repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/nats/src/main/java/com/netflix/conductor/contribs/queue/nats/config/NATSConfiguration.java
nats/src/main/java/com/netflix/conductor/contribs/queue/nats/config/NATSConfiguration.java
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.contribs.queue.nats.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import com.netflix.conductor.core.events.EventQueueProvider; import rx.Scheduler; @Configuration @ConditionalOnProperty(name = "conductor.event-queues.nats.enabled", havingValue = "true") public class NATSConfiguration { @Bean public EventQueueProvider natsEventQueueProvider(Environment environment, Scheduler scheduler) { return new NATSEventQueueProvider(environment, scheduler); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/test/java/com/netflix/conductor/redis/lock/RedisLockTest.java
redis-lock/src/test/java/com/netflix/conductor/redis/lock/RedisLockTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.lock; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.redisson.Redisson; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.testcontainers.containers.*; import com.netflix.conductor.redislock.config.RedisLockProperties; import com.netflix.conductor.redislock.config.RedisLockProperties.REDIS_SERVER_TYPE; import com.netflix.conductor.redislock.lock.RedisLock; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RedisLockTest { private static RedisLock redisLock; private static Config config; private static RedissonClient redisson; static GenericContainer redis = new GenericContainer("redis:5.0.3-alpine").withExposedPorts(6379); @BeforeClass public static void setUp() throws Exception { redis.start(); int port = redis.getFirstMappedPort(); String host = redis.getHost(); String testServerAddress = "redis://" + host + ":" + port; RedisLockProperties properties = mock(RedisLockProperties.class); when(properties.getServerType()).thenReturn(REDIS_SERVER_TYPE.SINGLE); when(properties.getServerAddress()).thenReturn(testServerAddress); when(properties.getServerMasterName()).thenReturn("master"); when(properties.getNamespace()).thenReturn(""); when(properties.isIgnoreLockingExceptions()).thenReturn(false); Config redissonConfig = new Config(); redissonConfig.useSingleServer().setAddress(testServerAddress).setTimeout(10000); redisLock = new RedisLock((Redisson) Redisson.create(redissonConfig), properties); // Create another instance of redisson for tests. RedisLockTest.config = new Config(); RedisLockTest.config.useSingleServer().setAddress(testServerAddress).setTimeout(10000); redisson = Redisson.create(RedisLockTest.config); } @AfterClass public static void tearDown() { redis.stop(); } @Test public void testLocking() { redisson.getKeys().flushall(); String lockId = "abcd-1234"; assertTrue(redisLock.acquireLock(lockId, 1000, 1000, TimeUnit.MILLISECONDS)); } @Test public void testLockExpiration() throws InterruptedException { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 1000, TimeUnit.MILLISECONDS); assertTrue(isLocked); Thread.sleep(2000); RLock lock = redisson.getLock(lockId); assertFalse(lock.isLocked()); } @Test public void testLockReentry() throws InterruptedException { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 60000, TimeUnit.MILLISECONDS); assertTrue(isLocked); Thread.sleep(1000); // get the lock back isLocked = redisLock.acquireLock(lockId, 1000, 1000, TimeUnit.MILLISECONDS); assertTrue(isLocked); RLock lock = redisson.getLock(lockId); assertTrue(isLocked); } @Test public void testReleaseLock() { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 10000, TimeUnit.MILLISECONDS); assertTrue(isLocked); redisLock.releaseLock(lockId); RLock lock = redisson.getLock(lockId); assertFalse(lock.isLocked()); } @Test public void testLockReleaseAndAcquire() throws InterruptedException { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 10000, TimeUnit.MILLISECONDS); assertTrue(isLocked); redisLock.releaseLock(lockId); Worker worker1 = new Worker(redisLock, lockId); worker1.start(); worker1.join(); assertTrue(worker1.isLocked); } @Test public void testLockingDuplicateThreads() throws InterruptedException { redisson.getKeys().flushall(); String lockId = "abcd-1234"; Worker worker1 = new Worker(redisLock, lockId); Worker worker2 = new Worker(redisLock, lockId); worker1.start(); worker2.start(); worker1.join(); worker2.join(); // Ensure only one of them had got the lock. assertFalse(worker1.isLocked && worker2.isLocked); assertTrue(worker1.isLocked || worker2.isLocked); } @Test public void testDuplicateLockAcquireFailure() throws InterruptedException { redisson.getKeys().flushall(); String lockId = "abcd-1234"; Worker worker1 = new Worker(redisLock, lockId, 100L, 60000L); worker1.start(); worker1.join(); boolean isLocked = redisLock.acquireLock(lockId, 500L, 1000L, TimeUnit.MILLISECONDS); // Ensure only one of them had got the lock. assertFalse(isLocked); assertTrue(worker1.isLocked); } @Test public void testReacquireLostKey() { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 10000, TimeUnit.MILLISECONDS); assertTrue(isLocked); // Delete key from the cluster to reacquire // Simulating the case when cluster goes down and possibly loses some keys. redisson.getKeys().flushall(); isLocked = redisLock.acquireLock(lockId, 100, 10000, TimeUnit.MILLISECONDS); assertTrue(isLocked); } @Test public void testReleaseLockTwice() { redisson.getKeys().flushall(); String lockId = "abcd-1234"; boolean isLocked = redisLock.acquireLock(lockId, 1000, 10000, TimeUnit.MILLISECONDS); assertTrue(isLocked); redisLock.releaseLock(lockId); redisLock.releaseLock(lockId); } private static class Worker extends Thread { private final RedisLock lock; private final String lockID; boolean isLocked; private Long timeToTry = 50L; private Long leaseTime = 1000L; Worker(RedisLock lock, String lockID) { super("TestWorker-" + lockID); this.lock = lock; this.lockID = lockID; } Worker(RedisLock lock, String lockID, Long timeToTry, Long leaseTime) { super("TestWorker-" + lockID); this.lock = lock; this.lockID = lockID; this.timeToTry = timeToTry; this.leaseTime = leaseTime; } @Override public void run() { isLocked = lock.acquireLock(lockID, timeToTry, leaseTime, TimeUnit.MILLISECONDS); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/test/java/com/netflix/conductor/redislock/config/RedisHealthIndicatorTest.java
redis-lock/src/test/java/com/netflix/conductor/redislock/config/RedisHealthIndicatorTest.java
/* * Copyright 2025 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redislock.config; import java.util.concurrent.TimeUnit; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.redisson.api.RedissonClient; import org.redisson.redisnode.RedissonClusterNodes; import org.redisson.redisnode.RedissonSentinelMasterSlaveNodes; import org.redisson.redisnode.RedissonSingleNode; import org.springframework.boot.actuate.health.Health; import org.springframework.test.context.junit4.SpringRunner; import static com.netflix.conductor.redislock.config.RedisLockProperties.REDIS_SERVER_TYPE.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.when; @RunWith(SpringRunner.class) public class RedisHealthIndicatorTest { @Mock private RedissonClient redissonClient; @Test public void shouldReturnAsHealthWhenServerTypeIsSingle() { // Given a Redisson client var redisProperties = new RedisLockProperties(); redisProperties.setServerType(SINGLE); // And its mocks var redisNode = Mockito.mock(RedissonSingleNode.class); when(redissonClient.getRedisNodes(any())).thenReturn(redisNode); when(redisNode.pingAll(anyLong(), any(TimeUnit.class))).thenReturn(true); // When execute a health indicator var actualHealth = new RedisHealthIndicator(redissonClient, redisProperties); // Then should return as health assertThat(actualHealth.health()).isEqualTo(Health.up().build()); } @Test public void shouldReturnAsHealthWhenServerTypeIsCluster() { // Given a Redisson client var redisProperties = new RedisLockProperties(); redisProperties.setServerType(CLUSTER); // And its mocks var redisNode = Mockito.mock(RedissonClusterNodes.class); when(redissonClient.getRedisNodes(any())).thenReturn(redisNode); when(redisNode.pingAll(anyLong(), any(TimeUnit.class))).thenReturn(true); // When execute a health indicator var actualHealth = new RedisHealthIndicator(redissonClient, redisProperties); // Then should return as health assertThat(actualHealth.health()).isEqualTo(Health.up().build()); } @Test public void shouldReturnAsHealthWhenServerTypeIsSentinel() { // Given a Redisson client var redisProperties = new RedisLockProperties(); redisProperties.setServerType(SENTINEL); // And its mocks var redisNode = Mockito.mock(RedissonSentinelMasterSlaveNodes.class); when(redissonClient.getRedisNodes(any())).thenReturn(redisNode); when(redisNode.pingAll(anyLong(), any(TimeUnit.class))).thenReturn(true); // When execute a health indicator var actualHealth = new RedisHealthIndicator(redissonClient, redisProperties); // Then should return as health assertThat(actualHealth.health()).isEqualTo(Health.up().build()); } @Test public void shouldReturnAsUnhealthyWhenAnyServerIsDown() { // Given a Redisson client var redisProperties = new RedisLockProperties(); redisProperties.setServerType(SINGLE); // And its mocks var redisNode = Mockito.mock(RedissonSingleNode.class); when(redissonClient.getRedisNodes(any())).thenReturn(redisNode); when(redisNode.pingAll(anyLong(), any(TimeUnit.class))).thenReturn(false); // When execute a health indicator var actualHealth = new RedisHealthIndicator(redissonClient, redisProperties); // Then should return as unhealthy assertThat(actualHealth.health()).isEqualTo(Health.down().build()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisHealthIndicator.java
redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisHealthIndicator.java
/* * Copyright 2025 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redislock.config; import org.redisson.api.RedissonClient; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; import static java.util.concurrent.TimeUnit.SECONDS; import static org.redisson.api.redisnode.RedisNodes.*; @Component @ConditionalOnProperty(name = "management.health.redis.enabled", havingValue = "true") public class RedisHealthIndicator implements HealthIndicator { private final RedissonClient redisClient; private final RedisLockProperties redisProperties; public RedisHealthIndicator(RedissonClient redisClient, RedisLockProperties redisProperties) { this.redisClient = redisClient; this.redisProperties = redisProperties; } @Override public Health health() { return isHealth() ? Health.up().build() : Health.down().build(); } private boolean isHealth() { switch (redisProperties.getServerType()) { case SINGLE -> { return redisClient.getRedisNodes(SINGLE).pingAll(5, SECONDS); } case CLUSTER -> { return redisClient.getRedisNodes(CLUSTER).pingAll(5, SECONDS); } case SENTINEL -> { return redisClient.getRedisNodes(SENTINEL_MASTER_SLAVE).pingAll(5, SECONDS); } default -> { return false; } } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisLockConfiguration.java
redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisLockConfiguration.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redislock.config; import java.util.Arrays; import org.redisson.Redisson; import org.redisson.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.conductor.core.sync.Lock; import com.netflix.conductor.redislock.config.RedisLockProperties.REDIS_SERVER_TYPE; import com.netflix.conductor.redislock.lock.RedisLock; @Configuration @EnableConfigurationProperties(RedisLockProperties.class) @ConditionalOnProperty(name = "conductor.workflow-execution-lock.type", havingValue = "redis") public class RedisLockConfiguration { private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockConfiguration.class); @Bean public Redisson getRedisson(RedisLockProperties properties) { RedisLockProperties.REDIS_SERVER_TYPE redisServerType; try { redisServerType = properties.getServerType(); } catch (IllegalArgumentException ie) { final String message = "Invalid Redis server type: " + properties.getServerType() + ", supported values are: " + Arrays.toString(REDIS_SERVER_TYPE.values()); LOGGER.error(message); throw new RuntimeException(message, ie); } String redisServerAddress = properties.getServerAddress(); String redisServerUsername = properties.getServerUsername(); String redisServerPassword = properties.getServerPassword(); String masterName = properties.getServerMasterName(); Config redisConfig = new Config(); if (properties.getNumNettyThreads() != null && properties.getNumNettyThreads() > 0) { redisConfig.setNettyThreads(properties.getNumNettyThreads()); } int connectionTimeout = 10000; switch (redisServerType) { case SINGLE: LOGGER.info("Setting up Redis Single Server for RedisLockConfiguration"); redisConfig .useSingleServer() .setAddress(redisServerAddress) .setUsername(redisServerUsername) .setPassword(redisServerPassword) .setTimeout(connectionTimeout) .setDnsMonitoringInterval(properties.getDnsMonitoringInterval()); break; case CLUSTER: LOGGER.info("Setting up Redis Cluster for RedisLockConfiguration"); redisConfig .useClusterServers() .setScanInterval(2000) // cluster state scan interval in milliseconds .addNodeAddress(redisServerAddress.split(",")) .setUsername(redisServerUsername) .setPassword(redisServerPassword) .setTimeout(connectionTimeout) .setSlaveConnectionMinimumIdleSize( properties.getClusterReplicaConnectionMinIdleSize()) .setSlaveConnectionPoolSize( properties.getClusterReplicaConnectionPoolSize()) .setMasterConnectionMinimumIdleSize( properties.getClusterPrimaryConnectionMinIdleSize()) .setMasterConnectionPoolSize( properties.getClusterPrimaryConnectionPoolSize()) .setDnsMonitoringInterval(properties.getDnsMonitoringInterval()); break; case SENTINEL: LOGGER.info("Setting up Redis Sentinel Servers for RedisLockConfiguration"); redisConfig .useSentinelServers() .setScanInterval(2000) .setMasterName(masterName) .addSentinelAddress(redisServerAddress) .setUsername(redisServerUsername) .setPassword(redisServerPassword) .setTimeout(connectionTimeout) .setDnsMonitoringInterval(properties.getDnsMonitoringInterval()); break; } return (Redisson) Redisson.create(redisConfig); } @Bean public Lock provideLock(Redisson redisson, RedisLockProperties properties) { return new RedisLock(redisson, properties); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisLockProperties.java
redis-lock/src/main/java/com/netflix/conductor/redislock/config/RedisLockProperties.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redislock.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("conductor.redis-lock") public class RedisLockProperties { /** The redis server configuration to be used. */ private REDIS_SERVER_TYPE serverType = REDIS_SERVER_TYPE.SINGLE; /** The address of the redis server following format -- host:port */ private String serverAddress = "redis://127.0.0.1:6379"; /** The username for redis authentication (Redis 6+). Default to null when not needed. */ private String serverUsername = null; /** The password for redis authentication */ private String serverPassword = null; /** The master server name used by Redis Sentinel servers and master change monitoring task */ private String serverMasterName = "master"; /** The namespace to use to prepend keys used for locking in redis */ private String namespace = ""; /** The number of natty threads to use */ private Integer numNettyThreads; /** If using Cluster Mode, you can use this to set num of min idle connections for replica */ private int clusterReplicaConnectionMinIdleSize = 24; /** If using Cluster Mode, you can use this to set num of min idle connections for replica */ private int clusterReplicaConnectionPoolSize = 64; /** If using Cluster Mode, you can use this to set num of min idle connections for replica */ private int clusterPrimaryConnectionMinIdleSize = 24; /** If using Cluster Mode, you can use this to set num of min idle connections for replica */ private int clusterPrimaryConnectionPoolSize = 64; /** * Enable to otionally continue without a lock to not block executions until the locking service * becomes available */ private boolean ignoreLockingExceptions = false; /** Interval in milliseconds to check the endpoint's DNS (Set -1 to disable). */ private long dnsMonitoringInterval = 5000L; public REDIS_SERVER_TYPE getServerType() { return serverType; } public void setServerType(REDIS_SERVER_TYPE serverType) { this.serverType = serverType; } public String getServerAddress() { return serverAddress; } public void setServerAddress(String serverAddress) { this.serverAddress = serverAddress; } public String getServerUsername() { return serverUsername; } public void setServerUsername(String serverUsername) { this.serverUsername = serverUsername; } public String getServerPassword() { return serverPassword; } public void setServerPassword(String serverPassword) { this.serverPassword = serverPassword; } public String getServerMasterName() { return serverMasterName; } public void setServerMasterName(String serverMasterName) { this.serverMasterName = serverMasterName; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public boolean isIgnoreLockingExceptions() { return ignoreLockingExceptions; } public void setIgnoreLockingExceptions(boolean ignoreLockingExceptions) { this.ignoreLockingExceptions = ignoreLockingExceptions; } public Integer getNumNettyThreads() { return numNettyThreads; } public void setNumNettyThreads(Integer numNettyThreads) { this.numNettyThreads = numNettyThreads; } public Integer getClusterReplicaConnectionMinIdleSize() { return clusterReplicaConnectionMinIdleSize; } public void setClusterReplicaConnectionMinIdleSize( Integer clusterReplicaConnectionMinIdleSize) { this.clusterReplicaConnectionMinIdleSize = clusterReplicaConnectionMinIdleSize; } public Integer getClusterReplicaConnectionPoolSize() { return clusterReplicaConnectionPoolSize; } public void setClusterReplicaConnectionPoolSize(Integer clusterReplicaConnectionPoolSize) { this.clusterReplicaConnectionPoolSize = clusterReplicaConnectionPoolSize; } public Integer getClusterPrimaryConnectionMinIdleSize() { return clusterPrimaryConnectionMinIdleSize; } public void setClusterPrimaryConnectionMinIdleSize( Integer clusterPrimaryConnectionMinIdleSize) { this.clusterPrimaryConnectionMinIdleSize = clusterPrimaryConnectionMinIdleSize; } public Integer getClusterPrimaryConnectionPoolSize() { return clusterPrimaryConnectionPoolSize; } public void setClusterPrimaryConnectionPoolSize(Integer clusterPrimaryConnectionPoolSize) { this.clusterPrimaryConnectionPoolSize = clusterPrimaryConnectionPoolSize; } public long getDnsMonitoringInterval() { return dnsMonitoringInterval; } public void setDnsMonitoringInterval(long dnsMonitoringInterval) { this.dnsMonitoringInterval = dnsMonitoringInterval; } public enum REDIS_SERVER_TYPE { SINGLE, CLUSTER, SENTINEL } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-lock/src/main/java/com/netflix/conductor/redislock/lock/RedisLock.java
redis-lock/src/main/java/com/netflix/conductor/redislock/lock/RedisLock.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redislock.lock; import java.util.concurrent.TimeUnit; import org.apache.commons.lang3.StringUtils; import org.redisson.Redisson; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.conductor.core.sync.Lock; import com.netflix.conductor.metrics.Monitors; import com.netflix.conductor.redislock.config.RedisLockProperties; public class RedisLock implements Lock { private static final Logger LOGGER = LoggerFactory.getLogger(RedisLock.class); private final RedisLockProperties properties; private final RedissonClient redisson; private static String LOCK_NAMESPACE = ""; public RedisLock(Redisson redisson, RedisLockProperties properties) { this.properties = properties; this.redisson = redisson; LOCK_NAMESPACE = properties.getNamespace(); } @Override public void acquireLock(String lockId) { RLock lock = redisson.getLock(parseLockId(lockId)); lock.lock(); } @Override public boolean acquireLock(String lockId, long timeToTry, TimeUnit unit) { RLock lock = redisson.getLock(parseLockId(lockId)); try { return lock.tryLock(timeToTry, unit); } catch (Exception e) { return handleAcquireLockFailure(lockId, e); } } /** * @param lockId resource to lock on * @param timeToTry blocks up to timeToTry duration in attempt to acquire the lock * @param leaseTime Lock lease expiration duration. Redisson default is -1, meaning it holds the * lock until explicitly unlocked. * @param unit time unit * @return */ @Override public boolean acquireLock(String lockId, long timeToTry, long leaseTime, TimeUnit unit) { RLock lock = redisson.getLock(parseLockId(lockId)); try { return lock.tryLock(timeToTry, leaseTime, unit); } catch (Exception e) { return handleAcquireLockFailure(lockId, e); } } @Override public void releaseLock(String lockId) { RLock lock = redisson.getLock(parseLockId(lockId)); try { lock.unlock(); } catch (IllegalMonitorStateException e) { // Releasing a lock twice using Redisson can cause this exception, which can be ignored. } } @Override public void deleteLock(String lockId) { // Noop for Redlock algorithm as releaseLock / unlock deletes it. } private String parseLockId(String lockId) { if (StringUtils.isEmpty(lockId)) { throw new IllegalArgumentException("lockId cannot be NULL or empty: lockId=" + lockId); } return LOCK_NAMESPACE + "." + lockId; } private boolean handleAcquireLockFailure(String lockId, Exception e) { LOGGER.error("Failed to acquireLock for lockId: {}", lockId, e); Monitors.recordAcquireLockFailure(e.getClass().getName()); // A Valid failure to acquire lock when another thread has acquired it returns false. // However, when an exception is thrown while acquiring lock, due to connection or others // issues, // we can optionally continue without a "lock" to not block executions until Locking service // is available. return properties.isIgnoreLockingExceptions(); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/tasks/TaskTest.java
common/src/test/java/com/netflix/conductor/common/tasks/TaskTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.tasks; import java.util.Arrays; import java.util.HashMap; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.ExecutionMetadata; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.Task.Status; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.protobuf.Any; import static org.junit.Assert.*; public class TaskTest { @Test public void test() { Task task = new Task(); task.setStatus(Status.FAILED); assertEquals(Status.FAILED, task.getStatus()); Set<String> resultStatues = Arrays.stream(TaskResult.Status.values()) .map(Enum::name) .collect(Collectors.toSet()); for (Status status : Status.values()) { if (resultStatues.contains(status.name())) { TaskResult.Status trStatus = TaskResult.Status.valueOf(status.name()); assertEquals(status.name(), trStatus.name()); task = new Task(); task.setStatus(status); assertEquals(status, task.getStatus()); } } } @Test public void testTaskDefinitionIfAvailable() { Task task = new Task(); task.setStatus(Status.FAILED); assertEquals(Status.FAILED, task.getStatus()); assertNull(task.getWorkflowTask()); assertFalse(task.getTaskDefinition().isPresent()); WorkflowTask workflowTask = new WorkflowTask(); TaskDef taskDefinition = new TaskDef(); workflowTask.setTaskDefinition(taskDefinition); task.setWorkflowTask(workflowTask); assertTrue(task.getTaskDefinition().isPresent()); assertEquals(taskDefinition, task.getTaskDefinition().get()); } @Test public void testTaskQueueWaitTime() { Task task = new Task(); long currentTimeMillis = System.currentTimeMillis(); task.setScheduledTime(currentTimeMillis - 30_000); // 30 seconds ago task.setStartTime(currentTimeMillis - 25_000); long queueWaitTime = task.getQueueWaitTime(); assertEquals(5000L, queueWaitTime); task.setUpdateTime(currentTimeMillis - 20_000); task.setCallbackAfterSeconds(10); queueWaitTime = task.getQueueWaitTime(); assertTrue(queueWaitTime > 0); } @Test public void testDeepCopyTask() { final Task task = new Task(); // In order to avoid forgetting putting inside the copy method the newly added fields check // the number of declared fields. final int expectedTaskFieldsNumber = 43; final int declaredFieldsNumber = task.getClass().getDeclaredFields().length; final ExecutionMetadata executionMetadata = new ExecutionMetadata(); executionMetadata.setServerSendTime(1000L); executionMetadata.setClientReceiveTime(2000L); executionMetadata.setExecutionStartTime(3000L); executionMetadata.setExecutionEndTime(4000L); executionMetadata.setClientSendTime(5000L); executionMetadata.setPollNetworkLatency(6000L); executionMetadata.setUpdateNetworkLatency(7000L); executionMetadata.setAdditionalContextMap(new HashMap<>()); assertEquals(expectedTaskFieldsNumber, declaredFieldsNumber); task.setCallbackAfterSeconds(111L); task.setCallbackFromWorker(false); task.setCorrelationId("correlation_id"); task.setInputData(new HashMap<>()); task.setOutputData(new HashMap<>()); task.setReferenceTaskName("ref_task_name"); task.setStartDelayInSeconds(1); task.setTaskDefName("task_def_name"); task.setTaskType("dummy_task_type"); task.setWorkflowInstanceId("workflowInstanceId"); task.setWorkflowType("workflowType"); task.setResponseTimeoutSeconds(11L); task.setStatus(Status.COMPLETED); task.setRetryCount(0); task.setPollCount(0); task.setTaskId("taskId"); task.setWorkflowTask(new WorkflowTask()); task.setDomain("domain"); task.setInputMessage(Any.getDefaultInstance()); task.setOutputMessage(Any.getDefaultInstance()); task.setRateLimitPerFrequency(11); task.setRateLimitFrequencyInSeconds(11); task.setExternalInputPayloadStoragePath("externalInputPayloadStoragePath"); task.setExternalOutputPayloadStoragePath("externalOutputPayloadStoragePath"); task.setWorkflowPriority(0); task.setIteration(1); task.setExecutionNameSpace("name_space"); task.setIsolationGroupId("groupId"); task.setStartTime(12L); task.setEndTime(20L); task.setScheduledTime(7L); task.setRetried(false); task.setReasonForIncompletion(""); task.setWorkerId(""); task.setSubWorkflowId(""); task.setSubworkflowChanged(false); task.setExecutionMetadata(executionMetadata); final Task copy = task.deepCopy(); assertEquals(task, copy); // Verify execution metadata is copied assertNotNull(copy.getExecutionMetadata()); assertEquals(Long.valueOf(1000L), copy.getOrCreateExecutionMetadata().getServerSendTime()); assertEquals( Long.valueOf(2000L), copy.getOrCreateExecutionMetadata().getClientReceiveTime()); assertEquals( Long.valueOf(3000L), copy.getOrCreateExecutionMetadata().getExecutionStartTime()); assertEquals( Long.valueOf(4000L), copy.getOrCreateExecutionMetadata().getExecutionEndTime()); assertEquals(Long.valueOf(5000L), copy.getOrCreateExecutionMetadata().getClientSendTime()); assertEquals( Long.valueOf(6000L), copy.getOrCreateExecutionMetadata().getPollNetworkLatency()); assertEquals( Long.valueOf(7000L), copy.getOrCreateExecutionMetadata().getUpdateNetworkLatency()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/tasks/TaskResultTest.java
common/src/test/java/com/netflix/conductor/common/tasks/TaskResultTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.tasks; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.TaskResult; import static org.junit.Assert.assertEquals; public class TaskResultTest { private Task task; private TaskResult taskResult; @Before public void setUp() { task = new Task(); task.setWorkflowInstanceId("workflow-id"); task.setTaskId("task-id"); task.setReasonForIncompletion("reason"); task.setCallbackAfterSeconds(10); task.setWorkerId("worker-id"); task.setOutputData(new HashMap<>()); task.setExternalOutputPayloadStoragePath("externalOutput"); } @Test public void testCanceledTask() { task.setStatus(Task.Status.CANCELED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.FAILED, taskResult.getStatus()); } @Test public void testCompletedWithErrorsTask() { task.setStatus(Task.Status.COMPLETED_WITH_ERRORS); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.FAILED, taskResult.getStatus()); } @Test public void testScheduledTask() { task.setStatus(Task.Status.SCHEDULED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.IN_PROGRESS, taskResult.getStatus()); } @Test public void testCompltetedTask() { task.setStatus(Task.Status.COMPLETED); taskResult = new TaskResult(task); validateTaskResult(); assertEquals(TaskResult.Status.COMPLETED, taskResult.getStatus()); } private void validateTaskResult() { assertEquals(task.getWorkflowInstanceId(), taskResult.getWorkflowInstanceId()); assertEquals(task.getTaskId(), taskResult.getTaskId()); assertEquals(task.getReasonForIncompletion(), taskResult.getReasonForIncompletion()); assertEquals(task.getCallbackAfterSeconds(), taskResult.getCallbackAfterSeconds()); assertEquals(task.getWorkerId(), taskResult.getWorkerId()); assertEquals(task.getOutputData(), taskResult.getOutputData()); assertEquals( task.getExternalOutputPayloadStoragePath(), taskResult.getExternalOutputPayloadStoragePath()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/tasks/TaskDefTest.java
common/src/test/java/com/netflix/conductor/common/tasks/TaskDefTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.tasks; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskDef; import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class TaskDefTest { private Validator validator; @Before public void setup() { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); this.validator = factory.getValidator(); } @Test public void test() { String name = "test1"; String description = "desc"; int retryCount = 10; int timeout = 100; TaskDef def = new TaskDef(name, description, retryCount, timeout); assertEquals(36_00, def.getResponseTimeoutSeconds()); assertEquals(name, def.getName()); assertEquals(description, def.getDescription()); assertEquals(retryCount, def.getRetryCount()); assertEquals(timeout, def.getTimeoutSeconds()); } @Test public void testTaskDef() { TaskDef taskDef = new TaskDef(); taskDef.setName("task1"); taskDef.setRetryCount(-1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1001); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.contains( "TaskDef: task1 responseTimeoutSeconds: 1001 must be less than timeoutSeconds: 1000")); assertTrue(validationErrors.contains("TaskDef retryCount: 0 must be >= 0")); assertTrue(validationErrors.contains("ownerEmail cannot be empty")); } @Test public void testTaskDefTotalTimeOutSeconds() { TaskDef taskDef = new TaskDef(); taskDef.setName("test-task"); taskDef.setRetryCount(1); taskDef.setTimeoutSeconds(1000); taskDef.setTotalTimeoutSeconds(900); taskDef.setResponseTimeoutSeconds(1); taskDef.setOwnerEmail("blah@gmail.com"); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.toString(), validationErrors.contains( "TaskDef: test-task timeoutSeconds: 1000 must be less than or equal to totalTimeoutSeconds: 900")); } @Test public void testTaskDefInvalidEmail() { TaskDef taskDef = new TaskDef(); taskDef.setName("test-task"); taskDef.setRetryCount(1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.toString(), validationErrors.contains("ownerEmail cannot be empty")); } @Test public void testTaskDefValidEmail() { TaskDef taskDef = new TaskDef(); taskDef.setName("test-task"); taskDef.setRetryCount(1); taskDef.setTimeoutSeconds(1000); taskDef.setResponseTimeoutSeconds(1); taskDef.setOwnerEmail("owner@test.com"); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(0, result.size()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/utils/SummaryUtilTest.java
common/src/test/java/com/netflix/conductor/common/utils/SummaryUtilTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.runner.ApplicationContextRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.jupiter.api.Assertions.assertEquals; @ContextConfiguration( classes = { TestObjectMapperConfiguration.class, SummaryUtilTest.SummaryUtilTestConfiguration.class }) @RunWith(SpringRunner.class) public class SummaryUtilTest { @Configuration static class SummaryUtilTestConfiguration { @Bean public SummaryUtil summaryUtil() { return new SummaryUtil(); } } @Autowired private ObjectMapper objectMapper; private Map<String, Object> testObject; @Before public void init() { Map<String, Object> child = new HashMap<>(); child.put("testStr", "childTestStr"); Map<String, Object> obj = new HashMap<>(); obj.put("testStr", "stringValue"); obj.put("testArray", new ArrayList<>(Arrays.asList(1, 2, 3))); obj.put("testObj", child); obj.put("testNull", null); testObject = obj; } @Test public void testSerializeInputOutput_defaultToString() throws Exception { new ApplicationContextRunner() .withPropertyValues( "conductor.app.summary-input-output-json-serialization.enabled:false") .withUserConfiguration(SummaryUtilTestConfiguration.class) .run( context -> { String serialized = SummaryUtil.serializeInputOutput(this.testObject); assertEquals( this.testObject.toString(), serialized, "The Java.toString() Serialization should match the serialized Test Object"); }); } @Test public void testSerializeInputOutput_jsonSerializationEnabled() throws Exception { new ApplicationContextRunner() .withPropertyValues( "conductor.app.summary-input-output-json-serialization.enabled:true") .withUserConfiguration(SummaryUtilTestConfiguration.class) .run( context -> { String serialized = SummaryUtil.serializeInputOutput(testObject); assertEquals( objectMapper.writeValueAsString(testObject), serialized, "The ObjectMapper Json Serialization should match the serialized Test Object"); }); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/utils/ConstraintParamUtilTest.java
common/src/test/java/com/netflix/conductor/common/utils/ConstraintParamUtilTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import static org.junit.Assert.assertEquals; public class ConstraintParamUtilTest { @Before public void before() { System.setProperty("NETFLIX_STACK", "test"); System.setProperty("NETFLIX_ENVIRONMENT", "test"); System.setProperty("TEST_ENV", "test"); } private WorkflowDef constructWorkflowDef() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); return workflowDef; } @Test public void testExtractParamPathComponents() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithValidJsonPath() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); WorkflowTask workflowTask_2 = new WorkflowTask(); workflowTask_2.setName("task_2"); workflowTask_2.setTaskReferenceName("task_2"); workflowTask_2.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${task_1.output.[\"task ref\"]}"); workflowTask_2.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_2", workflowDef); assertEquals(0, results.size()); } @Test public void testExtractParamPathComponentsWithInValidJsonPath() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); WorkflowTask workflowTask_2 = new WorkflowTask(); workflowTask_2.setName("task_2"); workflowTask_2.setTaskReferenceName("task_2"); workflowTask_2.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${task_1.output [\"task ref\"]}"); workflowTask_2.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_2", workflowDef); assertEquals(1, results.size()); } @Test public void testExtractParamPathComponentsWithMissingEnvVariable() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithValidEnvVariable() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithValidMap() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("NETFLIX_STACK", "${NETFLIX_STACK}"); envInputParam.put("NETFLIX_ENVIRONMENT", "${NETFLIX_ENVIRONMENT}"); envInputParam.put("TEST_ENV", "${TEST_ENV}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithInvalidEnv() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("TEST_ENV1", "${TEST_ENV1}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 1); } @Test public void testExtractParamPathComponentsWithInputParamEmpty() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", ""); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithListInputParamWithEmptyString() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", new String[] {""}); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithInputFieldWithSpace() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${workflow.input.status sta}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 1); } @Test public void testExtractParamPathComponentsWithPredefineEnums() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("NETFLIX_ENV", "${CPEWF_TASK_ID}"); inputParam.put( "entryPoint", "/tools/pdfwatermarker_mux.py ${NETFLIX_ENV} ${CPEWF_TASK_ID} alpha"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } @Test public void testExtractParamPathComponentsWithEscapedChar() { WorkflowDef workflowDef = constructWorkflowDef(); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "$${expression with spaces}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); List<String> results = ConstraintParamUtil.validateInputParam(inputParam, "task_1", workflowDef); assertEquals(results.size(), 0); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/constraints/NameValidatorTest.java
common/src/test/java/com/netflix/conductor/common/constraints/NameValidatorTest.java
/* * Copyright 2024 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import org.junit.Test; import org.springframework.test.util.ReflectionTestUtils; import jakarta.validation.ConstraintValidatorContext; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class NameValidatorTest { @Test public void nameWithAllowedCharactersIsValid() { ValidNameConstraint.NameValidator nameValidator = new ValidNameConstraint.NameValidator(); assertTrue(nameValidator.isValid("workflowDef", null)); } @Test public void nonAllowedCharactersInNameIsInvalid() { ValidNameConstraint.NameValidator nameValidator = new ValidNameConstraint.NameValidator(); ConstraintValidatorContext context = mock(ConstraintValidatorContext.class); ConstraintValidatorContext.ConstraintViolationBuilder builder = mock(ConstraintValidatorContext.ConstraintViolationBuilder.class); when(context.buildConstraintViolationWithTemplate(anyString())).thenReturn(builder); ReflectionTestUtils.setField(nameValidator, "nameValidationEnabled", true); assertFalse(nameValidator.isValid("workflowDef@", context)); } // Null should be tested by @NotEmpty or @NotNull @Test public void nullIsValid() { ValidNameConstraint.NameValidator nameValidator = new ValidNameConstraint.NameValidator(); assertTrue(nameValidator.isValid(null, null)); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/events/EventHandlerTest.java
common/src/test/java/com/netflix/conductor/common/events/EventHandlerTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.events; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.junit.Test; import com.netflix.conductor.common.metadata.events.EventHandler; import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class EventHandlerTest { @Test public void testWorkflowTaskName() { EventHandler taskDef = new EventHandler(); // name is null ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("Missing event handler name")); assertTrue(validationErrors.contains("Missing event location")); assertTrue( validationErrors.contains( "No actions specified. Please specify at-least one action")); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/run/TaskSummaryTest.java
common/src/test/java/com/netflix/conductor/common/run/TaskSummaryTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.Task; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.Assert.assertNotNull; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class TaskSummaryTest { @Autowired private ObjectMapper objectMapper; @Test public void testJsonSerializing() throws Exception { Task task = new Task(); TaskSummary taskSummary = new TaskSummary(task); String json = objectMapper.writeValueAsString(taskSummary); TaskSummary read = objectMapper.readValue(json, TaskSummary.class); assertNotNull(read); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java
common/src/test/java/com/netflix/conductor/common/config/TestObjectMapperConfiguration.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.databind.ObjectMapper; /** Supplies the standard Conductor {@link ObjectMapper} for tests that need them. */ @Configuration public class TestObjectMapperConfiguration { @Bean public ObjectMapper testObjectMapper() { return new ObjectMapperProvider().getObjectMapper(); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/workflow/SubWorkflowParamsTest.java
common/src/test/java/com/netflix/conductor/common/workflow/SubWorkflowParamsTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.workflow; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.SubWorkflowParams; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import static org.junit.Assert.assertEquals; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class SubWorkflowParamsTest { @Autowired private ObjectMapper objectMapper; @Test public void testWorkflowSetTaskToDomain() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); Map<String, String> taskToDomain = new HashMap<>(); taskToDomain.put("unit", "test"); subWorkflowParams.setTaskToDomain(taskToDomain); assertEquals(taskToDomain, subWorkflowParams.getTaskToDomain()); } @Test(expected = IllegalArgumentException.class) public void testSetWorkflowDefinition() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); subWorkflowParams.setWorkflowDefinition(new Object()); } @Test public void testGetWorkflowDef() { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); WorkflowDef def = new WorkflowDef(); def.setName("test_workflow"); def.setVersion(1); WorkflowTask task = new WorkflowTask(); task.setName("test_task"); task.setTaskReferenceName("t1"); def.getTasks().add(task); subWorkflowParams.setWorkflowDefinition(def); assertEquals(def, subWorkflowParams.getWorkflowDefinition()); } @Test public void testWorkflowDefJson() throws Exception { SubWorkflowParams subWorkflowParams = new SubWorkflowParams(); subWorkflowParams.setName("dummy-name"); WorkflowDef def = new WorkflowDef(); def.setName("test_workflow"); def.setVersion(1); WorkflowTask task = new WorkflowTask(); task.setName("test_task"); task.setTaskReferenceName("t1"); def.getTasks().add(task); subWorkflowParams.setWorkflowDefinition(def); objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY); objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); String serializedParams = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(subWorkflowParams); SubWorkflowParams deserializedParams = objectMapper.readValue(serializedParams, SubWorkflowParams.class); var x = (WorkflowDef) deserializedParams.getWorkflowDefinition(); assertEquals(def, x); var taskName = "taskName"; var subWorkflowName = "subwf"; TaskDef taskDef = new TaskDef(taskName); taskDef.setRetryCount(0); taskDef.setOwnerEmail("test@orkes.io"); WorkflowTask inline = new WorkflowTask(); inline.setTaskReferenceName(taskName); inline.setName(taskName); inline.setTaskDefinition(taskDef); inline.setWorkflowTaskType(TaskType.SIMPLE); inline.setInputParameters(Map.of("evaluatorType", "graaljs", "expression", "true;")); WorkflowDef subworkflowDef = new WorkflowDef(); subworkflowDef.setName(subWorkflowName); subworkflowDef.setOwnerEmail("test@orkes.io"); subworkflowDef.setInputParameters(Arrays.asList("value", "inlineValue")); subworkflowDef.setDescription("Sub Workflow to test retry"); subworkflowDef.setTimeoutSeconds(600); subworkflowDef.setTimeoutPolicy(WorkflowDef.TimeoutPolicy.TIME_OUT_WF); subworkflowDef.setTasks(Arrays.asList(inline)); // autowired var serializedSubWorkflowDef1 = objectMapper.writeValueAsString(subworkflowDef); var deserializedSubWorkflowDef1 = objectMapper.readValue(serializedSubWorkflowDef1, WorkflowDef.class); assertEquals(deserializedSubWorkflowDef1, subworkflowDef); // default ObjectMapper mapper = new ObjectMapper(); var serializedSubWorkflowDef2 = mapper.writeValueAsString(subworkflowDef); var deserializedSubWorkflowDef2 = mapper.readValue(serializedSubWorkflowDef2, WorkflowDef.class); assertEquals(deserializedSubWorkflowDef2, subworkflowDef); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/workflow/WorkflowTaskTest.java
common/src/test/java/com/netflix/conductor/common/workflow/WorkflowTaskTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.workflow; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.junit.Test; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; public class WorkflowTaskTest { @Test public void test() { WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setWorkflowTaskType(TaskType.DECISION); assertNotNull(workflowTask.getType()); assertEquals(TaskType.DECISION.name(), workflowTask.getType()); workflowTask = new WorkflowTask(); workflowTask.setWorkflowTaskType(TaskType.SWITCH); assertNotNull(workflowTask.getType()); assertEquals(TaskType.SWITCH.name(), workflowTask.getType()); } @Test public void testOptional() { WorkflowTask task = new WorkflowTask(); assertFalse(task.isOptional()); task.setOptional(Boolean.FALSE); assertFalse(task.isOptional()); task.setOptional(Boolean.TRUE); assertTrue(task.isOptional()); } @Test public void testWorkflowTaskName() { WorkflowTask taskDef = new WorkflowTask(); // name is null ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(taskDef); assertEquals(2, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("WorkflowTask name cannot be empty or null")); assertTrue( validationErrors.contains( "WorkflowTask taskReferenceName name cannot be empty or null")); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/test/java/com/netflix/conductor/common/workflow/WorkflowDefValidatorTest.java
common/src/test/java/com/netflix/conductor/common/workflow/WorkflowDefValidatorTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.workflow; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Test; import org.springframework.test.context.TestPropertySource; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import jakarta.validation.ConstraintViolation; import jakarta.validation.Validation; import jakarta.validation.Validator; import jakarta.validation.ValidatorFactory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @TestPropertySource(properties = "conductor.app.workflow.name-validation.enabled=true") public class WorkflowDefValidatorTest { @Before public void before() { System.setProperty("NETFLIX_STACK", "test"); System.setProperty("NETFLIX_ENVIRONMENT", "test"); System.setProperty("TEST_ENV", "test"); } @Test public void testWorkflowDefConstraints() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(3, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("WorkflowDef name cannot be null or empty")); assertTrue(validationErrors.contains("WorkflowTask list cannot be empty")); assertTrue(validationErrors.contains("ownerEmail cannot be empty")); // assertTrue(validationErrors.contains("workflowDef schemaVersion: 1 should be >= 2")); } @Test public void testWorkflowDefConstraintsWithMultipleEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); inputParam.put( "entryPoint", "${NETFLIX_ENVIRONMENT} ${NETFLIX_STACK} ${CPEWF_TASK_ID} ${workflow.input.status}"); workflowTask_1.setInputParameters(inputParam); WorkflowTask workflowTask_2 = new WorkflowTask(); workflowTask_2.setName("task_2"); workflowTask_2.setTaskReferenceName("task_2"); workflowTask_2.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam2 = new HashMap<>(); inputParam2.put("env", inputParam); workflowTask_2.setInputParameters(inputParam2); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); tasks.add(workflowTask_2); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsSingleEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsDualEnvVariable() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowDefConstraintsWithMapAsInputParam() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask_1 = new WorkflowTask(); workflowTask_1.setName("task_1"); workflowTask_1.setTaskReferenceName("task_1"); workflowTask_1.setType(TaskType.TASK_TYPE_SIMPLE); Map<String, Object> inputParam = new HashMap<>(); inputParam.put("taskId", "${CPEWF_TASK_ID} ${NETFLIX_STACK}"); Map<String, Object> envInputParam = new HashMap<>(); envInputParam.put("packageId", "${workflow.input.packageId}"); envInputParam.put("taskId", "${CPEWF_TASK_ID}"); envInputParam.put("NETFLIX_STACK", "${NETFLIX_STACK}"); envInputParam.put("NETFLIX_ENVIRONMENT", "${NETFLIX_ENVIRONMENT}"); inputParam.put("env", envInputParam); workflowTask_1.setInputParameters(inputParam); List<WorkflowTask> tasks = new ArrayList<>(); tasks.add(workflowTask_1); workflowDef.setTasks(tasks); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowTaskInputParamInvalid() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", "${workflow.input.Space Value}"); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue( validationErrors.contains( "key: blabla input parameter value: workflow.input.Space Value is not valid")); } @Test public void testWorkflowTaskEmptyStringInputParamValue() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowTasklistInputParamWithEmptyString() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(2); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); // name is null workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); map.put("foo", new String[] {""}); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowSchemaVersion1() { WorkflowDef workflowDef = new WorkflowDef(); // name is null workflowDef.setSchemaVersion(3); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(1, result.size()); List<String> validationErrors = new ArrayList<>(); result.forEach(e -> validationErrors.add(e.getMessage())); assertTrue(validationErrors.contains("workflowDef schemaVersion: 2 is only supported")); } @Test public void testWorkflowOwnerInvalidEmail() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } @Test public void testWorkflowOwnerValidEmail() { WorkflowDef workflowDef = new WorkflowDef(); workflowDef.setName("test_env"); workflowDef.setOwnerEmail("owner@test.com"); WorkflowTask workflowTask = new WorkflowTask(); workflowTask.setName("t1"); workflowTask.setWorkflowTaskType(TaskType.SIMPLE); workflowTask.setTaskReferenceName("t1"); Map<String, Object> map = new HashMap<>(); map.put("blabla", ""); workflowTask.setInputParameters(map); workflowDef.getTasks().add(workflowTask); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> result = validator.validate(workflowDef); assertEquals(0, result.size()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoMessage.java
common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoMessage.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoMessage annotates a given Java class so it becomes exposed via the GRPC API as a native * Protocol Buffers struct. The annotated class must be a POJO. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ProtoMessage { /** * Sets whether the generated mapping code will contain a helper to translate the POJO for this * class into the equivalent ProtoBuf object. * * @return whether this class will generate a mapper to ProtoBuf objects */ boolean toProto() default true; /** * Sets whether the generated mapping code will contain a helper to translate the ProtoBuf * object for this class into the equivalent POJO. * * @return whether this class will generate a mapper from ProtoBuf objects */ boolean fromProto() default true; /** * Sets whether this is a wrapper class that will be used to encapsulate complex nested type * interfaces. Wrapper classes are not directly exposed by the ProtoBuf API and must be mapped * manually. * * @return whether this is a wrapper class */ boolean wrapper() default false; }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoField.java
common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoField.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoField annotates a field inside an struct with metadata on how to expose it on its * corresponding Protocol Buffers struct. For a field to be exposed in a ProtoBuf struct, the * containing struct must also be annotated with a {@link ProtoMessage} or {@link ProtoEnum} tag. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface ProtoField { /** * Mandatory. Sets the Protocol Buffer ID for this specific field. Once a field has been * annotated with a given ID, the ID can never change to a different value or the resulting * Protocol Buffer struct will not be backwards compatible. * * @return the numeric ID for the field */ int id(); }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoEnum.java
common/src/main/java/com/netflix/conductor/annotations/protogen/ProtoEnum.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotations.protogen; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ProtoEnum annotates an enum type that will be exposed via the GRPC API as a native Protocol * Buffers enum. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface ProtoEnum {}
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/validation/ValidationError.java
common/src/main/java/com/netflix/conductor/common/validation/ValidationError.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.validation; import java.util.StringJoiner; /** Captures a validation error that can be returned in {@link ErrorResponse}. */ public class ValidationError { private String path; private String message; private String invalidValue; public ValidationError() {} public ValidationError(String path, String message, String invalidValue) { this.path = path; this.message = message; this.invalidValue = invalidValue; } public String getPath() { return path; } public String getMessage() { return message; } public String getInvalidValue() { return invalidValue; } public void setPath(String path) { this.path = path; } public void setMessage(String message) { this.message = message; } public void setInvalidValue(String invalidValue) { this.invalidValue = invalidValue; } @Override public String toString() { return new StringJoiner(", ", ValidationError.class.getSimpleName() + "[", "]") .add("path='" + path + "'") .add("message='" + message + "'") .add("invalidValue='" + invalidValue + "'") .toString(); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/validation/ErrorResponse.java
common/src/main/java/com/netflix/conductor/common/validation/ErrorResponse.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.validation; import java.util.List; import java.util.Map; public class ErrorResponse { private int status; private String code; private String message; private String instance; private boolean retryable; private List<ValidationError> validationErrors; private Map<String, Object> metadata; public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public List<ValidationError> getValidationErrors() { return validationErrors; } public void setValidationErrors(List<ValidationError> validationErrors) { this.validationErrors = validationErrors; } public boolean isRetryable() { return retryable; } public void setRetryable(boolean retryable) { this.retryable = retryable; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getInstance() { return instance; } public void setInstance(String instance) { this.instance = instance; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/SchemaDef.java
common/src/main/java/com/netflix/conductor/common/metadata/SchemaDef.java
/* * Copyright 2024 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @EqualsAndHashCode(callSuper = true) @Builder @Data @NoArgsConstructor @AllArgsConstructor @ProtoMessage public class SchemaDef extends Auditable { @ProtoEnum public enum Type { JSON, AVRO, PROTOBUF } @ProtoField(id = 1) @NotNull private String name; @ProtoField(id = 2) @NotNull @Builder.Default private int version = 1; @ProtoField(id = 3) @NotNull private Type type; // Schema definition stored here private Map<String, Object> data; // Externalized schema definition (eg. via AVRO, Protobuf registry) // If using Orkes Schema registry, this points to the name of the schema in the registry private String externalRef; }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/Auditable.java
common/src/main/java/com/netflix/conductor/common/metadata/Auditable.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata; public abstract class Auditable { private String ownerApp; private Long createTime; private Long updateTime; private String createdBy; private String updatedBy; /** * @return the ownerApp */ public String getOwnerApp() { return ownerApp; } /** * @param ownerApp the ownerApp to set */ public void setOwnerApp(String ownerApp) { this.ownerApp = ownerApp; } /** * @return the createTime */ public Long getCreateTime() { return createTime == null ? 0 : createTime; } /** * @param createTime the createTime to set */ public void setCreateTime(Long createTime) { this.createTime = createTime; } /** * @return the updateTime */ public Long getUpdateTime() { return updateTime == null ? 0 : updateTime; } /** * @param updateTime the updateTime to set */ public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } /** * @return the createdBy */ public String getCreatedBy() { return createdBy; } /** * @param createdBy the createdBy to set */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * @return the updatedBy */ public String getUpdatedBy() { return updatedBy; } /** * @param updatedBy the updatedBy to set */ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/BaseDef.java
common/src/main/java/com/netflix/conductor/common/metadata/BaseDef.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata; import java.util.Collections; import java.util.EnumMap; import java.util.Map; import com.netflix.conductor.common.metadata.acl.Permission; /** * A base class for {@link com.netflix.conductor.common.metadata.workflow.WorkflowDef} and {@link * com.netflix.conductor.common.metadata.tasks.TaskDef}. */ @Deprecated public abstract class BaseDef extends Auditable { private final Map<Permission, String> accessPolicy = new EnumMap<>(Permission.class); public void addPermission(Permission permission, String allowedAuthority) { this.accessPolicy.put(permission, allowedAuthority); } public void addPermissionIfAbsent(Permission permission, String allowedAuthority) { this.accessPolicy.putIfAbsent(permission, allowedAuthority); } public void removePermission(Permission permission) { this.accessPolicy.remove(permission); } public String getAllowedAuthority(Permission permission) { return this.accessPolicy.get(permission); } public void clearAccessPolicy() { this.accessPolicy.clear(); } public Map<Permission, String> getAccessPolicy() { return Collections.unmodifiableMap(this.accessPolicy); } public void setAccessPolicy(Map<Permission, String> accessPolicy) { this.accessPolicy.putAll(accessPolicy); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskExecLog.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskExecLog.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; /** Model that represents the task's execution log. */ @ProtoMessage public class TaskExecLog { @ProtoField(id = 1) private String log; @ProtoField(id = 2) private String taskId; @ProtoField(id = 3) private long createdTime; public TaskExecLog() {} public TaskExecLog(String log) { this.log = log; this.createdTime = System.currentTimeMillis(); } /** * @return Task Exec Log */ public String getLog() { return log; } /** * @param log The Log */ public void setLog(String log) { this.log = log; } /** * @return the taskId */ public String getTaskId() { return taskId; } /** * @param taskId the taskId to set */ public void setTaskId(String taskId) { this.taskId = taskId; } /** * @return the createdTime */ public long getCreatedTime() { return createdTime; } /** * @param createdTime the createdTime to set */ public void setCreatedTime(long createdTime) { this.createdTime = createdTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaskExecLog that = (TaskExecLog) o; return createdTime == that.createdTime && Objects.equals(log, that.log) && Objects.equals(taskId, that.taskId); } @Override public int hashCode() { return Objects.hash(log, taskId, createdTime); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/PollData.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/PollData.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; @ProtoMessage public class PollData { @ProtoField(id = 1) private String queueName; @ProtoField(id = 2) private String domain; @ProtoField(id = 3) private String workerId; @ProtoField(id = 4) private long lastPollTime; public PollData() { super(); } public PollData(String queueName, String domain, String workerId, long lastPollTime) { super(); this.queueName = queueName; this.domain = domain; this.workerId = workerId; this.lastPollTime = lastPollTime; } public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = domain; } public String getWorkerId() { return workerId; } public void setWorkerId(String workerId) { this.workerId = workerId; } public long getLastPollTime() { return lastPollTime; } public void setLastPollTime(long lastPollTime) { this.lastPollTime = lastPollTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PollData pollData = (PollData) o; return getLastPollTime() == pollData.getLastPollTime() && Objects.equals(getQueueName(), pollData.getQueueName()) && Objects.equals(getDomain(), pollData.getDomain()) && Objects.equals(getWorkerId(), pollData.getWorkerId()); } @Override public int hashCode() { return Objects.hash(getQueueName(), getDomain(), getWorkerId(), getLastPollTime()); } @Override public String toString() { return "PollData{" + "queueName='" + queueName + '\'' + ", domain='" + domain + '\'' + ", workerId='" + workerId + '\'' + ", lastPollTime=" + lastPollTime + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/ExecutionMetadata.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/ExecutionMetadata.java
/* * Copyright 2025 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.HashMap; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; /** * Execution metadata for capturing NEW operational metadata not already present in Task/TaskResult * models. Contains enhanced timing measurements and additional context for operational purposes. */ @ProtoMessage public class ExecutionMetadata { // Direct timing fields @ProtoField(id = 1) private Long serverSendTime; @ProtoField(id = 2) private Long clientReceiveTime; @ProtoField(id = 3) private Long executionStartTime; @ProtoField(id = 4) private Long executionEndTime; @ProtoField(id = 5) private Long clientSendTime; @ProtoField(id = 6) private Long pollNetworkLatency; @ProtoField(id = 7) private Long updateNetworkLatency; // Additional context as Map for flexibility @ProtoField(id = 8) private Map<String, Object> additionalContext = new HashMap<>(); public ExecutionMetadata() {} // ============ TIMING METHODS ============ /** Sets server send time */ public void setServerSendTime(long timestamp) { this.serverSendTime = timestamp; } /** Sets client receive time */ public void setClientReceiveTime(long timestamp) { this.clientReceiveTime = timestamp; } /** Sets execution start time */ public void setExecutionStartTime(long timestamp) { this.executionStartTime = timestamp; } /** Sets execution end time */ public void setExecutionEndTime(long timestamp) { this.executionEndTime = timestamp; } /** Sets client send time */ public void setClientSendTime(long timestamp) { this.clientSendTime = timestamp; } /** Sets poll network latency */ public void setPollNetworkLatency(long latencyMs) { this.pollNetworkLatency = latencyMs; } /** Sets update network latency */ public void setUpdateNetworkLatency(long latencyMs) { this.updateNetworkLatency = latencyMs; } /** Gets server send time */ public Long getServerSendTime() { return serverSendTime; } /** Gets client receive time */ public Long getClientReceiveTime() { return clientReceiveTime; } /** Gets execution start time */ public Long getExecutionStartTime() { return executionStartTime; } /** Gets execution end time */ public Long getExecutionEndTime() { return executionEndTime; } /** Gets client send time */ public Long getClientSendTime() { return clientSendTime; } /** Gets poll network latency */ public Long getPollNetworkLatency() { return pollNetworkLatency; } /** Gets update network latency */ public Long getUpdateNetworkLatency() { return updateNetworkLatency; } /** Calculates total execution time */ public Long getExecutionDuration() { if (executionStartTime != null && executionEndTime != null) { return executionEndTime - executionStartTime; } return null; } // ============ ADDITIONAL CONTEXT METHODS ============ /** Sets additional context data */ public void setAdditionalContext(String key, Object value) { additionalContext.put(key, value); } /** Gets additional context data */ public Object getAdditionalContext(String key) { return additionalContext.get(key); } /** Gets the additional context map (for protogen compatibility) */ public Map<String, Object> getAdditionalContext() { return additionalContext; } // ============ GETTERS AND SETTERS ============ public void setServerSendTime(Long serverSendTime) { this.serverSendTime = serverSendTime; } public void setClientReceiveTime(Long clientReceiveTime) { this.clientReceiveTime = clientReceiveTime; } public void setExecutionStartTime(Long executionStartTime) { this.executionStartTime = executionStartTime; } public void setExecutionEndTime(Long executionEndTime) { this.executionEndTime = executionEndTime; } public void setClientSendTime(Long clientSendTime) { this.clientSendTime = clientSendTime; } public void setPollNetworkLatency(Long pollNetworkLatency) { this.pollNetworkLatency = pollNetworkLatency; } public void setUpdateNetworkLatency(Long updateNetworkLatency) { this.updateNetworkLatency = updateNetworkLatency; } public Map<String, Object> getAdditionalContextMap() { return additionalContext; } public void setAdditionalContextMap(Map<String, Object> additionalContext) { this.additionalContext = additionalContext != null ? additionalContext : new HashMap<>(); } /** Sets the additional context map (for protogen compatibility) */ public void setAdditionalContext(Map<String, Object> additionalContext) { this.additionalContext = additionalContext != null ? additionalContext : new HashMap<>(); } /** Checks if this ExecutionMetadata has any meaningful data */ public boolean hasData() { return serverSendTime != null || clientReceiveTime != null || executionStartTime != null || executionEndTime != null || clientSendTime != null || pollNetworkLatency != null || updateNetworkLatency != null || (additionalContext != null && !additionalContext.isEmpty()); } /** Checks if this ExecutionMetadata is completely empty (used by protobuf serialization) */ public boolean isEmpty() { return !hasData(); } @Override public String toString() { return "ExecutionMetadata{" + "serverSendTime=" + serverSendTime + ", clientReceiveTime=" + clientReceiveTime + ", executionStartTime=" + executionStartTime + ", executionEndTime=" + executionEndTime + ", clientSendTime=" + clientSendTime + ", pollNetworkLatency=" + pollNetworkLatency + ", updateNetworkLatency=" + updateNetworkLatency + ", additionalContext=" + additionalContext + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskResult.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskResult.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.google.protobuf.Any; import io.swagger.v3.oas.annotations.Hidden; import jakarta.validation.constraints.NotEmpty; /** Result of the task execution. */ @ProtoMessage public class TaskResult { @ProtoEnum public enum Status { IN_PROGRESS, FAILED, FAILED_WITH_TERMINAL_ERROR, COMPLETED } @NotEmpty(message = "Workflow Id cannot be null or empty") @ProtoField(id = 1) private String workflowInstanceId; @NotEmpty(message = "Task ID cannot be null or empty") @ProtoField(id = 2) private String taskId; @ProtoField(id = 3) private String reasonForIncompletion; @ProtoField(id = 4) private long callbackAfterSeconds; @ProtoField(id = 5) private String workerId; @ProtoField(id = 6) private Status status; @ProtoField(id = 7) private Map<String, Object> outputData = new HashMap<>(); @ProtoField(id = 8) @Hidden private Any outputMessage; @ProtoField(id = 9) private ExecutionMetadata executionMetadata; private List<TaskExecLog> logs = new CopyOnWriteArrayList<>(); private String externalOutputPayloadStoragePath; private String subWorkflowId; private boolean extendLease; public TaskResult(Task task) { this.workflowInstanceId = task.getWorkflowInstanceId(); this.taskId = task.getTaskId(); this.reasonForIncompletion = task.getReasonForIncompletion(); this.callbackAfterSeconds = task.getCallbackAfterSeconds(); this.workerId = task.getWorkerId(); this.outputData = task.getOutputData(); // Only copy ExecutionMetadata if the task actually has one (to avoid creating empty ones) if (task.hasExecutionMetadata()) { this.executionMetadata = task.getExecutionMetadata(); } this.externalOutputPayloadStoragePath = task.getExternalOutputPayloadStoragePath(); this.subWorkflowId = task.getSubWorkflowId(); switch (task.getStatus()) { case CANCELED: case COMPLETED_WITH_ERRORS: case TIMED_OUT: case SKIPPED: this.status = Status.FAILED; break; case SCHEDULED: this.status = Status.IN_PROGRESS; break; default: this.status = Status.valueOf(task.getStatus().name()); break; } } public TaskResult() {} /** * @return Workflow instance id for which the task result is produced */ public String getWorkflowInstanceId() { return workflowInstanceId; } public void setWorkflowInstanceId(String workflowInstanceId) { this.workflowInstanceId = workflowInstanceId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getReasonForIncompletion() { return reasonForIncompletion; } public void setReasonForIncompletion(String reasonForIncompletion) { this.reasonForIncompletion = StringUtils.substring(reasonForIncompletion, 0, 500); } public long getCallbackAfterSeconds() { return callbackAfterSeconds; } /** * When set to non-zero values, the task remains in the queue for the specified seconds before * sent back to the worker when polled. Useful for the long running task, where the task is * updated as IN_PROGRESS and should not be polled out of the queue for a specified amount of * time. (delayed queue implementation) * * @param callbackAfterSeconds Amount of time in seconds the task should be held in the queue * before giving it to a polling worker. */ public void setCallbackAfterSeconds(long callbackAfterSeconds) { this.callbackAfterSeconds = callbackAfterSeconds; } public String getWorkerId() { return workerId; } /** * @param workerId a free form string identifying the worker host. Could be hostname, IP Address * or any other meaningful identifier that can help identify the host/process which executed * the task, in case of troubleshooting. */ public void setWorkerId(String workerId) { this.workerId = workerId; } /** * @return the status */ public Status getStatus() { return status; } /** * @param status Status of the task * <p><b>IN_PROGRESS</b>: Use this for long running tasks, indicating the task is still in * progress and should be checked again at a later time. e.g. the worker checks the status * of the job in the DB, while the job is being executed by another process. * <p><b>FAILED, FAILED_WITH_TERMINAL_ERROR, COMPLETED</b>: Terminal statuses for the task. * Use FAILED_WITH_TERMINAL_ERROR when you do not want the task to be retried. * @see #setCallbackAfterSeconds(long) */ public void setStatus(Status status) { this.status = status; } public Map<String, Object> getOutputData() { return outputData; } /** * @param outputData output data to be set for the task execution result */ public void setOutputData(Map<String, Object> outputData) { this.outputData = outputData; } /** * Adds output * * @param key output field * @param value value * @return current instance */ public TaskResult addOutputData(String key, Object value) { this.outputData.put(key, value); return this; } public Any getOutputMessage() { return outputMessage; } public void setOutputMessage(Any outputMessage) { this.outputMessage = outputMessage; } /** * @return Task execution logs */ public List<TaskExecLog> getLogs() { return logs; } /** * @param logs Task execution logs */ public void setLogs(List<TaskExecLog> logs) { this.logs = logs; } /** * @param log Log line to be added * @return Instance of TaskResult */ public TaskResult log(String log) { this.logs.add(new TaskExecLog(log)); return this; } /** * @return the path where the task output is stored in external storage */ public String getExternalOutputPayloadStoragePath() { return externalOutputPayloadStoragePath; } /** * @param externalOutputPayloadStoragePath path in the external storage where the task output is * stored */ public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) { this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath; } public String getSubWorkflowId() { return subWorkflowId; } public void setSubWorkflowId(String subWorkflowId) { this.subWorkflowId = subWorkflowId; } public boolean isExtendLease() { return extendLease; } public void setExtendLease(boolean extendLease) { this.extendLease = extendLease; } /** * @return the execution metadata containing timing, worker context, and other operational data. * Returns null if no execution metadata has been explicitly set or used. */ public ExecutionMetadata getExecutionMetadata() { // Only return ExecutionMetadata if it exists and has data if (executionMetadata != null && executionMetadata.hasData()) { return executionMetadata; } return null; } /** * @return the execution metadata, creating it if it doesn't exist (for setting timing data) */ public ExecutionMetadata getOrCreateExecutionMetadata() { if (executionMetadata == null) { executionMetadata = new ExecutionMetadata(); } return executionMetadata; } /** * @param executionMetadata the execution metadata to set */ public void setExecutionMetadata(ExecutionMetadata executionMetadata) { this.executionMetadata = executionMetadata; } @Override public String toString() { return "TaskResult{" + "workflowInstanceId='" + workflowInstanceId + '\'' + ", taskId='" + taskId + '\'' + ", reasonForIncompletion='" + reasonForIncompletion + '\'' + ", callbackAfterSeconds=" + callbackAfterSeconds + ", workerId='" + workerId + '\'' + ", status=" + status + ", outputData=" + outputData + ", outputMessage=" + outputMessage + ", logs=" + logs + ", executionMetadata=" + executionMetadata + ", externalOutputPayloadStoragePath='" + externalOutputPayloadStoragePath + '\'' + ", subWorkflowId='" + subWorkflowId + '\'' + ", extendLease='" + extendLease + '\'' + '}'; } public static TaskResult complete() { return newTaskResult(Status.COMPLETED); } public static TaskResult failed() { return newTaskResult(Status.FAILED); } public static TaskResult failed(String failureReason) { TaskResult result = newTaskResult(Status.FAILED); result.setReasonForIncompletion(failureReason); return result; } public static TaskResult inProgress() { return newTaskResult(Status.IN_PROGRESS); } public static TaskResult newTaskResult(Status status) { TaskResult result = new TaskResult(); result.setStatus(status); return result; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskDef.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskDef.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.constraints.OwnerEmailMandatoryConstraint; import com.netflix.conductor.common.constraints.TaskTimeoutConstraint; import com.netflix.conductor.common.metadata.Auditable; import com.netflix.conductor.common.metadata.SchemaDef; import jakarta.validation.Valid; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; @ProtoMessage @TaskTimeoutConstraint @Valid public class TaskDef extends Auditable { @ProtoEnum public enum TimeoutPolicy { RETRY, TIME_OUT_WF, ALERT_ONLY } @ProtoEnum public enum RetryLogic { FIXED, EXPONENTIAL_BACKOFF, LINEAR_BACKOFF } public static final int ONE_HOUR = 60 * 60; /** Unique name identifying the task. The name is unique across */ @NotEmpty(message = "TaskDef name cannot be null or empty") @ProtoField(id = 1) private String name; @ProtoField(id = 2) private String description; @ProtoField(id = 3) @Min(value = 0, message = "TaskDef retryCount: {value} must be >= 0") private int retryCount = 3; // Default @ProtoField(id = 4) @NotNull private long timeoutSeconds; @ProtoField(id = 5) private List<String> inputKeys = new ArrayList<>(); @ProtoField(id = 6) private List<String> outputKeys = new ArrayList<>(); @ProtoField(id = 7) private TimeoutPolicy timeoutPolicy = TimeoutPolicy.TIME_OUT_WF; @ProtoField(id = 8) private RetryLogic retryLogic = RetryLogic.FIXED; @ProtoField(id = 9) private int retryDelaySeconds = 60; @ProtoField(id = 10) @Min( value = 1, message = "TaskDef responseTimeoutSeconds: ${validatedValue} should be minimum {value} second") private long responseTimeoutSeconds = ONE_HOUR; @ProtoField(id = 11) private Integer concurrentExecLimit; @ProtoField(id = 12) private Map<String, Object> inputTemplate = new HashMap<>(); // This field is deprecated, do not use id 13. // @ProtoField(id = 13) // private Integer rateLimitPerSecond; @ProtoField(id = 14) private Integer rateLimitPerFrequency; @ProtoField(id = 15) private Integer rateLimitFrequencyInSeconds; @ProtoField(id = 16) private String isolationGroupId; @ProtoField(id = 17) private String executionNameSpace; @ProtoField(id = 18) @OwnerEmailMandatoryConstraint private String ownerEmail; @ProtoField(id = 19) @Min(value = 0, message = "TaskDef pollTimeoutSeconds: {value} must be >= 0") private Integer pollTimeoutSeconds; @ProtoField(id = 20) @Min(value = 1, message = "Backoff scale factor. Applicable for LINEAR_BACKOFF") private Integer backoffScaleFactor = 1; @ProtoField(id = 21) private String baseType; @ProtoField(id = 22) @NotNull private long totalTimeoutSeconds; private SchemaDef inputSchema; private SchemaDef outputSchema; private boolean enforceSchema; public TaskDef() {} public TaskDef(String name) { this.name = name; } public TaskDef(String name, String description) { this.name = name; this.description = description; } public TaskDef(String name, String description, int retryCount, long timeoutSeconds) { this.name = name; this.description = description; this.retryCount = retryCount; this.timeoutSeconds = timeoutSeconds; } public TaskDef( String name, String description, String ownerEmail, int retryCount, long timeoutSeconds, long responseTimeoutSeconds) { this.name = name; this.description = description; this.ownerEmail = ownerEmail; this.retryCount = retryCount; this.timeoutSeconds = timeoutSeconds; this.responseTimeoutSeconds = responseTimeoutSeconds; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the retryCount */ public int getRetryCount() { return retryCount; } /** * @param retryCount the retryCount to set */ public void setRetryCount(int retryCount) { this.retryCount = retryCount; } /** * @return the timeoutSeconds */ public long getTimeoutSeconds() { return timeoutSeconds; } /** * @param timeoutSeconds the timeoutSeconds to set */ public void setTimeoutSeconds(long timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; } /** * @return Returns the input keys */ public List<String> getInputKeys() { return inputKeys; } /** * @param inputKeys Set of keys that the task accepts in the input map */ public void setInputKeys(List<String> inputKeys) { this.inputKeys = inputKeys; } /** * @return Returns the output keys for the task when executed */ public List<String> getOutputKeys() { return outputKeys; } /** * @param outputKeys Sets the output keys */ public void setOutputKeys(List<String> outputKeys) { this.outputKeys = outputKeys; } /** * @return the timeoutPolicy */ public TimeoutPolicy getTimeoutPolicy() { return timeoutPolicy; } /** * @param timeoutPolicy the timeoutPolicy to set */ public void setTimeoutPolicy(TimeoutPolicy timeoutPolicy) { this.timeoutPolicy = timeoutPolicy; } /** * @return the retryLogic */ public RetryLogic getRetryLogic() { return retryLogic; } /** * @param retryLogic the retryLogic to set */ public void setRetryLogic(RetryLogic retryLogic) { this.retryLogic = retryLogic; } /** * @return the retryDelaySeconds */ public int getRetryDelaySeconds() { return retryDelaySeconds; } /** * @return the timeout for task to send response. After this timeout, the task will be re-queued */ public long getResponseTimeoutSeconds() { return responseTimeoutSeconds; } /** * @param responseTimeoutSeconds - timeout for task to send response. After this timeout, the * task will be re-queued */ public void setResponseTimeoutSeconds(long responseTimeoutSeconds) { this.responseTimeoutSeconds = responseTimeoutSeconds; } /** * @param retryDelaySeconds the retryDelaySeconds to set */ public void setRetryDelaySeconds(int retryDelaySeconds) { this.retryDelaySeconds = retryDelaySeconds; } /** * @return the inputTemplate */ public Map<String, Object> getInputTemplate() { return inputTemplate; } /** * @return rateLimitPerFrequency The max number of tasks that will be allowed to be executed per * rateLimitFrequencyInSeconds. */ public Integer getRateLimitPerFrequency() { return rateLimitPerFrequency == null ? 0 : rateLimitPerFrequency; } /** * @param rateLimitPerFrequency The max number of tasks that will be allowed to be executed per * rateLimitFrequencyInSeconds. Setting the value to 0 removes the rate limit */ public void setRateLimitPerFrequency(Integer rateLimitPerFrequency) { this.rateLimitPerFrequency = rateLimitPerFrequency; } /** * @return rateLimitFrequencyInSeconds: The time bucket that is used to rate limit tasks based * on {@link #getRateLimitPerFrequency()} If null or not set, then defaults to 1 second */ public Integer getRateLimitFrequencyInSeconds() { return rateLimitFrequencyInSeconds == null ? 1 : rateLimitFrequencyInSeconds; } /** * @param rateLimitFrequencyInSeconds: The time window/bucket for which the rate limit needs to * be applied. This will only have affect if {@link #getRateLimitPerFrequency()} is greater * than zero */ public void setRateLimitFrequencyInSeconds(Integer rateLimitFrequencyInSeconds) { this.rateLimitFrequencyInSeconds = rateLimitFrequencyInSeconds; } /** * @param concurrentExecLimit Limit of number of concurrent task that can be IN_PROGRESS at a * given time. Seting the value to 0 removes the limit. */ public void setConcurrentExecLimit(Integer concurrentExecLimit) { this.concurrentExecLimit = concurrentExecLimit; } /** * @return Limit of number of concurrent task that can be IN_PROGRESS at a given time */ public Integer getConcurrentExecLimit() { return concurrentExecLimit; } /** * @return concurrency limit */ public int concurrencyLimit() { return concurrentExecLimit == null ? 0 : concurrentExecLimit; } /** * @param inputTemplate the inputTemplate to set */ public void setInputTemplate(Map<String, Object> inputTemplate) { this.inputTemplate = inputTemplate; } public String getIsolationGroupId() { return isolationGroupId; } public void setIsolationGroupId(String isolationGroupId) { this.isolationGroupId = isolationGroupId; } public String getExecutionNameSpace() { return executionNameSpace; } public void setExecutionNameSpace(String executionNameSpace) { this.executionNameSpace = executionNameSpace; } /** * @return the email of the owner of this task definition */ public String getOwnerEmail() { return ownerEmail; } /** * @param ownerEmail the owner email to set */ public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } /** * @param pollTimeoutSeconds the poll timeout to set */ public void setPollTimeoutSeconds(Integer pollTimeoutSeconds) { this.pollTimeoutSeconds = pollTimeoutSeconds; } /** * @return the poll timeout of this task definition */ public Integer getPollTimeoutSeconds() { return pollTimeoutSeconds; } /** * @param backoffScaleFactor the backoff rate to set */ public void setBackoffScaleFactor(Integer backoffScaleFactor) { this.backoffScaleFactor = backoffScaleFactor; } /** * @return the backoff rate of this task definition */ public Integer getBackoffScaleFactor() { return backoffScaleFactor; } public String getBaseType() { return baseType; } public void setBaseType(String baseType) { this.baseType = baseType; } public SchemaDef getInputSchema() { return inputSchema; } public void setInputSchema(SchemaDef inputSchema) { this.inputSchema = inputSchema; } public SchemaDef getOutputSchema() { return outputSchema; } public void setOutputSchema(SchemaDef outputSchema) { this.outputSchema = outputSchema; } public boolean isEnforceSchema() { return enforceSchema; } public void setEnforceSchema(boolean enforceSchema) { this.enforceSchema = enforceSchema; } public long getTotalTimeoutSeconds() { return totalTimeoutSeconds; } public void setTotalTimeoutSeconds(long totalTimeoutSeconds) { this.totalTimeoutSeconds = totalTimeoutSeconds; } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaskDef taskDef = (TaskDef) o; return getRetryCount() == taskDef.getRetryCount() && getTimeoutSeconds() == taskDef.getTimeoutSeconds() && getRetryDelaySeconds() == taskDef.getRetryDelaySeconds() && getBackoffScaleFactor() == taskDef.getBackoffScaleFactor() && getResponseTimeoutSeconds() == taskDef.getResponseTimeoutSeconds() && Objects.equals(getName(), taskDef.getName()) && Objects.equals(getDescription(), taskDef.getDescription()) && Objects.equals(getInputKeys(), taskDef.getInputKeys()) && Objects.equals(getOutputKeys(), taskDef.getOutputKeys()) && getTimeoutPolicy() == taskDef.getTimeoutPolicy() && getRetryLogic() == taskDef.getRetryLogic() && Objects.equals(getConcurrentExecLimit(), taskDef.getConcurrentExecLimit()) && Objects.equals(getRateLimitPerFrequency(), taskDef.getRateLimitPerFrequency()) && Objects.equals(getInputTemplate(), taskDef.getInputTemplate()) && Objects.equals(getIsolationGroupId(), taskDef.getIsolationGroupId()) && Objects.equals(getExecutionNameSpace(), taskDef.getExecutionNameSpace()) && Objects.equals(getOwnerEmail(), taskDef.getOwnerEmail()) && Objects.equals(getBaseType(), taskDef.getBaseType()) && Objects.equals(getInputSchema(), taskDef.getInputSchema()) && Objects.equals(getOutputSchema(), taskDef.getOutputSchema()) && Objects.equals(getTotalTimeoutSeconds(), taskDef.getTotalTimeoutSeconds()); } @Override public int hashCode() { return Objects.hash( getName(), getDescription(), getRetryCount(), getTimeoutSeconds(), getInputKeys(), getOutputKeys(), getTimeoutPolicy(), getRetryLogic(), getRetryDelaySeconds(), getBackoffScaleFactor(), getResponseTimeoutSeconds(), getConcurrentExecLimit(), getRateLimitPerFrequency(), getInputTemplate(), getIsolationGroupId(), getExecutionNameSpace(), getOwnerEmail(), getBaseType(), getInputSchema(), getOutputSchema(), getTotalTimeoutSeconds()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/Task.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.google.protobuf.Any; import io.swagger.v3.oas.annotations.Hidden; @ProtoMessage public class Task { @ProtoEnum public enum Status { IN_PROGRESS(false, true, true), CANCELED(true, false, false), FAILED(true, false, true), FAILED_WITH_TERMINAL_ERROR( true, false, false), // No retries even if retries are configured, the task and the related // workflow should be terminated COMPLETED(true, true, true), COMPLETED_WITH_ERRORS(true, true, true), SCHEDULED(false, true, true), TIMED_OUT(true, false, true), SKIPPED(true, true, false); private final boolean terminal; private final boolean successful; private final boolean retriable; Status(boolean terminal, boolean successful, boolean retriable) { this.terminal = terminal; this.successful = successful; this.retriable = retriable; } public boolean isTerminal() { return terminal; } public boolean isSuccessful() { return successful; } public boolean isRetriable() { return retriable; } } @ProtoField(id = 1) private String taskType; @ProtoField(id = 2) private Status status; @ProtoField(id = 3) private Map<String, Object> inputData = new HashMap<>(); @ProtoField(id = 4) private String referenceTaskName; @ProtoField(id = 5) private int retryCount; @ProtoField(id = 6) private int seq; @ProtoField(id = 7) private String correlationId; @ProtoField(id = 8) private int pollCount; @ProtoField(id = 9) private String taskDefName; /** Time when the task was scheduled */ @ProtoField(id = 10) private long scheduledTime; /** Time when the task was first polled */ @ProtoField(id = 11) private long startTime; /** Time when the task completed executing */ @ProtoField(id = 12) private long endTime; /** Time when the task was last updated */ @ProtoField(id = 13) private long updateTime; @ProtoField(id = 14) private int startDelayInSeconds; @ProtoField(id = 15) private String retriedTaskId; @ProtoField(id = 16) private boolean retried; @ProtoField(id = 17) private boolean executed; @ProtoField(id = 18) private boolean callbackFromWorker = true; @ProtoField(id = 19) private long responseTimeoutSeconds; @ProtoField(id = 20) private String workflowInstanceId; @ProtoField(id = 21) private String workflowType; @ProtoField(id = 22) private String taskId; @ProtoField(id = 23) private String reasonForIncompletion; @ProtoField(id = 24) private long callbackAfterSeconds; @ProtoField(id = 25) private String workerId; @ProtoField(id = 26) private Map<String, Object> outputData = new HashMap<>(); @ProtoField(id = 27) private WorkflowTask workflowTask; @ProtoField(id = 28) private String domain; @ProtoField(id = 29) @Hidden private Any inputMessage; @ProtoField(id = 30) @Hidden private Any outputMessage; // id 31 is reserved @ProtoField(id = 32) private int rateLimitPerFrequency; @ProtoField(id = 33) private int rateLimitFrequencyInSeconds; @ProtoField(id = 34) private String externalInputPayloadStoragePath; @ProtoField(id = 35) private String externalOutputPayloadStoragePath; @ProtoField(id = 36) private int workflowPriority; @ProtoField(id = 37) private String executionNameSpace; @ProtoField(id = 38) private String isolationGroupId; @ProtoField(id = 40) private int iteration; @ProtoField(id = 41) private String subWorkflowId; /** * Use to note that a sub workflow associated with SUB_WORKFLOW task has an action performed on * it directly. */ @ProtoField(id = 42) private boolean subworkflowChanged; @ProtoField(id = 43) private long firstStartTime; @ProtoField(id = 44) private ExecutionMetadata executionMetadata; // If the task is an event associated with a parent task, the id of the parent task private String parentTaskId; public Task() {} /** * @return Type of the task * @see TaskType */ public String getTaskType() { return taskType; } public void setTaskType(String taskType) { this.taskType = taskType; } /** * @return Status of the task */ public Status getStatus() { return status; } /** * @param status Status of the task */ public void setStatus(Status status) { this.status = status; } public Map<String, Object> getInputData() { return inputData; } public void setInputData(Map<String, Object> inputData) { if (inputData == null) { inputData = new HashMap<>(); } this.inputData = inputData; } /** * @return the referenceTaskName */ public String getReferenceTaskName() { return referenceTaskName; } /** * @param referenceTaskName the referenceTaskName to set */ public void setReferenceTaskName(String referenceTaskName) { this.referenceTaskName = referenceTaskName; } /** * @return the correlationId */ public String getCorrelationId() { return correlationId; } /** * @param correlationId the correlationId to set */ public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } /** * @return the retryCount */ public int getRetryCount() { return retryCount; } /** * @param retryCount the retryCount to set */ public void setRetryCount(int retryCount) { this.retryCount = retryCount; } /** * @return the scheduledTime */ public long getScheduledTime() { return scheduledTime; } /** * @param scheduledTime the scheduledTime to set */ public void setScheduledTime(long scheduledTime) { this.scheduledTime = scheduledTime; } /** * @return the startTime */ public long getStartTime() { return startTime; } /** * @param startTime the startTime to set */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * @return the endTime */ public long getEndTime() { return endTime; } /** * @param endTime the endTime to set */ public void setEndTime(long endTime) { this.endTime = endTime; } /** * @return the startDelayInSeconds */ public int getStartDelayInSeconds() { return startDelayInSeconds; } /** * @param startDelayInSeconds the startDelayInSeconds to set */ public void setStartDelayInSeconds(int startDelayInSeconds) { this.startDelayInSeconds = startDelayInSeconds; } /** * @return the retriedTaskId */ public String getRetriedTaskId() { return retriedTaskId; } /** * @param retriedTaskId the retriedTaskId to set */ public void setRetriedTaskId(String retriedTaskId) { this.retriedTaskId = retriedTaskId; } /** * @return the seq */ public int getSeq() { return seq; } /** * @param seq the seq to set */ public void setSeq(int seq) { this.seq = seq; } /** * @return the updateTime */ public long getUpdateTime() { return updateTime; } /** * @param updateTime the updateTime to set */ public void setUpdateTime(long updateTime) { this.updateTime = updateTime; } /** * @return the queueWaitTime */ public long getQueueWaitTime() { if (this.startTime > 0 && this.scheduledTime > 0) { if (this.updateTime > 0 && getCallbackAfterSeconds() > 0) { long waitTime = System.currentTimeMillis() - (this.updateTime + (getCallbackAfterSeconds() * 1000)); return waitTime > 0 ? waitTime : 0; } else { return this.startTime - this.scheduledTime; } } return 0L; } /** * @return True if the task has been retried after failure */ public boolean isRetried() { return retried; } /** * @param retried the retried to set */ public void setRetried(boolean retried) { this.retried = retried; } /** * @return True if the task has completed its lifecycle within conductor (from start to * completion to being updated in the datastore) */ public boolean isExecuted() { return executed; } /** * @param executed the executed value to set */ public void setExecuted(boolean executed) { this.executed = executed; } /** * @return No. of times task has been polled */ public int getPollCount() { return pollCount; } public void setPollCount(int pollCount) { this.pollCount = pollCount; } public void incrementPollCount() { ++this.pollCount; } public boolean isCallbackFromWorker() { return callbackFromWorker; } public void setCallbackFromWorker(boolean callbackFromWorker) { this.callbackFromWorker = callbackFromWorker; } /** * @return Name of the task definition */ public String getTaskDefName() { if (taskDefName == null || "".equals(taskDefName)) { taskDefName = taskType; } return taskDefName; } /** * @param taskDefName Name of the task definition */ public void setTaskDefName(String taskDefName) { this.taskDefName = taskDefName; } /** * @return the timeout for task to send response. After this timeout, the task will be re-queued */ public long getResponseTimeoutSeconds() { return responseTimeoutSeconds; } /** * @param responseTimeoutSeconds - timeout for task to send response. After this timeout, the * task will be re-queued */ public void setResponseTimeoutSeconds(long responseTimeoutSeconds) { this.responseTimeoutSeconds = responseTimeoutSeconds; } /** * @return the workflowInstanceId */ public String getWorkflowInstanceId() { return workflowInstanceId; } /** * @param workflowInstanceId the workflowInstanceId to set */ public void setWorkflowInstanceId(String workflowInstanceId) { this.workflowInstanceId = workflowInstanceId; } public String getWorkflowType() { return workflowType; } /** * @param workflowType the name of the workflow * @return the task object with the workflow type set */ public com.netflix.conductor.common.metadata.tasks.Task setWorkflowType(String workflowType) { this.workflowType = workflowType; return this; } /** * @return the taskId */ public String getTaskId() { return taskId; } /** * @param taskId the taskId to set */ public void setTaskId(String taskId) { this.taskId = taskId; } /** * @return the reasonForIncompletion */ public String getReasonForIncompletion() { return reasonForIncompletion; } /** * @param reasonForIncompletion the reasonForIncompletion to set */ public void setReasonForIncompletion(String reasonForIncompletion) { this.reasonForIncompletion = StringUtils.substring(reasonForIncompletion, 0, 500); } /** * @return the callbackAfterSeconds */ public long getCallbackAfterSeconds() { return callbackAfterSeconds; } /** * @param callbackAfterSeconds the callbackAfterSeconds to set */ public void setCallbackAfterSeconds(long callbackAfterSeconds) { this.callbackAfterSeconds = callbackAfterSeconds; } /** * @return the workerId */ public String getWorkerId() { return workerId; } /** * @param workerId the workerId to set */ public void setWorkerId(String workerId) { this.workerId = workerId; } /** * @return the outputData */ public Map<String, Object> getOutputData() { return outputData; } /** * @param outputData the outputData to set */ public void setOutputData(Map<String, Object> outputData) { if (outputData == null) { outputData = new HashMap<>(); } this.outputData = outputData; } /** * @return Workflow Task definition */ public WorkflowTask getWorkflowTask() { return workflowTask; } /** * @param workflowTask Task definition */ public void setWorkflowTask(WorkflowTask workflowTask) { this.workflowTask = workflowTask; } /** * @return the domain */ public String getDomain() { return domain; } /** * @param domain the Domain */ public void setDomain(String domain) { this.domain = domain; } public Any getInputMessage() { return inputMessage; } public void setInputMessage(Any inputMessage) { this.inputMessage = inputMessage; } public Any getOutputMessage() { return outputMessage; } public void setOutputMessage(Any outputMessage) { this.outputMessage = outputMessage; } /** * @return {@link Optional} containing the task definition if available */ public Optional<TaskDef> getTaskDefinition() { return Optional.ofNullable(this.getWorkflowTask()).map(WorkflowTask::getTaskDefinition); } public int getRateLimitPerFrequency() { return rateLimitPerFrequency; } public void setRateLimitPerFrequency(int rateLimitPerFrequency) { this.rateLimitPerFrequency = rateLimitPerFrequency; } public int getRateLimitFrequencyInSeconds() { return rateLimitFrequencyInSeconds; } public void setRateLimitFrequencyInSeconds(int rateLimitFrequencyInSeconds) { this.rateLimitFrequencyInSeconds = rateLimitFrequencyInSeconds; } /** * @return the external storage path for the task input payload */ public String getExternalInputPayloadStoragePath() { return externalInputPayloadStoragePath; } /** * @param externalInputPayloadStoragePath the external storage path where the task input payload * is stored */ public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; } /** * @return the external storage path for the task output payload */ public String getExternalOutputPayloadStoragePath() { return externalOutputPayloadStoragePath; } /** * @param externalOutputPayloadStoragePath the external storage path where the task output * payload is stored */ public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) { this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath; } public void setIsolationGroupId(String isolationGroupId) { this.isolationGroupId = isolationGroupId; } public String getIsolationGroupId() { return isolationGroupId; } public String getExecutionNameSpace() { return executionNameSpace; } public void setExecutionNameSpace(String executionNameSpace) { this.executionNameSpace = executionNameSpace; } /** * @return the iteration */ public int getIteration() { return iteration; } /** * @param iteration iteration */ public void setIteration(int iteration) { this.iteration = iteration; } public boolean isLoopOverTask() { return iteration > 0; } /** * @return the priority defined on workflow */ public int getWorkflowPriority() { return workflowPriority; } /** * @param workflowPriority Priority defined for workflow */ public void setWorkflowPriority(int workflowPriority) { this.workflowPriority = workflowPriority; } public boolean isSubworkflowChanged() { return subworkflowChanged; } public void setSubworkflowChanged(boolean subworkflowChanged) { this.subworkflowChanged = subworkflowChanged; } public String getSubWorkflowId() { // For backwards compatibility if (StringUtils.isNotBlank(subWorkflowId)) { return subWorkflowId; } else { return this.getOutputData() != null && this.getOutputData().get("subWorkflowId") != null ? (String) this.getOutputData().get("subWorkflowId") : this.getInputData() != null ? (String) this.getInputData().get("subWorkflowId") : null; } } public void setSubWorkflowId(String subWorkflowId) { this.subWorkflowId = subWorkflowId; // For backwards compatibility if (this.getOutputData() != null && this.getOutputData().containsKey("subWorkflowId")) { this.getOutputData().put("subWorkflowId", subWorkflowId); } } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public long getFirstStartTime() { return firstStartTime; } public void setFirstStartTime(long firstStartTime) { this.firstStartTime = firstStartTime; } /** * @return the execution metadata containing timing, worker context, and other operational data. * Returns null if no execution metadata has been explicitly set or used. */ public ExecutionMetadata getExecutionMetadata() { // Only return ExecutionMetadata if it exists and has data if (executionMetadata != null && executionMetadata.hasData()) { return executionMetadata; } return null; } /** * @return the execution metadata, creating it if it doesn't exist (for setting timing data) */ public ExecutionMetadata getOrCreateExecutionMetadata() { if (executionMetadata == null) { executionMetadata = new ExecutionMetadata(); } return executionMetadata; } /** * @return the execution metadata only if it has data, null otherwise (for protobuf * serialization) */ public ExecutionMetadata getExecutionMetadataIfHasData() { if (executionMetadata != null && executionMetadata.hasData()) { return executionMetadata; } return null; } /** * @return true if the task has execution metadata (without creating it) */ public boolean hasExecutionMetadata() { return executionMetadata != null; } /** * @param executionMetadata the execution metadata to set */ public void setExecutionMetadata(ExecutionMetadata executionMetadata) { this.executionMetadata = executionMetadata; } public Task copy() { Task copy = new Task(); copy.setCallbackAfterSeconds(callbackAfterSeconds); copy.setCallbackFromWorker(callbackFromWorker); copy.setCorrelationId(correlationId); copy.setInputData(inputData); copy.setOutputData(outputData); copy.setReferenceTaskName(referenceTaskName); copy.setStartDelayInSeconds(startDelayInSeconds); copy.setTaskDefName(taskDefName); copy.setTaskType(taskType); copy.setWorkflowInstanceId(workflowInstanceId); copy.setWorkflowType(workflowType); copy.setResponseTimeoutSeconds(responseTimeoutSeconds); copy.setStatus(status); copy.setRetryCount(retryCount); copy.setPollCount(pollCount); copy.setTaskId(taskId); copy.setWorkflowTask(workflowTask); copy.setDomain(domain); copy.setInputMessage(inputMessage); copy.setOutputMessage(outputMessage); copy.setRateLimitPerFrequency(rateLimitPerFrequency); copy.setRateLimitFrequencyInSeconds(rateLimitFrequencyInSeconds); copy.setExternalInputPayloadStoragePath(externalInputPayloadStoragePath); copy.setExternalOutputPayloadStoragePath(externalOutputPayloadStoragePath); copy.setWorkflowPriority(workflowPriority); copy.setIteration(iteration); copy.setExecutionNameSpace(executionNameSpace); copy.setIsolationGroupId(isolationGroupId); copy.setSubWorkflowId(getSubWorkflowId()); copy.setSubworkflowChanged(subworkflowChanged); copy.setParentTaskId(parentTaskId); copy.setFirstStartTime(firstStartTime); copy.setExecutionMetadata(executionMetadata); return copy; } /** * @return a deep copy of the task instance To be used inside copy Workflow method to provide a * valid deep copied object. Note: This does not copy the following fields: * <ul> * <li>retried * <li>updateTime * <li>retriedTaskId * </ul> */ public Task deepCopy() { Task deepCopy = copy(); deepCopy.setStartTime(startTime); deepCopy.setScheduledTime(scheduledTime); deepCopy.setEndTime(endTime); deepCopy.setWorkerId(workerId); deepCopy.setReasonForIncompletion(reasonForIncompletion); deepCopy.setSeq(seq); deepCopy.setParentTaskId(parentTaskId); deepCopy.setFirstStartTime(firstStartTime); return deepCopy; } @Override public String toString() { return "Task{" + "taskType='" + taskType + '\'' + ", status=" + status + ", inputData=" + inputData + ", referenceTaskName='" + referenceTaskName + '\'' + ", retryCount=" + retryCount + ", seq=" + seq + ", correlationId='" + correlationId + '\'' + ", pollCount=" + pollCount + ", taskDefName='" + taskDefName + '\'' + ", scheduledTime=" + scheduledTime + ", startTime=" + startTime + ", endTime=" + endTime + ", updateTime=" + updateTime + ", startDelayInSeconds=" + startDelayInSeconds + ", retriedTaskId='" + retriedTaskId + '\'' + ", retried=" + retried + ", executed=" + executed + ", callbackFromWorker=" + callbackFromWorker + ", responseTimeoutSeconds=" + responseTimeoutSeconds + ", workflowInstanceId='" + workflowInstanceId + '\'' + ", workflowType='" + workflowType + '\'' + ", taskId='" + taskId + '\'' + ", reasonForIncompletion='" + reasonForIncompletion + '\'' + ", callbackAfterSeconds=" + callbackAfterSeconds + ", workerId='" + workerId + '\'' + ", outputData=" + outputData + ", workflowTask=" + workflowTask + ", domain='" + domain + '\'' + ", inputMessage='" + inputMessage + '\'' + ", outputMessage='" + outputMessage + '\'' + ", rateLimitPerFrequency=" + rateLimitPerFrequency + ", rateLimitFrequencyInSeconds=" + rateLimitFrequencyInSeconds + ", workflowPriority=" + workflowPriority + ", externalInputPayloadStoragePath='" + externalInputPayloadStoragePath + '\'' + ", externalOutputPayloadStoragePath='" + externalOutputPayloadStoragePath + '\'' + ", isolationGroupId='" + isolationGroupId + '\'' + ", executionNameSpace='" + executionNameSpace + '\'' + ", subworkflowChanged='" + subworkflowChanged + '\'' + ", firstStartTime='" + firstStartTime + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Task task = (Task) o; return getRetryCount() == task.getRetryCount() && getSeq() == task.getSeq() && getPollCount() == task.getPollCount() && getScheduledTime() == task.getScheduledTime() && getStartTime() == task.getStartTime() && getEndTime() == task.getEndTime() && getUpdateTime() == task.getUpdateTime() && getStartDelayInSeconds() == task.getStartDelayInSeconds() && isRetried() == task.isRetried() && isExecuted() == task.isExecuted() && isCallbackFromWorker() == task.isCallbackFromWorker() && getResponseTimeoutSeconds() == task.getResponseTimeoutSeconds() && getCallbackAfterSeconds() == task.getCallbackAfterSeconds() && getRateLimitPerFrequency() == task.getRateLimitPerFrequency() && getRateLimitFrequencyInSeconds() == task.getRateLimitFrequencyInSeconds() && Objects.equals(getTaskType(), task.getTaskType()) && getStatus() == task.getStatus() && getIteration() == task.getIteration() && getWorkflowPriority() == task.getWorkflowPriority() && Objects.equals(getInputData(), task.getInputData()) && Objects.equals(getReferenceTaskName(), task.getReferenceTaskName()) && Objects.equals(getCorrelationId(), task.getCorrelationId()) && Objects.equals(getTaskDefName(), task.getTaskDefName()) && Objects.equals(getRetriedTaskId(), task.getRetriedTaskId()) && Objects.equals(getWorkflowInstanceId(), task.getWorkflowInstanceId()) && Objects.equals(getWorkflowType(), task.getWorkflowType()) && Objects.equals(getTaskId(), task.getTaskId()) && Objects.equals(getReasonForIncompletion(), task.getReasonForIncompletion()) && Objects.equals(getWorkerId(), task.getWorkerId()) && Objects.equals(getOutputData(), task.getOutputData()) && Objects.equals(getWorkflowTask(), task.getWorkflowTask()) && Objects.equals(getDomain(), task.getDomain()) && Objects.equals(getInputMessage(), task.getInputMessage()) && Objects.equals(getOutputMessage(), task.getOutputMessage()) && Objects.equals( getExternalInputPayloadStoragePath(), task.getExternalInputPayloadStoragePath()) && Objects.equals( getExternalOutputPayloadStoragePath(), task.getExternalOutputPayloadStoragePath()) && Objects.equals(getIsolationGroupId(), task.getIsolationGroupId()) && Objects.equals(getExecutionNameSpace(), task.getExecutionNameSpace()) && Objects.equals(getParentTaskId(), task.getParentTaskId()) && Objects.equals(getFirstStartTime(), task.getFirstStartTime()); } @Override public int hashCode() { return Objects.hash( getTaskType(), getStatus(), getInputData(), getReferenceTaskName(), getWorkflowPriority(), getRetryCount(), getSeq(), getCorrelationId(), getPollCount(), getTaskDefName(), getScheduledTime(), getStartTime(), getEndTime(), getUpdateTime(), getStartDelayInSeconds(), getRetriedTaskId(), isRetried(), isExecuted(), isCallbackFromWorker(), getResponseTimeoutSeconds(), getWorkflowInstanceId(), getWorkflowType(), getTaskId(), getReasonForIncompletion(), getCallbackAfterSeconds(), getWorkerId(), getOutputData(), getWorkflowTask(), getDomain(), getInputMessage(), getOutputMessage(), getRateLimitPerFrequency(), getRateLimitFrequencyInSeconds(), getExternalInputPayloadStoragePath(), getExternalOutputPayloadStoragePath(), getIsolationGroupId(), getExecutionNameSpace(), getParentTaskId(), getFirstStartTime()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskType.java
common/src/main/java/com/netflix/conductor/common/metadata/tasks/TaskType.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.tasks; import java.util.HashSet; import java.util.Set; import com.netflix.conductor.annotations.protogen.ProtoEnum; @ProtoEnum public enum TaskType { SIMPLE, DYNAMIC, FORK_JOIN, FORK_JOIN_DYNAMIC, DECISION, SWITCH, JOIN, DO_WHILE, SUB_WORKFLOW, START_WORKFLOW, EVENT, WAIT, HUMAN, USER_DEFINED, HTTP, LAMBDA, INLINE, EXCLUSIVE_JOIN, TERMINATE, KAFKA_PUBLISH, JSON_JQ_TRANSFORM, SET_VARIABLE, NOOP; /** * TaskType constants representing each of the possible enumeration values. Motivation: to not * have any hardcoded/inline strings used in the code. */ public static final String TASK_TYPE_DECISION = "DECISION"; public static final String TASK_TYPE_SWITCH = "SWITCH"; public static final String TASK_TYPE_DYNAMIC = "DYNAMIC"; public static final String TASK_TYPE_JOIN = "JOIN"; public static final String TASK_TYPE_DO_WHILE = "DO_WHILE"; public static final String TASK_TYPE_FORK_JOIN_DYNAMIC = "FORK_JOIN_DYNAMIC"; public static final String TASK_TYPE_EVENT = "EVENT"; public static final String TASK_TYPE_WAIT = "WAIT"; public static final String TASK_TYPE_HUMAN = "HUMAN"; public static final String TASK_TYPE_SUB_WORKFLOW = "SUB_WORKFLOW"; public static final String TASK_TYPE_START_WORKFLOW = "START_WORKFLOW"; public static final String TASK_TYPE_FORK_JOIN = "FORK_JOIN"; public static final String TASK_TYPE_SIMPLE = "SIMPLE"; public static final String TASK_TYPE_HTTP = "HTTP"; public static final String TASK_TYPE_LAMBDA = "LAMBDA"; public static final String TASK_TYPE_INLINE = "INLINE"; public static final String TASK_TYPE_EXCLUSIVE_JOIN = "EXCLUSIVE_JOIN"; public static final String TASK_TYPE_TERMINATE = "TERMINATE"; public static final String TASK_TYPE_KAFKA_PUBLISH = "KAFKA_PUBLISH"; public static final String TASK_TYPE_JSON_JQ_TRANSFORM = "JSON_JQ_TRANSFORM"; public static final String TASK_TYPE_SET_VARIABLE = "SET_VARIABLE"; public static final String TASK_TYPE_FORK = "FORK"; public static final String TASK_TYPE_NOOP = "NOOP"; private static final Set<String> BUILT_IN_TASKS = new HashSet<>(); static { BUILT_IN_TASKS.add(TASK_TYPE_DECISION); BUILT_IN_TASKS.add(TASK_TYPE_SWITCH); BUILT_IN_TASKS.add(TASK_TYPE_FORK); BUILT_IN_TASKS.add(TASK_TYPE_JOIN); BUILT_IN_TASKS.add(TASK_TYPE_EXCLUSIVE_JOIN); BUILT_IN_TASKS.add(TASK_TYPE_DO_WHILE); } /** * Converts a task type string to {@link TaskType}. For an unknown string, the value is * defaulted to {@link TaskType#USER_DEFINED}. * * <p>NOTE: Use {@link Enum#valueOf(Class, String)} if the default of USER_DEFINED is not * necessary. * * @param taskType The task type string. * @return The {@link TaskType} enum. */ public static TaskType of(String taskType) { try { return TaskType.valueOf(taskType); } catch (IllegalArgumentException iae) { return TaskType.USER_DEFINED; } } public static boolean isBuiltIn(String taskType) { return BUILT_IN_TASKS.contains(taskType); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java
common/src/main/java/com/netflix/conductor/common/metadata/events/EventExecution.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.events; import java.util.HashMap; import java.util.Map; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.events.EventHandler.Action; @ProtoMessage public class EventExecution { @ProtoEnum public enum Status { IN_PROGRESS, COMPLETED, FAILED, SKIPPED } @ProtoField(id = 1) private String id; @ProtoField(id = 2) private String messageId; @ProtoField(id = 3) private String name; @ProtoField(id = 4) private String event; @ProtoField(id = 5) private long created; @ProtoField(id = 6) private Status status; @ProtoField(id = 7) private Action.Type action; @ProtoField(id = 8) private Map<String, Object> output = new HashMap<>(); public EventExecution() {} public EventExecution(String id, String messageId) { this.id = id; this.messageId = messageId; } /** * @return the id */ public String getId() { return id; } /** * @param id the id to set */ public void setId(String id) { this.id = id; } /** * @return the messageId */ public String getMessageId() { return messageId; } /** * @param messageId the messageId to set */ public void setMessageId(String messageId) { this.messageId = messageId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the event */ public String getEvent() { return event; } /** * @param event the event to set */ public void setEvent(String event) { this.event = event; } /** * @return the created */ public long getCreated() { return created; } /** * @param created the created to set */ public void setCreated(long created) { this.created = created; } /** * @return the status */ public Status getStatus() { return status; } /** * @param status the status to set */ public void setStatus(Status status) { this.status = status; } /** * @return the action */ public Action.Type getAction() { return action; } /** * @param action the action to set */ public void setAction(Action.Type action) { this.action = action; } /** * @return the output */ public Map<String, Object> getOutput() { return output; } /** * @param output the output to set */ public void setOutput(Map<String, Object> output) { this.output = output; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EventExecution execution = (EventExecution) o; return created == execution.created && Objects.equals(id, execution.id) && Objects.equals(messageId, execution.messageId) && Objects.equals(name, execution.name) && Objects.equals(event, execution.event) && status == execution.status && action == execution.action && Objects.equals(output, execution.output); } @Override public int hashCode() { return Objects.hash(id, messageId, name, event, created, status, action, output); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/events/EventHandler.java
common/src/main/java/com/netflix/conductor/common/metadata/events/EventHandler.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.events; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.google.protobuf.Any; import io.swagger.v3.oas.annotations.Hidden; import jakarta.validation.Valid; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; /** Defines an event handler */ @ProtoMessage public class EventHandler { @ProtoField(id = 1) @NotEmpty(message = "Missing event handler name") private String name; @ProtoField(id = 2) @NotEmpty(message = "Missing event location") private String event; @ProtoField(id = 3) private String condition; @ProtoField(id = 4) @NotNull @NotEmpty(message = "No actions specified. Please specify at-least one action") private List<@Valid Action> actions = new LinkedList<>(); @ProtoField(id = 5) private boolean active; @ProtoField(id = 6) private String evaluatorType; public EventHandler() {} /** * @return the name MUST be unique within a conductor instance */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the event */ public String getEvent() { return event; } /** * @param event the event to set */ public void setEvent(String event) { this.event = event; } /** * @return the condition */ public String getCondition() { return condition; } /** * @param condition the condition to set */ public void setCondition(String condition) { this.condition = condition; } /** * @return the actions */ public List<Action> getActions() { return actions; } /** * @param actions the actions to set */ public void setActions(List<Action> actions) { this.actions = actions; } /** * @return the active */ public boolean isActive() { return active; } /** * @param active if set to false, the event handler is deactivated */ public void setActive(boolean active) { this.active = active; } /** * @return the evaluator type */ public String getEvaluatorType() { return evaluatorType; } /** * @param evaluatorType the evaluatorType to set */ public void setEvaluatorType(String evaluatorType) { this.evaluatorType = evaluatorType; } @ProtoMessage public static class Action { @ProtoEnum public enum Type { start_workflow, complete_task, fail_task, terminate_workflow, update_workflow_variables } @ProtoField(id = 1) private Type action; @ProtoField(id = 2) private StartWorkflow start_workflow; @ProtoField(id = 3) private TaskDetails complete_task; @ProtoField(id = 4) private TaskDetails fail_task; @ProtoField(id = 5) private boolean expandInlineJSON; @ProtoField(id = 6) private TerminateWorkflow terminate_workflow; @ProtoField(id = 7) private UpdateWorkflowVariables update_workflow_variables; /** * @return the action */ public Type getAction() { return action; } /** * @param action the action to set */ public void setAction(Type action) { this.action = action; } /** * @return the start_workflow */ public StartWorkflow getStart_workflow() { return start_workflow; } /** * @param start_workflow the start_workflow to set */ public void setStart_workflow(StartWorkflow start_workflow) { this.start_workflow = start_workflow; } /** * @return the complete_task */ public TaskDetails getComplete_task() { return complete_task; } /** * @param complete_task the complete_task to set */ public void setComplete_task(TaskDetails complete_task) { this.complete_task = complete_task; } /** * @return the fail_task */ public TaskDetails getFail_task() { return fail_task; } /** * @param fail_task the fail_task to set */ public void setFail_task(TaskDetails fail_task) { this.fail_task = fail_task; } /** * @param expandInlineJSON when set to true, the in-lined JSON strings are expanded to a * full json document */ public void setExpandInlineJSON(boolean expandInlineJSON) { this.expandInlineJSON = expandInlineJSON; } /** * @return true if the json strings within the payload should be expanded. */ public boolean isExpandInlineJSON() { return expandInlineJSON; } /** * @return the terminate_workflow */ public TerminateWorkflow getTerminate_workflow() { return terminate_workflow; } /** * @param terminate_workflow the terminate_workflow to set */ public void setTerminate_workflow(TerminateWorkflow terminate_workflow) { this.terminate_workflow = terminate_workflow; } /** * @return the update_workflow_variables */ public UpdateWorkflowVariables getUpdate_workflow_variables() { return update_workflow_variables; } /** * @param update_workflow_variables the update_workflow_variables to set */ public void setUpdate_workflow_variables( UpdateWorkflowVariables update_workflow_variables) { this.update_workflow_variables = update_workflow_variables; } } @ProtoMessage public static class TaskDetails { @ProtoField(id = 1) private String workflowId; @ProtoField(id = 2) private String taskRefName; @ProtoField(id = 3) private Map<String, Object> output = new HashMap<>(); @ProtoField(id = 4) @Hidden private Any outputMessage; @ProtoField(id = 5) private String taskId; /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @param workflowId the workflowId to set */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * @return the taskRefName */ public String getTaskRefName() { return taskRefName; } /** * @param taskRefName the taskRefName to set */ public void setTaskRefName(String taskRefName) { this.taskRefName = taskRefName; } /** * @return the output */ public Map<String, Object> getOutput() { return output; } /** * @param output the output to set */ public void setOutput(Map<String, Object> output) { this.output = output; } public Any getOutputMessage() { return outputMessage; } public void setOutputMessage(Any outputMessage) { this.outputMessage = outputMessage; } /** * @return the taskId */ public String getTaskId() { return taskId; } /** * @param taskId the taskId to set */ public void setTaskId(String taskId) { this.taskId = taskId; } } @ProtoMessage public static class StartWorkflow { @ProtoField(id = 1) private String name; @ProtoField(id = 2) private Integer version; @ProtoField(id = 3) private String correlationId; @ProtoField(id = 4) private Map<String, Object> input = new HashMap<>(); @ProtoField(id = 5) @Hidden private Any inputMessage; @ProtoField(id = 6) private Map<String, String> taskToDomain; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the version */ public Integer getVersion() { return version; } /** * @param version the version to set */ public void setVersion(Integer version) { this.version = version; } /** * @return the correlationId */ public String getCorrelationId() { return correlationId; } /** * @param correlationId the correlationId to set */ public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } /** * @return the input */ public Map<String, Object> getInput() { return input; } /** * @param input the input to set */ public void setInput(Map<String, Object> input) { this.input = input; } public Any getInputMessage() { return inputMessage; } public void setInputMessage(Any inputMessage) { this.inputMessage = inputMessage; } public Map<String, String> getTaskToDomain() { return taskToDomain; } public void setTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; } } @ProtoMessage public static class TerminateWorkflow { @ProtoField(id = 1) private String workflowId; @ProtoField(id = 2) private String terminationReason; /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @param workflowId the workflowId to set */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * @return the reasonForTermination */ public String getTerminationReason() { return terminationReason; } /** * @param terminationReason the reasonForTermination to set */ public void setTerminationReason(String terminationReason) { this.terminationReason = terminationReason; } } @ProtoMessage public static class UpdateWorkflowVariables { @ProtoField(id = 1) private String workflowId; @ProtoField(id = 2) private Map<String, Object> variables; @ProtoField(id = 3) private Boolean appendArray; /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @param workflowId the workflowId to set */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * @return the variables */ public Map<String, Object> getVariables() { return variables; } /** * @param variables the variables to set */ public void setVariables(Map<String, Object> variables) { this.variables = variables; } /** * @return appendArray */ public Boolean isAppendArray() { return appendArray; } /** * @param appendArray the appendArray to set */ public void setAppendArray(Boolean appendArray) { this.appendArray = appendArray; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/acl/Permission.java
common/src/main/java/com/netflix/conductor/common/metadata/acl/Permission.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.acl; import com.netflix.conductor.annotations.protogen.ProtoEnum; @ProtoEnum @Deprecated public enum Permission { OWNER, OPERATOR }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/SkipTaskRequest.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/SkipTaskRequest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.google.protobuf.Any; import io.swagger.v3.oas.annotations.Hidden; @ProtoMessage(toProto = false) public class SkipTaskRequest { @ProtoField(id = 1) private Map<String, Object> taskInput; @ProtoField(id = 2) private Map<String, Object> taskOutput; @ProtoField(id = 3) @Hidden private Any taskInputMessage; @ProtoField(id = 4) @Hidden private Any taskOutputMessage; public Map<String, Object> getTaskInput() { return taskInput; } public void setTaskInput(Map<String, Object> taskInput) { this.taskInput = taskInput; } public Map<String, Object> getTaskOutput() { return taskOutput; } public void setTaskOutput(Map<String, Object> taskOutput) { this.taskOutput = taskOutput; } public Any getTaskInputMessage() { return taskInputMessage; } public void setTaskInputMessage(Any taskInputMessage) { this.taskInputMessage = taskInputMessage; } public Any getTaskOutputMessage() { return taskOutputMessage; } public void setTaskOutputMessage(Any taskOutputMessage) { this.taskOutputMessage = taskOutputMessage; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/DynamicForkJoinTaskList.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/DynamicForkJoinTaskList.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; @ProtoMessage public class DynamicForkJoinTaskList { @ProtoField(id = 1) private List<DynamicForkJoinTask> dynamicTasks = new ArrayList<>(); public void add( String taskName, String workflowName, String referenceName, Map<String, Object> input) { dynamicTasks.add(new DynamicForkJoinTask(taskName, workflowName, referenceName, input)); } public void add(DynamicForkJoinTask dtask) { dynamicTasks.add(dtask); } public List<DynamicForkJoinTask> getDynamicTasks() { return dynamicTasks; } public void setDynamicTasks(List<DynamicForkJoinTask> dynamicTasks) { this.dynamicTasks = dynamicTasks; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowTask.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonSetter; import jakarta.validation.Valid; import jakarta.validation.constraints.*; /** * This is the task definition definied as part of the {@link WorkflowDef}. The tasks definied in * the Workflow definition are saved as part of {@link WorkflowDef#getTasks} */ @ProtoMessage public class WorkflowTask { @ProtoField(id = 1) @NotEmpty(message = "WorkflowTask name cannot be empty or null") private String name; @ProtoField(id = 2) @NotEmpty(message = "WorkflowTask taskReferenceName name cannot be empty or null") private String taskReferenceName; @ProtoField(id = 3) private String description; @ProtoField(id = 4) private Map<String, Object> inputParameters = new HashMap<>(); @ProtoField(id = 5) private String type = TaskType.SIMPLE.name(); @ProtoField(id = 6) private String dynamicTaskNameParam; @Deprecated @ProtoField(id = 7) private String caseValueParam; @Deprecated @ProtoField(id = 8) private String caseExpression; @ProtoField(id = 22) private String scriptExpression; @ProtoMessage(wrapper = true) public static class WorkflowTaskList { public List<WorkflowTask> getTasks() { return tasks; } public void setTasks(List<WorkflowTask> tasks) { this.tasks = tasks; } @ProtoField(id = 1) private List<WorkflowTask> tasks; } // Populates for the tasks of the decision type @ProtoField(id = 9) private Map<String, @Valid List<@Valid WorkflowTask>> decisionCases = new LinkedHashMap<>(); @Deprecated private String dynamicForkJoinTasksParam; @ProtoField(id = 10) private String dynamicForkTasksParam; @ProtoField(id = 11) private String dynamicForkTasksInputParamName; @ProtoField(id = 12) private List<@Valid WorkflowTask> defaultCase = new LinkedList<>(); @ProtoField(id = 13) private List<@Valid List<@Valid WorkflowTask>> forkTasks = new LinkedList<>(); @ProtoField(id = 14) @PositiveOrZero private int startDelay; // No. of seconds (at-least) to wait before starting a task. @ProtoField(id = 15) @Valid private SubWorkflowParams subWorkflowParam; @ProtoField(id = 16) private List<String> joinOn = new LinkedList<>(); @ProtoField(id = 17) private String sink; @ProtoField(id = 18) private boolean optional = false; @ProtoField(id = 19) private TaskDef taskDefinition; @ProtoField(id = 20) private Boolean rateLimited; @ProtoField(id = 21) private List<String> defaultExclusiveJoinTask = new LinkedList<>(); @ProtoField(id = 23) private Boolean asyncComplete = false; @ProtoField(id = 24) private String loopCondition; @ProtoField(id = 25) private List<WorkflowTask> loopOver = new LinkedList<>(); @ProtoField(id = 26) private Integer retryCount; @ProtoField(id = 27) private String evaluatorType; @ProtoField(id = 28) private String expression; /* Map of events to be emitted when the task status changed. key can be comma separated values of the status changes prefixed with "on"<STATUS> */ // @ProtoField(id = 29) private @Valid Map<String, List<StateChangeEvent>> onStateChange = new HashMap<>(); @ProtoField(id = 30) private String joinStatus; @ProtoField(id = 31) private CacheConfig cacheConfig; @ProtoField(id = 32) private boolean permissive; /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the taskReferenceName */ public String getTaskReferenceName() { return taskReferenceName; } /** * @param taskReferenceName the taskReferenceName to set */ public void setTaskReferenceName(String taskReferenceName) { this.taskReferenceName = taskReferenceName; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the inputParameters */ public Map<String, Object> getInputParameters() { return inputParameters; } /** * @param inputParameters the inputParameters to set */ public void setInputParameters(Map<String, Object> inputParameters) { this.inputParameters = inputParameters; } /** * @return the type */ public String getType() { return type; } public void setWorkflowTaskType(TaskType type) { this.type = type.name(); } /** * @param type the type to set */ public void setType(@NotEmpty(message = "WorkTask type cannot be null or empty") String type) { this.type = type; } /** * @return the decisionCases */ public Map<String, List<WorkflowTask>> getDecisionCases() { return decisionCases; } /** * @param decisionCases the decisionCases to set */ public void setDecisionCases(Map<String, List<WorkflowTask>> decisionCases) { this.decisionCases = decisionCases; } /** * @return the defaultCase */ public List<WorkflowTask> getDefaultCase() { return defaultCase; } /** * @param defaultCase the defaultCase to set */ public void setDefaultCase(List<WorkflowTask> defaultCase) { this.defaultCase = defaultCase; } /** * @return the forkTasks */ public List<List<WorkflowTask>> getForkTasks() { return forkTasks; } /** * @param forkTasks the forkTasks to set */ public void setForkTasks(List<List<WorkflowTask>> forkTasks) { this.forkTasks = forkTasks; } /** * @return the startDelay in seconds */ public int getStartDelay() { return startDelay; } /** * @param startDelay the startDelay to set */ public void setStartDelay(int startDelay) { this.startDelay = startDelay; } /** * @return the retryCount */ public Integer getRetryCount() { return retryCount; } /** * @param retryCount the retryCount to set */ public void setRetryCount(final Integer retryCount) { this.retryCount = retryCount; } /** * @return the dynamicTaskNameParam */ public String getDynamicTaskNameParam() { return dynamicTaskNameParam; } /** * @param dynamicTaskNameParam the dynamicTaskNameParam to set to be used by DYNAMIC tasks */ public void setDynamicTaskNameParam(String dynamicTaskNameParam) { this.dynamicTaskNameParam = dynamicTaskNameParam; } /** * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link * WorkflowTask#getExpression()} combination. * @return the caseValueParam */ @Deprecated public String getCaseValueParam() { return caseValueParam; } @Deprecated public String getDynamicForkJoinTasksParam() { return dynamicForkJoinTasksParam; } @Deprecated public void setDynamicForkJoinTasksParam(String dynamicForkJoinTasksParam) { this.dynamicForkJoinTasksParam = dynamicForkJoinTasksParam; } public String getDynamicForkTasksParam() { return dynamicForkTasksParam; } public void setDynamicForkTasksParam(String dynamicForkTasksParam) { this.dynamicForkTasksParam = dynamicForkTasksParam; } public String getDynamicForkTasksInputParamName() { return dynamicForkTasksInputParamName; } public void setDynamicForkTasksInputParamName(String dynamicForkTasksInputParamName) { this.dynamicForkTasksInputParamName = dynamicForkTasksInputParamName; } /** * @param caseValueParam the caseValueParam to set * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link * WorkflowTask#getExpression()} combination. */ @Deprecated public void setCaseValueParam(String caseValueParam) { this.caseValueParam = caseValueParam; } /** * @return A javascript expression for decision cases. The result should be a scalar value that * is used to decide the case branches. * @see #getDecisionCases() * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link * WorkflowTask#getExpression()} combination. */ @Deprecated public String getCaseExpression() { return caseExpression; } /** * @param caseExpression A javascript expression for decision cases. The result should be a * scalar value that is used to decide the case branches. * @deprecated Use {@link WorkflowTask#getEvaluatorType()} and {@link * WorkflowTask#getExpression()} combination. */ @Deprecated public void setCaseExpression(String caseExpression) { this.caseExpression = caseExpression; } public String getScriptExpression() { return scriptExpression; } public void setScriptExpression(String expression) { this.scriptExpression = expression; } public CacheConfig getCacheConfig() { return cacheConfig; } public void setCacheConfig(CacheConfig cacheConfig) { this.cacheConfig = cacheConfig; } /** * @return the subWorkflow */ @JsonGetter public SubWorkflowParams getSubWorkflowParam() { return subWorkflowParam; } /** * @param subWorkflow the subWorkflowParam to set */ @JsonSetter public void setSubWorkflowParam(SubWorkflowParams subWorkflow) { this.subWorkflowParam = subWorkflow; } /** * @return the joinOn */ public List<String> getJoinOn() { return joinOn; } /** * @param joinOn the joinOn to set */ public void setJoinOn(List<String> joinOn) { this.joinOn = joinOn; } /** * @return the loopCondition */ public String getLoopCondition() { return loopCondition; } /** * @param loopCondition the expression to set */ public void setLoopCondition(String loopCondition) { this.loopCondition = loopCondition; } /** * @return the loopOver */ public List<WorkflowTask> getLoopOver() { return loopOver; } /** * @param loopOver the loopOver to set */ public void setLoopOver(List<WorkflowTask> loopOver) { this.loopOver = loopOver; } /** * @return Sink value for the EVENT type of task */ public String getSink() { return sink; } /** * @param sink Name of the sink */ public void setSink(String sink) { this.sink = sink; } /** * @return whether wait for an external event to complete the task, for EVENT and HTTP tasks */ public Boolean isAsyncComplete() { return asyncComplete; } public void setAsyncComplete(Boolean asyncComplete) { this.asyncComplete = asyncComplete; } /** * @return If the task is optional. When set to true, the workflow execution continues even when * the task is in failed status. */ public boolean isOptional() { return optional; } /** * @return Task definition associated to the Workflow Task */ public TaskDef getTaskDefinition() { return taskDefinition; } /** * @param taskDefinition Task definition */ public void setTaskDefinition(TaskDef taskDefinition) { this.taskDefinition = taskDefinition; } /** * @param optional when set to true, the task is marked as optional */ public void setOptional(boolean optional) { this.optional = optional; } public Boolean getRateLimited() { return rateLimited; } public void setRateLimited(Boolean rateLimited) { this.rateLimited = rateLimited; } public Boolean isRateLimited() { return rateLimited != null && rateLimited; } public List<String> getDefaultExclusiveJoinTask() { return defaultExclusiveJoinTask; } public void setDefaultExclusiveJoinTask(List<String> defaultExclusiveJoinTask) { this.defaultExclusiveJoinTask = defaultExclusiveJoinTask; } /** * @return the evaluatorType */ public String getEvaluatorType() { return evaluatorType; } /** * @param evaluatorType the evaluatorType to set */ public void setEvaluatorType(String evaluatorType) { this.evaluatorType = evaluatorType; } /** * @return An evaluation expression for switch cases evaluated by corresponding evaluator. The * result should be a scalar value that is used to decide the case branches. * @see #getDecisionCases() */ public String getExpression() { return expression; } /** * @param expression the expression to set */ public void setExpression(String expression) { this.expression = expression; } public String getJoinStatus() { return joinStatus; } public void setJoinStatus(String joinStatus) { this.joinStatus = joinStatus; } public boolean isPermissive() { return permissive; } public void setPermissive(boolean permissive) { this.permissive = permissive; } private Collection<List<WorkflowTask>> children() { Collection<List<WorkflowTask>> workflowTaskLists = new LinkedList<>(); switch (TaskType.of(type)) { case DECISION: case SWITCH: workflowTaskLists.addAll(decisionCases.values()); workflowTaskLists.add(defaultCase); break; case FORK_JOIN: workflowTaskLists.addAll(forkTasks); break; case DO_WHILE: workflowTaskLists.add(loopOver); break; default: break; } return workflowTaskLists; } public List<WorkflowTask> collectTasks() { List<WorkflowTask> tasks = new LinkedList<>(); tasks.add(this); for (List<WorkflowTask> workflowTaskList : children()) { for (WorkflowTask workflowTask : workflowTaskList) { tasks.addAll(workflowTask.collectTasks()); } } return tasks; } public WorkflowTask next(String taskReferenceName, WorkflowTask parent) { TaskType taskType = TaskType.of(type); switch (taskType) { case DO_WHILE: case DECISION: case SWITCH: for (List<WorkflowTask> workflowTasks : children()) { Iterator<WorkflowTask> iterator = workflowTasks.iterator(); while (iterator.hasNext()) { WorkflowTask task = iterator.next(); if (task.getTaskReferenceName().equals(taskReferenceName)) { break; } WorkflowTask nextTask = task.next(taskReferenceName, this); if (nextTask != null) { return nextTask; } if (task.has(taskReferenceName)) { break; } } if (iterator.hasNext()) { return iterator.next(); } } if (taskType == TaskType.DO_WHILE && this.has(taskReferenceName)) { // come here means this is DO_WHILE task and `taskReferenceName` is the last // task in // this DO_WHILE task, because DO_WHILE task need to be executed to decide // whether to // schedule next iteration, so we just return the DO_WHILE task, and then ignore // generating this task again in deciderService.getNextTask() return this; } break; case FORK_JOIN: boolean found = false; for (List<WorkflowTask> workflowTasks : children()) { Iterator<WorkflowTask> iterator = workflowTasks.iterator(); while (iterator.hasNext()) { WorkflowTask task = iterator.next(); if (task.getTaskReferenceName().equals(taskReferenceName)) { found = true; break; } WorkflowTask nextTask = task.next(taskReferenceName, this); if (nextTask != null) { return nextTask; } if (task.has(taskReferenceName)) { break; } } if (iterator.hasNext()) { return iterator.next(); } if (found && parent != null) { return parent.next( this.taskReferenceName, parent); // we need to return join task... -- get my sibling from my // parent.. } } break; case DYNAMIC: case TERMINATE: case SIMPLE: return null; default: break; } return null; } public boolean has(String taskReferenceName) { if (this.getTaskReferenceName().equals(taskReferenceName)) { return true; } switch (TaskType.of(type)) { case DECISION: case SWITCH: case DO_WHILE: case FORK_JOIN: for (List<WorkflowTask> childx : children()) { for (WorkflowTask child : childx) { if (child.has(taskReferenceName)) { return true; } } } break; default: break; } return false; } public WorkflowTask get(String taskReferenceName) { if (this.getTaskReferenceName().equals(taskReferenceName)) { return this; } for (List<WorkflowTask> childx : children()) { for (WorkflowTask child : childx) { WorkflowTask found = child.get(taskReferenceName); if (found != null) { return found; } } } return null; } public Map<String, List<StateChangeEvent>> getOnStateChange() { return onStateChange; } public void setOnStateChange(Map<String, List<StateChangeEvent>> onStateChange) { this.onStateChange = onStateChange; } @Override public String toString() { return name + "/" + taskReferenceName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkflowTask that = (WorkflowTask) o; return Objects.equals(name, that.name) && Objects.equals(taskReferenceName, that.taskReferenceName); } @Override public int hashCode() { return Objects.hash(name, taskReferenceName); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/StartWorkflowRequest.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/StartWorkflowRequest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.HashMap; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import jakarta.validation.Valid; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; @ProtoMessage public class StartWorkflowRequest { @ProtoField(id = 1) @NotNull(message = "Workflow name cannot be null or empty") private String name; @ProtoField(id = 2) private Integer version; @ProtoField(id = 3) private String correlationId; @ProtoField(id = 4) private Map<String, Object> input = new HashMap<>(); @ProtoField(id = 5) private Map<String, String> taskToDomain = new HashMap<>(); @ProtoField(id = 6) @Valid private WorkflowDef workflowDef; @ProtoField(id = 7) private String externalInputPayloadStoragePath; @ProtoField(id = 8) @Min(value = 0, message = "priority: ${validatedValue} should be minimum {value}") @Max(value = 99, message = "priority: ${validatedValue} should be maximum {value}") private Integer priority = 0; @ProtoField(id = 9) private String createdBy; private String idempotencyKey; private IdempotencyStrategy idempotencyStrategy; public String getIdempotencyKey() { return idempotencyKey; } public void setIdempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; } public IdempotencyStrategy getIdempotencyStrategy() { return idempotencyStrategy; } public void setIdempotencyStrategy(IdempotencyStrategy idempotencyStrategy) { this.idempotencyStrategy = idempotencyStrategy; } public String getName() { return name; } public void setName(String name) { this.name = name; } public StartWorkflowRequest withName(String name) { this.name = name; return this; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } public StartWorkflowRequest withVersion(Integer version) { this.version = version; return this; } public String getCorrelationId() { return correlationId; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public StartWorkflowRequest withCorrelationId(String correlationId) { this.correlationId = correlationId; return this; } public String getExternalInputPayloadStoragePath() { return externalInputPayloadStoragePath; } public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; } public StartWorkflowRequest withExternalInputPayloadStoragePath( String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; return this; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public StartWorkflowRequest withPriority(Integer priority) { this.priority = priority; return this; } public Map<String, Object> getInput() { return input; } public void setInput(Map<String, Object> input) { this.input = input; } public StartWorkflowRequest withInput(Map<String, Object> input) { this.input = input; return this; } public Map<String, String> getTaskToDomain() { return taskToDomain; } public void setTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; } public StartWorkflowRequest withTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; return this; } public WorkflowDef getWorkflowDef() { return workflowDef; } public void setWorkflowDef(WorkflowDef workflowDef) { this.workflowDef = workflowDef; } public StartWorkflowRequest withWorkflowDef(WorkflowDef workflowDef) { this.workflowDef = workflowDef; return this; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public StartWorkflowRequest withCreatedBy(String createdBy) { this.createdBy = createdBy; return this; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDefSummary.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDefSummary.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.constraints.NoSemiColonConstraint; import jakarta.validation.constraints.NotEmpty; @ProtoMessage public class WorkflowDefSummary implements Comparable<WorkflowDefSummary> { @NotEmpty(message = "WorkflowDef name cannot be null or empty") @ProtoField(id = 1) @NoSemiColonConstraint( message = "Workflow name cannot contain the following set of characters: ':'") private String name; @ProtoField(id = 2) private int version = 1; @ProtoField(id = 3) private Long createTime; /** * @return the version */ public int getVersion() { return version; } /** * @return the workflow name */ public String getName() { return name; } /** * @return the createTime */ public Long getCreateTime() { return createTime; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkflowDefSummary that = (WorkflowDefSummary) o; return getVersion() == that.getVersion() && Objects.equals(getName(), that.getName()); } public void setName(String name) { this.name = name; } public void setVersion(int version) { this.version = version; } public void setCreateTime(Long createTime) { this.createTime = createTime; } @Override public int hashCode() { return Objects.hash(getName(), getVersion()); } @Override public String toString() { return "WorkflowDef{name='" + name + ", version=" + version + "}"; } @Override public int compareTo(WorkflowDefSummary o) { int res = this.name.compareTo(o.name); if (res != 0) { return res; } res = Integer.compare(this.version, o.version); return res; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/CacheConfig.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/CacheConfig.java
/* * Copyright 2025 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; @ProtoMessage public class CacheConfig { @ProtoField(id = 1) private String key; @ProtoField(id = 2) private int ttlInSecond; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public int getTtlInSecond() { return ttlInSecond; } public void setTtlInSecond(int ttlInSecond) { this.ttlInSecond = ttlInSecond; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/IdempotencyStrategy.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/IdempotencyStrategy.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; public enum IdempotencyStrategy { FAIL, RETURN_EXISTING, FAIL_ON_RUNNING }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/SubWorkflowParams.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/SubWorkflowParams.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.utils.TaskUtils; import com.fasterxml.jackson.annotation.JsonGetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSetter; @ProtoMessage public class SubWorkflowParams { @ProtoField(id = 1) private String name; @ProtoField(id = 2) private Integer version; @ProtoField(id = 3) private Map<String, String> taskToDomain; // workaround as WorkflowDef cannot directly be used due to cyclic dependency issue in protobuf // imports @ProtoField(id = 4) private Object workflowDefinition; private String idempotencyKey; private IdempotencyStrategy idempotencyStrategy; // Priority of the sub workflow, not set inherits from the parent private Object priority; public String getIdempotencyKey() { return idempotencyKey; } public void setIdempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; } public IdempotencyStrategy getIdempotencyStrategy() { return idempotencyStrategy; } public void setIdempotencyStrategy(IdempotencyStrategy idempotencyStrategy) { this.idempotencyStrategy = idempotencyStrategy; } public Object getPriority() { return priority; } public void setPriority(Object priority) { this.priority = priority; } /** * @return the name */ public String getName() { if (workflowDefinition != null) { if (workflowDefinition instanceof WorkflowDef) { return ((WorkflowDef) workflowDefinition).getName(); } } return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the version */ public Integer getVersion() { if (workflowDefinition != null) { if (workflowDefinition instanceof WorkflowDef) { return ((WorkflowDef) workflowDefinition).getVersion(); } } return version; } /** * @param version the version to set */ public void setVersion(Integer version) { this.version = version; } /** * @return the taskToDomain */ public Map<String, String> getTaskToDomain() { return taskToDomain; } /** * @param taskToDomain the taskToDomain to set */ public void setTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; } /** * @return the workflowDefinition as an Object */ @JsonGetter("workflowDefinition") public Object getWorkflowDefinition() { return workflowDefinition; } @Deprecated @JsonIgnore public void setWorkflowDef(WorkflowDef workflowDef) { this.setWorkflowDefinition(workflowDef); } @Deprecated @JsonIgnore public WorkflowDef getWorkflowDef() { return (WorkflowDef) workflowDefinition; } /** * @param workflowDef the workflowDefinition to set */ @JsonSetter("workflowDefinition") public void setWorkflowDefinition(Object workflowDef) { if (workflowDef == null) { this.workflowDefinition = workflowDef; } else if (workflowDef instanceof WorkflowDef) { this.workflowDefinition = workflowDef; } else if (workflowDef instanceof String) { if (!(((String) workflowDef).startsWith("${")) || !(((String) workflowDef).endsWith("}"))) { throw new IllegalArgumentException( "workflowDefinition is a string, but not a valid DSL string"); } else { this.workflowDefinition = workflowDef; } } else if (workflowDef instanceof LinkedHashMap) { this.workflowDefinition = TaskUtils.convertToWorkflowDef(workflowDef); } else { throw new IllegalArgumentException( "workflowDefinition must be either null, or WorkflowDef, or a valid DSL string"); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubWorkflowParams that = (SubWorkflowParams) o; return Objects.equals(getName(), that.getName()) && Objects.equals(getVersion(), that.getVersion()) && Objects.equals(getTaskToDomain(), that.getTaskToDomain()) && Objects.equals(getWorkflowDefinition(), that.getWorkflowDefinition()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDef.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/WorkflowDef.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.*; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.constraints.OwnerEmailMandatoryConstraint; import com.netflix.conductor.common.constraints.TaskReferenceNameUniqueConstraint; import com.netflix.conductor.common.constraints.ValidNameConstraint; import com.netflix.conductor.common.metadata.Auditable; import com.netflix.conductor.common.metadata.SchemaDef; import com.netflix.conductor.common.metadata.tasks.TaskType; import jakarta.validation.Valid; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; @ProtoMessage @TaskReferenceNameUniqueConstraint public class WorkflowDef extends Auditable { @NotEmpty(message = "WorkflowDef name cannot be null or empty") @ProtoField(id = 1) @ValidNameConstraint private String name; @ProtoField(id = 2) private String description; @ProtoField(id = 3) private int version = 1; @ProtoField(id = 4) @NotNull @NotEmpty(message = "WorkflowTask list cannot be empty") private List<@Valid WorkflowTask> tasks = new LinkedList<>(); @ProtoField(id = 5) private List<String> inputParameters = new LinkedList<>(); @ProtoField(id = 6) private Map<String, Object> outputParameters = new HashMap<>(); @ProtoField(id = 7) private String failureWorkflow; @ProtoField(id = 8) @Min(value = 2, message = "workflowDef schemaVersion: {value} is only supported") @Max(value = 2, message = "workflowDef schemaVersion: {value} is only supported") private int schemaVersion = 2; // By default a workflow is restartable @ProtoField(id = 9) private boolean restartable = true; @ProtoField(id = 10) private boolean workflowStatusListenerEnabled = false; @ProtoField(id = 11) @OwnerEmailMandatoryConstraint private String ownerEmail; @ProtoField(id = 12) private TimeoutPolicy timeoutPolicy = TimeoutPolicy.ALERT_ONLY; @ProtoField(id = 13) @NotNull private long timeoutSeconds; @ProtoField(id = 14) private Map<String, Object> variables = new HashMap<>(); @ProtoField(id = 15) private Map<String, Object> inputTemplate = new HashMap<>(); @ProtoField(id = 17) private String workflowStatusListenerSink; @ProtoField(id = 18) private RateLimitConfig rateLimitConfig; @ProtoField(id = 19) private SchemaDef inputSchema; @ProtoField(id = 20) private SchemaDef outputSchema; @ProtoField(id = 21) private boolean enforceSchema = true; @ProtoField(id = 22) private Map<String, Object> metadata = new HashMap<>(); @ProtoField(id = 23) private CacheConfig cacheConfig; @ProtoField(id = 24) private List<String> maskedFields = new ArrayList<>(); public static String getKey(String name, int version) { return name + "." + version; } public boolean isEnforceSchema() { return enforceSchema; } public void setEnforceSchema(boolean enforceSchema) { this.enforceSchema = enforceSchema; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the tasks */ public List<WorkflowTask> getTasks() { return tasks; } /** * @param tasks the tasks to set */ public void setTasks(List<@Valid WorkflowTask> tasks) { this.tasks = tasks; } /** * @return the inputParameters */ public List<String> getInputParameters() { return inputParameters; } /** * @param inputParameters the inputParameters to set */ public void setInputParameters(List<String> inputParameters) { this.inputParameters = inputParameters; } /** * @return the outputParameters */ public Map<String, Object> getOutputParameters() { return outputParameters; } /** * @param outputParameters the outputParameters to set */ public void setOutputParameters(Map<String, Object> outputParameters) { this.outputParameters = outputParameters; } /** * @return the version */ public int getVersion() { return version; } /** * @param version the version to set */ public void setVersion(int version) { this.version = version; } /** * @return the failureWorkflow */ public String getFailureWorkflow() { return failureWorkflow; } /** * @param failureWorkflow the failureWorkflow to set */ public void setFailureWorkflow(String failureWorkflow) { this.failureWorkflow = failureWorkflow; } /** * This method determines if the workflow is restartable or not * * @return true: if the workflow is restartable false: if the workflow is non restartable */ public boolean isRestartable() { return restartable; } /** * This method is called only when the workflow definition is created * * @param restartable true: if the workflow is restartable false: if the workflow is non * restartable */ public void setRestartable(boolean restartable) { this.restartable = restartable; } /** * @return the schemaVersion */ public int getSchemaVersion() { return schemaVersion; } /** * @param schemaVersion the schemaVersion to set */ public void setSchemaVersion(int schemaVersion) { this.schemaVersion = schemaVersion; } /** * @return true is workflow listener will be invoked when workflow gets into a terminal state */ public boolean isWorkflowStatusListenerEnabled() { return workflowStatusListenerEnabled; } /** * Specify if workflow listener is enabled to invoke a callback for completed or terminated * workflows * * @param workflowStatusListenerEnabled */ public void setWorkflowStatusListenerEnabled(boolean workflowStatusListenerEnabled) { this.workflowStatusListenerEnabled = workflowStatusListenerEnabled; } /** * @return the email of the owner of this workflow definition */ public String getOwnerEmail() { return ownerEmail; } /** * @param ownerEmail the owner email to set */ public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } /** * @return the timeoutPolicy */ public TimeoutPolicy getTimeoutPolicy() { return timeoutPolicy; } /** * @param timeoutPolicy the timeoutPolicy to set */ public void setTimeoutPolicy(TimeoutPolicy timeoutPolicy) { this.timeoutPolicy = timeoutPolicy; } /** * @return the time after which a workflow is deemed to have timed out */ public long getTimeoutSeconds() { return timeoutSeconds; } /** * @param timeoutSeconds the timeout in seconds to set */ public void setTimeoutSeconds(long timeoutSeconds) { this.timeoutSeconds = timeoutSeconds; } /** * @return the global workflow variables */ public Map<String, Object> getVariables() { return variables; } /** * @param variables the set of global workflow variables to set */ public void setVariables(Map<String, Object> variables) { this.variables = variables; } public Map<String, Object> getInputTemplate() { return inputTemplate; } public void setInputTemplate(Map<String, Object> inputTemplate) { this.inputTemplate = inputTemplate; } public String key() { return getKey(name, version); } public String getWorkflowStatusListenerSink() { return workflowStatusListenerSink; } public void setWorkflowStatusListenerSink(String workflowStatusListenerSink) { this.workflowStatusListenerSink = workflowStatusListenerSink; } public RateLimitConfig getRateLimitConfig() { return rateLimitConfig; } public void setRateLimitConfig(RateLimitConfig rateLimitConfig) { this.rateLimitConfig = rateLimitConfig; } public SchemaDef getInputSchema() { return inputSchema; } public void setInputSchema(SchemaDef inputSchema) { this.inputSchema = inputSchema; } public SchemaDef getOutputSchema() { return outputSchema; } public void setOutputSchema(SchemaDef outputSchema) { this.outputSchema = outputSchema; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public CacheConfig getCacheConfig() { return cacheConfig; } public void setCacheConfig(final CacheConfig cacheConfig) { this.cacheConfig = cacheConfig; } public List<String> getMaskedFields() { return maskedFields; } public void setMaskedFields(List<String> maskedFields) { this.maskedFields = maskedFields; } public boolean containsType(String taskType) { return collectTasks().stream().anyMatch(t -> t.getType().equals(taskType)); } public WorkflowTask getNextTask(String taskReferenceName) { WorkflowTask workflowTask = getTaskByRefName(taskReferenceName); if (workflowTask != null && TaskType.TERMINATE.name().equals(workflowTask.getType())) { return null; } Iterator<WorkflowTask> iterator = tasks.iterator(); while (iterator.hasNext()) { WorkflowTask task = iterator.next(); if (task.getTaskReferenceName().equals(taskReferenceName)) { // If taskReferenceName matches, break out break; } WorkflowTask nextTask = task.next(taskReferenceName, null); if (nextTask != null) { return nextTask; } else if (TaskType.DO_WHILE.name().equals(task.getType()) && !task.getTaskReferenceName().equals(taskReferenceName) && task.has(taskReferenceName)) { // If the task is child of Loop Task and at last position, return null. return null; } if (task.has(taskReferenceName)) { break; } } if (iterator.hasNext()) { return iterator.next(); } return null; } public WorkflowTask getTaskByRefName(String taskReferenceName) { return collectTasks().stream() .filter( workflowTask -> workflowTask.getTaskReferenceName().equals(taskReferenceName)) .findFirst() .orElse(null); } public List<WorkflowTask> collectTasks() { List<WorkflowTask> tasks = new LinkedList<>(); for (WorkflowTask workflowTask : this.tasks) { tasks.addAll(workflowTask.collectTasks()); } return tasks; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkflowDef that = (WorkflowDef) o; return version == that.version && Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name, version); } @Override public String toString() { return "WorkflowDef{" + "name='" + name + '\'' + ", description='" + description + '\'' + ", version=" + version + ", tasks=" + tasks + ", inputParameters=" + inputParameters + ", outputParameters=" + outputParameters + ", failureWorkflow='" + failureWorkflow + '\'' + ", schemaVersion=" + schemaVersion + ", restartable=" + restartable + ", workflowStatusListenerEnabled=" + workflowStatusListenerEnabled + ", ownerEmail='" + ownerEmail + '\'' + ", timeoutPolicy=" + timeoutPolicy + ", timeoutSeconds=" + timeoutSeconds + ", variables=" + variables + ", inputTemplate=" + inputTemplate + ", workflowStatusListenerSink='" + workflowStatusListenerSink + '\'' + ", rateLimitConfig=" + rateLimitConfig + ", inputSchema=" + inputSchema + ", outputSchema=" + outputSchema + ", enforceSchema=" + enforceSchema + ", maskedFields=" + maskedFields + '}'; } @ProtoEnum public enum TimeoutPolicy { TIME_OUT_WF, ALERT_ONLY } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/RateLimitConfig.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/RateLimitConfig.java
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; /** Rate limit configuration for workflows */ @ProtoMessage public class RateLimitConfig { /** Rate limit policy defining how to handle requests exceeding the limit */ @ProtoEnum public enum RateLimitPolicy { /** Queue the request until capacity is available */ QUEUE, /** Reject the request immediately */ REJECT } /** * Key that defines the rate limit. Rate limit key is a combination of workflow payload such as * name, or correlationId etc. */ @ProtoField(id = 1) private String rateLimitKey; /** Number of concurrently running workflows that are allowed per key */ @ProtoField(id = 2) private int concurrentExecLimit; /** Policy to apply when rate limit is exceeded */ @ProtoField(id = 3) private RateLimitPolicy policy = RateLimitPolicy.QUEUE; public String getRateLimitKey() { return rateLimitKey; } public void setRateLimitKey(String rateLimitKey) { this.rateLimitKey = rateLimitKey; } public int getConcurrentExecLimit() { return concurrentExecLimit; } public void setConcurrentExecLimit(int concurrentExecLimit) { this.concurrentExecLimit = concurrentExecLimit; } public RateLimitPolicy getPolicy() { return policy; } public void setPolicy(RateLimitPolicy policy) { this.policy = policy; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/StateChangeEvent.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/StateChangeEvent.java
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; @Valid @ProtoMessage public class StateChangeEvent { @ProtoField(id = 1) @NotNull private String type; @ProtoField(id = 2) private Map<String, Object> payload; public String getType() { return type; } public void setType(String type) { this.type = type; } public Map<String, Object> getPayload() { return payload; } public void setPayload(Map<String, Object> payload) { this.payload = payload; } @Override public String toString() { return "StateChangeEvent{" + "type='" + type + '\'' + ", payload=" + payload + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/UpgradeWorkflowRequest.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/UpgradeWorkflowRequest.java
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import jakarta.validation.constraints.NotNull; @ProtoMessage public class UpgradeWorkflowRequest { public Map<String, Object> getTaskOutput() { return taskOutput; } public void setTaskOutput(Map<String, Object> taskOutput) { this.taskOutput = taskOutput; } public Map<String, Object> getWorkflowInput() { return workflowInput; } public void setWorkflowInput(Map<String, Object> workflowInput) { this.workflowInput = workflowInput; } @ProtoField(id = 4) private Map<String, Object> taskOutput; @ProtoField(id = 3) private Map<String, Object> workflowInput; @ProtoField(id = 2) private Integer version; @NotNull(message = "Workflow name cannot be null or empty") @ProtoField(id = 1) private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/DynamicForkJoinTask.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/DynamicForkJoinTask.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.HashMap; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.tasks.TaskType; @ProtoMessage public class DynamicForkJoinTask { @ProtoField(id = 1) private String taskName; @ProtoField(id = 2) private String workflowName; @ProtoField(id = 3) private String referenceName; @ProtoField(id = 4) private Map<String, Object> input = new HashMap<>(); @ProtoField(id = 5) private String type = TaskType.SIMPLE.name(); public DynamicForkJoinTask() {} public DynamicForkJoinTask( String taskName, String workflowName, String referenceName, Map<String, Object> input) { super(); this.taskName = taskName; this.workflowName = workflowName; this.referenceName = referenceName; this.input = input; } public DynamicForkJoinTask( String taskName, String workflowName, String referenceName, String type, Map<String, Object> input) { super(); this.taskName = taskName; this.workflowName = workflowName; this.referenceName = referenceName; this.input = input; this.type = type; } public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public String getWorkflowName() { return workflowName; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } public String getReferenceName() { return referenceName; } public void setReferenceName(String referenceName) { this.referenceName = referenceName; } public Map<String, Object> getInput() { return input; } public void setInput(Map<String, Object> input) { this.input = input; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/metadata/workflow/RerunWorkflowRequest.java
common/src/main/java/com/netflix/conductor/common/metadata/workflow/RerunWorkflowRequest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.metadata.workflow; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; @ProtoMessage public class RerunWorkflowRequest { @ProtoField(id = 1) private String reRunFromWorkflowId; @ProtoField(id = 2) private Map<String, Object> workflowInput; @ProtoField(id = 3) private String reRunFromTaskId; @ProtoField(id = 4) private Map<String, Object> taskInput; @ProtoField(id = 5) private String correlationId; public String getReRunFromWorkflowId() { return reRunFromWorkflowId; } public void setReRunFromWorkflowId(String reRunFromWorkflowId) { this.reRunFromWorkflowId = reRunFromWorkflowId; } public Map<String, Object> getWorkflowInput() { return workflowInput; } public void setWorkflowInput(Map<String, Object> workflowInput) { this.workflowInput = workflowInput; } public String getReRunFromTaskId() { return reRunFromTaskId; } public void setReRunFromTaskId(String reRunFromTaskId) { this.reRunFromTaskId = reRunFromTaskId; } public Map<String, Object> getTaskInput() { return taskInput; } public void setTaskInput(Map<String, Object> taskInput) { this.taskInput = taskInput; } public String getCorrelationId() { return correlationId; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/model/BulkResponse.java
common/src/main/java/com/netflix/conductor/common/model/BulkResponse.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.model; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; /** * Response object to return a list of succeeded entities and a map of failed ones, including error * message, for the bulk request. * * @param <T> the type of entities included in the successful results */ public class BulkResponse<T> { /** Key - entityId Value - error message processing this entity */ private final Map<String, String> bulkErrorResults; private final List<T> bulkSuccessfulResults; private final String message = "Bulk Request has been processed."; public BulkResponse() { this.bulkSuccessfulResults = new ArrayList<>(); this.bulkErrorResults = new HashMap<>(); } public List<T> getBulkSuccessfulResults() { return bulkSuccessfulResults; } public Map<String, String> getBulkErrorResults() { return bulkErrorResults; } public void appendSuccessResponse(T result) { bulkSuccessfulResults.add(result); } public void appendFailedResponse(String id, String errorMessage) { bulkErrorResults.put(id, errorMessage); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof BulkResponse that)) { return false; } return Objects.equals(bulkSuccessfulResults, that.bulkSuccessfulResults) && Objects.equals(bulkErrorResults, that.bulkErrorResults); } @Override public int hashCode() { return Objects.hash(bulkSuccessfulResults, bulkErrorResults, message); } @Override public String toString() { return "BulkResponse{" + "bulkSuccessfulResults=" + bulkSuccessfulResults + ", bulkErrorResults=" + bulkErrorResults + ", message='" + message + '\'' + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/utils/SummaryUtil.java
common/src/main/java/com/netflix/conductor/common/utils/SummaryUtil.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import com.netflix.conductor.common.config.ObjectMapperProvider; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.annotation.PostConstruct; @Component public class SummaryUtil { private static final Logger logger = LoggerFactory.getLogger(SummaryUtil.class); private static final ObjectMapper objectMapper = new ObjectMapperProvider().getObjectMapper(); private static boolean isSummaryInputOutputJsonSerializationEnabled; @Value("${conductor.app.summary-input-output-json-serialization.enabled:false}") private boolean isJsonSerializationEnabled; @PostConstruct public void init() { isSummaryInputOutputJsonSerializationEnabled = isJsonSerializationEnabled; } /** * Serializes the Workflow or Task's Input/Output object by Java's toString (default), or by a * Json ObjectMapper (@see Configuration.isSummaryInputOutputJsonSerializationEnabled) * * @param object the Input or Output Object to serialize * @return the serialized string of the Input or Output object */ public static String serializeInputOutput(Map<String, Object> object) { if (!isSummaryInputOutputJsonSerializationEnabled) { return object.toString(); } try { return objectMapper.writeValueAsString(object); } catch (JsonProcessingException e) { logger.error( "The provided value ({}) could not be serialized as Json", object.toString(), e); throw new RuntimeException(e); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/utils/TaskUtils.java
common/src/main/java/com/netflix/conductor/common/utils/TaskUtils.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import com.netflix.conductor.common.config.ObjectMapperProvider; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; public class TaskUtils { private static final ObjectMapper objectMapper; static { ObjectMapperProvider provider = new ObjectMapperProvider(); objectMapper = provider.getObjectMapper(); } private static final String LOOP_TASK_DELIMITER = "__"; public static String appendIteration(String name, int iteration) { return name + LOOP_TASK_DELIMITER + iteration; } public static String getLoopOverTaskRefNameSuffix(int iteration) { return LOOP_TASK_DELIMITER + iteration; } public static String removeIterationFromTaskRefName(String referenceTaskName) { String[] tokens = referenceTaskName.split(TaskUtils.LOOP_TASK_DELIMITER); return tokens.length > 0 ? tokens[0] : referenceTaskName; } public static WorkflowDef convertToWorkflowDef(Object workflowDef) { return objectMapper.convertValue(workflowDef, new TypeReference<WorkflowDef>() {}); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/utils/EnvUtils.java
common/src/main/java/com/netflix/conductor/common/utils/EnvUtils.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.util.Optional; public class EnvUtils { public enum SystemParameters { CPEWF_TASK_ID, NETFLIX_ENV, NETFLIX_STACK } public static boolean isEnvironmentVariable(String test) { for (SystemParameters c : SystemParameters.values()) { if (c.name().equals(test)) { return true; } } String value = Optional.ofNullable(System.getProperty(test)).orElseGet(() -> System.getenv(test)); return value != null; } public static String getSystemParametersValue(String sysParam, String taskId) { if ("CPEWF_TASK_ID".equals(sysParam)) { return taskId; } String value = System.getenv(sysParam); if (value == null) { value = System.getProperty(sysParam); } return value; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/utils/ExternalPayloadStorage.java
common/src/main/java/com/netflix/conductor/common/utils/ExternalPayloadStorage.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.io.InputStream; import com.netflix.conductor.common.run.ExternalStorageLocation; /** * Interface used to externalize the storage of large JSON payloads in workflow and task * input/output */ public interface ExternalPayloadStorage { enum Operation { READ, WRITE } enum PayloadType { WORKFLOW_INPUT, WORKFLOW_OUTPUT, TASK_INPUT, TASK_OUTPUT } /** * Obtain a uri used to store/access a json payload in external storage. * * @param operation the type of {@link Operation} to be performed with the uri * @param payloadType the {@link PayloadType} that is being accessed at the uri * @param path (optional) the relative path for which the external storage location object is to * be populated. If path is not specified, it will be computed and populated. * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the * json payload */ ExternalStorageLocation getLocation(Operation operation, PayloadType payloadType, String path); /** * Obtain an uri used to store/access a json payload in external storage with deduplication of * data based on payloadBytes digest. * * @param operation the type of {@link Operation} to be performed with the uri * @param payloadType the {@link PayloadType} that is being accessed at the uri * @param path (optional) the relative path for which the external storage location object is to * be populated. If path is not specified, it will be computed and populated. * @param payloadBytes for calculating digest which is used for objectKey * @return a {@link ExternalStorageLocation} object which contains the uri and the path for the * json payload */ default ExternalStorageLocation getLocation( Operation operation, PayloadType payloadType, String path, byte[] payloadBytes) { return getLocation(operation, payloadType, path); } /** * Upload a json payload to the specified external storage location. * * @param path the location to which the object is to be uploaded * @param payload an {@link InputStream} containing the json payload which is to be uploaded * @param payloadSize the size of the json payload in bytes */ void upload(String path, InputStream payload, long payloadSize); /** * Download the json payload from the specified external storage location. * * @param path the location from where the object is to be downloaded * @return an {@link InputStream} of the json payload at the specified location */ InputStream download(String path); }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/utils/ConstraintParamUtil.java
common/src/main/java/com/netflix/conductor/common/utils/ConstraintParamUtil.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.utils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.utils.EnvUtils.SystemParameters; import com.jayway.jsonpath.JsonPath; @SuppressWarnings("unchecked") public class ConstraintParamUtil { /** * Validates inputParam and returns a list of errors if input is not valid. * * @param input {@link Map} of inputParameters * @param taskName TaskName of inputParameters * @param workflow WorkflowDef * @return {@link List} of error strings. */ public static List<String> validateInputParam( Map<String, Object> input, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); for (Entry<String, Object> e : input.entrySet()) { Object value = e.getValue(); if (value instanceof String) { errorList.addAll( extractParamPathComponentsFromString( e.getKey(), value.toString(), taskName, workflow)); } else if (value instanceof Map) { // recursive call errorList.addAll( validateInputParam((Map<String, Object>) value, taskName, workflow)); } else if (value instanceof List) { errorList.addAll( extractListInputParam(e.getKey(), (List<?>) value, taskName, workflow)); } else { e.setValue(value); } } return errorList; } private static List<String> extractListInputParam( String key, List<?> values, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); for (Object listVal : values) { if (listVal instanceof String) { errorList.addAll( extractParamPathComponentsFromString( key, listVal.toString(), taskName, workflow)); } else if (listVal instanceof Map) { errorList.addAll( validateInputParam((Map<String, Object>) listVal, taskName, workflow)); } else if (listVal instanceof List) { errorList.addAll(extractListInputParam(key, (List<?>) listVal, taskName, workflow)); } } return errorList; } private static List<String> extractParamPathComponentsFromString( String key, String value, String taskName, WorkflowDef workflow) { ArrayList<String> errorList = new ArrayList<>(); if (value == null) { String message = String.format("key: %s input parameter value: is null", key); errorList.add(message); return errorList; } String[] values = value.split("(?=(?<!\\$)\\$\\{)|(?<=\\})"); for (String s : values) { if (s.startsWith("${") && s.endsWith("}")) { String paramPath = s.substring(2, s.length() - 1); if (!isValidPath(paramPath)) { String message = String.format( "key: %s input parameter value: %s is not valid", key, paramPath); errorList.add(message); } else if (EnvUtils.isEnvironmentVariable(paramPath)) { // if it one of the predefined enums skip validation boolean isPredefinedEnum = false; for (SystemParameters systemParameters : SystemParameters.values()) { if (systemParameters.name().equals(paramPath)) { isPredefinedEnum = true; break; } } if (!isPredefinedEnum) { String sysValue = EnvUtils.getSystemParametersValue(paramPath, ""); if (sysValue == null) { String errorMessage = String.format( "environment variable: %s for given task: %s" + " input value: %s" + " of input parameter: %s is not valid", paramPath, taskName, key, value); errorList.add(errorMessage); } } } // workflow, or task reference name else { String[] components = paramPath.split("\\."); if (!"workflow".equals(components[0])) { WorkflowTask task = workflow.getTaskByRefName(components[0]); if (task == null) { String message = String.format( "taskReferenceName: %s for given task: %s input value: %s of input" + " parameter: %s" + " is not defined in workflow definition.", components[0], taskName, key, value); errorList.add(message); } } } } } return errorList; } public static boolean isValidPath(String path) { try { JsonPath.compile(path); return true; } catch (Exception e) { return false; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/constraints/NoSemiColonConstraint.java
common/src/main/java/com/netflix/conductor/common/constraints/NoSemiColonConstraint.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.commons.lang3.StringUtils; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; /** This constraint checks semi-colon is not allowed in a given string. */ @Documented @Constraint(validatedBy = NoSemiColonConstraint.NoSemiColonValidator.class) @Target({FIELD, PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface NoSemiColonConstraint { String message() default "String: cannot contain the following set of characters: ':'"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class NoSemiColonValidator implements ConstraintValidator<NoSemiColonConstraint, String> { @Override public void initialize(NoSemiColonConstraint constraintAnnotation) {} @Override public boolean isValid(String value, ConstraintValidatorContext context) { boolean valid = true; if (!StringUtils.isEmpty(value) && value.contains(":")) { valid = false; } return valid; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/constraints/OwnerEmailMandatoryConstraint.java
common/src/main/java/com/netflix/conductor/common/constraints/OwnerEmailMandatoryConstraint.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.apache.commons.lang3.StringUtils; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.TYPE; /** * This constraint class validates that owner email is non-empty, but only if configuration says * owner email is mandatory. */ @Documented @Constraint(validatedBy = OwnerEmailMandatoryConstraint.WorkflowTaskValidValidator.class) @Target({TYPE, FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface OwnerEmailMandatoryConstraint { String message() default "ownerEmail cannot be empty"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class WorkflowTaskValidValidator implements ConstraintValidator<OwnerEmailMandatoryConstraint, String> { @Override public void initialize(OwnerEmailMandatoryConstraint constraintAnnotation) {} @Override public boolean isValid(String ownerEmail, ConstraintValidatorContext context) { return !ownerEmailMandatory || !StringUtils.isEmpty(ownerEmail); } private static boolean ownerEmailMandatory = true; public static void setOwnerEmailMandatory(boolean ownerEmailMandatory) { WorkflowTaskValidValidator.ownerEmailMandatory = ownerEmailMandatory; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/constraints/TaskReferenceNameUniqueConstraint.java
common/src/main/java/com/netflix/conductor/common/constraints/TaskReferenceNameUniqueConstraint.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.HashMap; import java.util.List; import org.apache.commons.lang3.mutable.MutableBoolean; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.common.metadata.workflow.WorkflowTask; import com.netflix.conductor.common.utils.ConstraintParamUtil; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import static java.lang.annotation.ElementType.TYPE; /** * This constraint class validates following things. * * <ul> * <li>1. WorkflowDef is valid or not * <li>2. Make sure taskReferenceName used across different tasks are unique * <li>3. Verify inputParameters points to correct tasks or not * </ul> */ @Documented @Constraint(validatedBy = TaskReferenceNameUniqueConstraint.TaskReferenceNameUniqueValidator.class) @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TaskReferenceNameUniqueConstraint { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class TaskReferenceNameUniqueValidator implements ConstraintValidator<TaskReferenceNameUniqueConstraint, WorkflowDef> { @Override public void initialize(TaskReferenceNameUniqueConstraint constraintAnnotation) {} @Override public boolean isValid(WorkflowDef workflowDef, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean valid = true; // check if taskReferenceNames are unique across tasks or not HashMap<String, Integer> taskReferenceMap = new HashMap<>(); for (WorkflowTask workflowTask : workflowDef.collectTasks()) { if (taskReferenceMap.containsKey(workflowTask.getTaskReferenceName())) { String message = String.format( "taskReferenceName: %s should be unique across tasks for a given workflowDefinition: %s", workflowTask.getTaskReferenceName(), workflowDef.getName()); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); valid = false; } else { taskReferenceMap.put(workflowTask.getTaskReferenceName(), 1); } } // check inputParameters points to valid taskDef return valid & verifyTaskInputParameters(context, workflowDef); } private boolean verifyTaskInputParameters( ConstraintValidatorContext context, WorkflowDef workflow) { MutableBoolean valid = new MutableBoolean(); valid.setValue(true); if (workflow.getTasks() == null) { return valid.getValue(); } workflow.getTasks().stream() .filter(workflowTask -> workflowTask.getInputParameters() != null) .forEach( workflowTask -> { List<String> errors = ConstraintParamUtil.validateInputParam( workflowTask.getInputParameters(), workflowTask.getName(), workflow); errors.forEach( message -> context.buildConstraintViolationWithTemplate( message) .addConstraintViolation()); if (errors.size() > 0) { valid.setValue(false); } }); return valid.getValue(); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/constraints/ValidNameConstraint.java
common/src/main/java/com/netflix/conductor/common/constraints/ValidNameConstraint.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Value; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import static java.lang.annotation.ElementType.FIELD; /** * This constraint class validates following things. * * <ul> * <li>1. Name is valid or not * </ul> */ @Documented @Constraint(validatedBy = ValidNameConstraint.NameValidator.class) @Target({FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface ValidNameConstraint { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class NameValidator implements ConstraintValidator<ValidNameConstraint, String> { private static final String NAME_PATTERN = "^[A-Za-z0-9_<>{}#\\s-]+$"; public static final String INVALID_NAME_MESSAGE = "Allowed characters are alphanumeric, underscores, spaces, hyphens, and special characters like <, >, {, }, #"; @Value("${conductor.app.workflow.name-validation.enabled}") private boolean nameValidationEnabled; @Override public void initialize(ValidNameConstraint constraintAnnotation) {} @Override public boolean isValid(String name, ConstraintValidatorContext context) { boolean valid = name == null || !nameValidationEnabled || name.matches(NAME_PATTERN); if (!valid) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate( "Invalid name '" + name + "'. " + INVALID_NAME_MESSAGE) .addConstraintViolation(); } return valid; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/constraints/TaskTimeoutConstraint.java
common/src/main/java/com/netflix/conductor/common/constraints/TaskTimeoutConstraint.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.constraints; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.netflix.conductor.common.metadata.tasks.TaskDef; import jakarta.validation.Constraint; import jakarta.validation.ConstraintValidator; import jakarta.validation.ConstraintValidatorContext; import jakarta.validation.Payload; import static java.lang.annotation.ElementType.TYPE; /** * This constraint checks for a given task responseTimeoutSeconds should be less than * timeoutSeconds. */ @Documented @Constraint(validatedBy = TaskTimeoutConstraint.TaskTimeoutValidator.class) @Target({TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface TaskTimeoutConstraint { String message() default ""; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; class TaskTimeoutValidator implements ConstraintValidator<TaskTimeoutConstraint, TaskDef> { @Override public void initialize(TaskTimeoutConstraint constraintAnnotation) {} @Override public boolean isValid(TaskDef taskDef, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); boolean valid = true; if (taskDef.getTimeoutSeconds() > 0) { if (taskDef.getResponseTimeoutSeconds() > taskDef.getTimeoutSeconds()) { valid = false; String message = String.format( "TaskDef: %s responseTimeoutSeconds: %d must be less than timeoutSeconds: %d", taskDef.getName(), taskDef.getResponseTimeoutSeconds(), taskDef.getTimeoutSeconds()); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } } // Check if timeoutSeconds is greater than totalTimeoutSeconds if (taskDef.getTimeoutSeconds() > 0 && taskDef.getTotalTimeoutSeconds() > 0 && taskDef.getTimeoutSeconds() > taskDef.getTotalTimeoutSeconds()) { valid = false; String message = String.format( "TaskDef: %s timeoutSeconds: %d must be less than or equal to totalTimeoutSeconds: %d", taskDef.getName(), taskDef.getTimeoutSeconds(), taskDef.getTotalTimeoutSeconds()); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); } return valid; } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/WorkflowSummaryExtended.java
common/src/main/java/com/netflix/conductor/common/run/WorkflowSummaryExtended.java
/* * Copyright 2025 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.util.Map; import com.netflix.conductor.annotations.protogen.ProtoField; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; /** Extended version of WorkflowSummary that retains input/output as Map */ public class WorkflowSummaryExtended extends WorkflowSummary { @ProtoField(id = 9) // Ensure Protobuf compatibility @JsonIgnore private Map<String, Object> inputMap; @ProtoField(id = 10) @JsonIgnore private Map<String, Object> outputMap; public WorkflowSummaryExtended(Workflow workflow) { super(workflow); if (workflow.getInput() != null) { this.inputMap = workflow.getInput(); } if (workflow.getOutput() != null) { this.outputMap = workflow.getOutput(); } } /** New method for JSON serialization */ @JsonProperty("input") public Map<String, Object> getInputMap() { return inputMap; } /** New method for JSON serialization */ @JsonProperty("output") public Map<String, Object> getOutputMap() { return outputMap; } public void setInputMap(Map<String, Object> inputMap) { this.inputMap = inputMap; } public void setOutputMap(Map<String, Object> outputMap) { this.outputMap = outputMap; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/ExternalStorageLocation.java
common/src/main/java/com/netflix/conductor/common/run/ExternalStorageLocation.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; /** * Describes the location where the JSON payload is stored in external storage. * * <p>The location is described using the following fields: * * <ul> * <li>uri: The uri of the json file in external storage. * <li>path: The relative path of the file in external storage. * </ul> */ public class ExternalStorageLocation { private String uri; private String path; public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "ExternalStorageLocation{" + "uri='" + uri + '\'' + ", path='" + path + '\'' + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/TaskSummary.java
common/src/main/java/com/netflix/conductor/common/run/TaskSummary.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Objects; import java.util.TimeZone; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.tasks.Task.Status; import com.netflix.conductor.common.utils.SummaryUtil; @ProtoMessage public class TaskSummary { /** The time should be stored as GMT */ private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); @ProtoField(id = 1) private String workflowId; @ProtoField(id = 2) private String workflowType; @ProtoField(id = 3) private String correlationId; @ProtoField(id = 4) private String scheduledTime; @ProtoField(id = 5) private String startTime; @ProtoField(id = 6) private String updateTime; @ProtoField(id = 7) private String endTime; @ProtoField(id = 8) private Task.Status status; @ProtoField(id = 9) private String reasonForIncompletion; @ProtoField(id = 10) private long executionTime; @ProtoField(id = 11) private long queueWaitTime; @ProtoField(id = 12) private String taskDefName; @ProtoField(id = 13) private String taskType; @ProtoField(id = 14) private String input; @ProtoField(id = 15) private String output; @ProtoField(id = 16) private String taskId; @ProtoField(id = 17) private String externalInputPayloadStoragePath; @ProtoField(id = 18) private String externalOutputPayloadStoragePath; @ProtoField(id = 19) private int workflowPriority; @ProtoField(id = 20) private String domain; public TaskSummary() {} public TaskSummary(Task task) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(GMT); this.taskId = task.getTaskId(); this.taskDefName = task.getTaskDefName(); this.taskType = task.getTaskType(); this.workflowId = task.getWorkflowInstanceId(); this.workflowType = task.getWorkflowType(); this.workflowPriority = task.getWorkflowPriority(); this.correlationId = task.getCorrelationId(); this.scheduledTime = sdf.format(new Date(task.getScheduledTime())); this.startTime = sdf.format(new Date(task.getStartTime())); this.updateTime = sdf.format(new Date(task.getUpdateTime())); this.endTime = sdf.format(new Date(task.getEndTime())); this.status = task.getStatus(); this.reasonForIncompletion = task.getReasonForIncompletion(); this.queueWaitTime = task.getQueueWaitTime(); this.domain = task.getDomain(); if (task.getInputData() != null) { this.input = SummaryUtil.serializeInputOutput(task.getInputData()); } if (task.getOutputData() != null) { this.output = SummaryUtil.serializeInputOutput(task.getOutputData()); } if (task.getEndTime() > 0) { this.executionTime = task.getEndTime() - task.getStartTime(); } if (StringUtils.isNotBlank(task.getExternalInputPayloadStoragePath())) { this.externalInputPayloadStoragePath = task.getExternalInputPayloadStoragePath(); } if (StringUtils.isNotBlank(task.getExternalOutputPayloadStoragePath())) { this.externalOutputPayloadStoragePath = task.getExternalOutputPayloadStoragePath(); } } /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @param workflowId the workflowId to set */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * @return the workflowType */ public String getWorkflowType() { return workflowType; } /** * @param workflowType the workflowType to set */ public void setWorkflowType(String workflowType) { this.workflowType = workflowType; } /** * @return the correlationId */ public String getCorrelationId() { return correlationId; } /** * @param correlationId the correlationId to set */ public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } /** * @return the scheduledTime */ public String getScheduledTime() { return scheduledTime; } /** * @param scheduledTime the scheduledTime to set */ public void setScheduledTime(String scheduledTime) { this.scheduledTime = scheduledTime; } /** * @return the startTime */ public String getStartTime() { return startTime; } /** * @param startTime the startTime to set */ public void setStartTime(String startTime) { this.startTime = startTime; } /** * @return the updateTime */ public String getUpdateTime() { return updateTime; } /** * @param updateTime the updateTime to set */ public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } /** * @return the endTime */ public String getEndTime() { return endTime; } /** * @param endTime the endTime to set */ public void setEndTime(String endTime) { this.endTime = endTime; } /** * @return the status */ public Status getStatus() { return status; } /** * @param status the status to set */ public void setStatus(Status status) { this.status = status; } /** * @return the reasonForIncompletion */ public String getReasonForIncompletion() { return reasonForIncompletion; } /** * @param reasonForIncompletion the reasonForIncompletion to set */ public void setReasonForIncompletion(String reasonForIncompletion) { this.reasonForIncompletion = reasonForIncompletion; } /** * @return the executionTime */ public long getExecutionTime() { return executionTime; } /** * @param executionTime the executionTime to set */ public void setExecutionTime(long executionTime) { this.executionTime = executionTime; } /** * @return the queueWaitTime */ public long getQueueWaitTime() { return queueWaitTime; } /** * @param queueWaitTime the queueWaitTime to set */ public void setQueueWaitTime(long queueWaitTime) { this.queueWaitTime = queueWaitTime; } /** * @return the taskDefName */ public String getTaskDefName() { return taskDefName; } /** * @param taskDefName the taskDefName to set */ public void setTaskDefName(String taskDefName) { this.taskDefName = taskDefName; } /** * @return the taskType */ public String getTaskType() { return taskType; } /** * @param taskType the taskType to set */ public void setTaskType(String taskType) { this.taskType = taskType; } /** * @return input to the task */ public String getInput() { return input; } /** * @param input input to the task */ public void setInput(String input) { this.input = input; } /** * @return output of the task */ public String getOutput() { return output; } /** * @param output Task output */ public void setOutput(String output) { this.output = output; } /** * @return the taskId */ public String getTaskId() { return taskId; } /** * @param taskId the taskId to set */ public void setTaskId(String taskId) { this.taskId = taskId; } /** * @return the external storage path for the task input payload */ public String getExternalInputPayloadStoragePath() { return externalInputPayloadStoragePath; } /** * @param externalInputPayloadStoragePath the external storage path where the task input payload * is stored */ public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; } /** * @return the external storage path for the task output payload */ public String getExternalOutputPayloadStoragePath() { return externalOutputPayloadStoragePath; } /** * @param externalOutputPayloadStoragePath the external storage path where the task output * payload is stored */ public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) { this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath; } /** * @return the priority defined on workflow */ public int getWorkflowPriority() { return workflowPriority; } /** * @param workflowPriority Priority defined for workflow */ public void setWorkflowPriority(int workflowPriority) { this.workflowPriority = workflowPriority; } /** * @return the domain that the task was scheduled in */ public String getDomain() { return domain; } /** * @param domain The domain that the task was scheduled in */ public void setDomain(String domain) { this.domain = domain; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TaskSummary that = (TaskSummary) o; return getExecutionTime() == that.getExecutionTime() && getQueueWaitTime() == that.getQueueWaitTime() && getWorkflowPriority() == that.getWorkflowPriority() && getWorkflowId().equals(that.getWorkflowId()) && getWorkflowType().equals(that.getWorkflowType()) && Objects.equals(getCorrelationId(), that.getCorrelationId()) && getScheduledTime().equals(that.getScheduledTime()) && Objects.equals(getStartTime(), that.getStartTime()) && Objects.equals(getUpdateTime(), that.getUpdateTime()) && Objects.equals(getEndTime(), that.getEndTime()) && getStatus() == that.getStatus() && Objects.equals(getReasonForIncompletion(), that.getReasonForIncompletion()) && Objects.equals(getTaskDefName(), that.getTaskDefName()) && getTaskType().equals(that.getTaskType()) && getTaskId().equals(that.getTaskId()) && Objects.equals(getDomain(), that.getDomain()); } @Override public int hashCode() { return Objects.hash( getWorkflowId(), getWorkflowType(), getCorrelationId(), getScheduledTime(), getStartTime(), getUpdateTime(), getEndTime(), getStatus(), getReasonForIncompletion(), getExecutionTime(), getQueueWaitTime(), getTaskDefName(), getTaskType(), getTaskId(), getWorkflowPriority(), getDomain()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/WorkflowTestRequest.java
common/src/main/java/com/netflix/conductor/common/run/WorkflowTestRequest.java
/* * Copyright 2023 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.util.HashMap; import java.util.List; import java.util.Map; import com.netflix.conductor.common.metadata.tasks.TaskResult; import com.netflix.conductor.common.metadata.workflow.StartWorkflowRequest; public class WorkflowTestRequest extends StartWorkflowRequest { // Map of task reference name to mock output for the task private Map<String, List<TaskMock>> taskRefToMockOutput = new HashMap<>(); // If there are sub-workflows inside the workflow // The map of task reference name to the mock for the sub-workflow private Map<String, WorkflowTestRequest> subWorkflowTestRequest = new HashMap<>(); public static class TaskMock { private TaskResult.Status status = TaskResult.Status.COMPLETED; private Map<String, Object> output; private long executionTime; // Time in millis for the execution of the task. Useful for // simulating timeout conditions private long queueWaitTime; // Time in millis for the wait time in the queue. public TaskMock() {} public TaskMock(TaskResult.Status status, Map<String, Object> output) { this.status = status; this.output = output; } public TaskResult.Status getStatus() { return status; } public void setStatus(TaskResult.Status status) { this.status = status; } public Map<String, Object> getOutput() { return output; } public void setOutput(Map<String, Object> output) { this.output = output; } public long getExecutionTime() { return executionTime; } public void setExecutionTime(long executionTime) { this.executionTime = executionTime; } public long getQueueWaitTime() { return queueWaitTime; } public void setQueueWaitTime(long queueWaitTime) { this.queueWaitTime = queueWaitTime; } } public Map<String, List<TaskMock>> getTaskRefToMockOutput() { return taskRefToMockOutput; } public void setTaskRefToMockOutput(Map<String, List<TaskMock>> taskRefToMockOutput) { this.taskRefToMockOutput = taskRefToMockOutput; } public Map<String, WorkflowTestRequest> getSubWorkflowTestRequest() { return subWorkflowTestRequest; } public void setSubWorkflowTestRequest(Map<String, WorkflowTestRequest> subWorkflowTestRequest) { this.subWorkflowTestRequest = subWorkflowTestRequest; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/Workflow.java
common/src/main/java/com/netflix/conductor/common/run/Workflow.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.util.*; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.metadata.Auditable; import com.netflix.conductor.common.metadata.tasks.Task; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import jakarta.validation.constraints.Max; import jakarta.validation.constraints.Min; @ProtoMessage public class Workflow extends Auditable { @ProtoEnum public enum WorkflowStatus { RUNNING(false, false), COMPLETED(true, true), FAILED(true, false), TIMED_OUT(true, false), TERMINATED(true, false), PAUSED(false, true); private final boolean terminal; private final boolean successful; WorkflowStatus(boolean terminal, boolean successful) { this.terminal = terminal; this.successful = successful; } public boolean isTerminal() { return terminal; } public boolean isSuccessful() { return successful; } } @ProtoField(id = 1) private WorkflowStatus status = WorkflowStatus.RUNNING; @ProtoField(id = 2) private long endTime; @ProtoField(id = 3) private String workflowId; @ProtoField(id = 4) private String parentWorkflowId; @ProtoField(id = 5) private String parentWorkflowTaskId; @ProtoField(id = 6) private List<Task> tasks = new LinkedList<>(); @ProtoField(id = 8) private Map<String, Object> input = new HashMap<>(); @ProtoField(id = 9) private Map<String, Object> output = new HashMap<>(); // ids 10,11 are reserved @ProtoField(id = 12) private String correlationId; @ProtoField(id = 13) private String reRunFromWorkflowId; @ProtoField(id = 14) private String reasonForIncompletion; // id 15 is reserved @ProtoField(id = 16) private String event; @ProtoField(id = 17) private Map<String, String> taskToDomain = new HashMap<>(); @ProtoField(id = 18) private Set<String> failedReferenceTaskNames = new HashSet<>(); @ProtoField(id = 19) private WorkflowDef workflowDefinition; @ProtoField(id = 20) private String externalInputPayloadStoragePath; @ProtoField(id = 21) private String externalOutputPayloadStoragePath; @ProtoField(id = 22) @Min(value = 0, message = "workflow priority: ${validatedValue} should be minimum {value}") @Max(value = 99, message = "workflow priority: ${validatedValue} should be maximum {value}") private int priority; @ProtoField(id = 23) private Map<String, Object> variables = new HashMap<>(); @ProtoField(id = 24) private long lastRetriedTime; @ProtoField(id = 25) private Set<String> failedTaskNames = new HashSet<>(); @ProtoField(id = 26) private List<Workflow> history = new LinkedList<>(); private String idempotencyKey; private String rateLimitKey; private boolean rateLimited; public Workflow() {} public String getIdempotencyKey() { return idempotencyKey; } public void setIdempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; } public String getRateLimitKey() { return rateLimitKey; } public void setRateLimitKey(String rateLimitKey) { this.rateLimitKey = rateLimitKey; } public boolean isRateLimited() { return rateLimited; } public void setRateLimited(boolean rateLimited) { this.rateLimited = rateLimited; } public List<Workflow> getHistory() { return history; } public void setHistory(List<Workflow> history) { this.history = history; } /** * @return the status */ public WorkflowStatus getStatus() { return status; } /** * @param status the status to set */ public void setStatus(WorkflowStatus status) { this.status = status; } /** * @return the startTime */ public long getStartTime() { return getCreateTime(); } /** * @param startTime the startTime to set */ public void setStartTime(long startTime) { this.setCreateTime(startTime); } /** * @return the endTime */ public long getEndTime() { return endTime; } /** * @param endTime the endTime to set */ public void setEndTime(long endTime) { this.endTime = endTime; } /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @param workflowId the workflowId to set */ public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } /** * @return the tasks which are scheduled, in progress or completed. */ public List<Task> getTasks() { return tasks; } /** * @param tasks the tasks to set */ public void setTasks(List<Task> tasks) { this.tasks = tasks; } /** * @return the input */ public Map<String, Object> getInput() { return input; } /** * @param input the input to set */ public void setInput(Map<String, Object> input) { if (input == null) { input = new HashMap<>(); } this.input = input; } /** * @return the task to domain map */ public Map<String, String> getTaskToDomain() { return taskToDomain; } /** * @param taskToDomain the task to domain map */ public void setTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; } /** * @return the output */ public Map<String, Object> getOutput() { return output; } /** * @param output the output to set */ public void setOutput(Map<String, Object> output) { if (output == null) { output = new HashMap<>(); } this.output = output; } /** * @return The correlation id used when starting the workflow */ public String getCorrelationId() { return correlationId; } /** * @param correlationId the correlation id */ public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public String getReRunFromWorkflowId() { return reRunFromWorkflowId; } public void setReRunFromWorkflowId(String reRunFromWorkflowId) { this.reRunFromWorkflowId = reRunFromWorkflowId; } public String getReasonForIncompletion() { return reasonForIncompletion; } public void setReasonForIncompletion(String reasonForIncompletion) { this.reasonForIncompletion = reasonForIncompletion; } /** * @return the parentWorkflowId */ public String getParentWorkflowId() { return parentWorkflowId; } /** * @param parentWorkflowId the parentWorkflowId to set */ public void setParentWorkflowId(String parentWorkflowId) { this.parentWorkflowId = parentWorkflowId; } /** * @return the parentWorkflowTaskId */ public String getParentWorkflowTaskId() { return parentWorkflowTaskId; } /** * @param parentWorkflowTaskId the parentWorkflowTaskId to set */ public void setParentWorkflowTaskId(String parentWorkflowTaskId) { this.parentWorkflowTaskId = parentWorkflowTaskId; } /** * @return Name of the event that started the workflow */ public String getEvent() { return event; } /** * @param event Name of the event that started the workflow */ public void setEvent(String event) { this.event = event; } public Set<String> getFailedReferenceTaskNames() { return failedReferenceTaskNames; } public void setFailedReferenceTaskNames(Set<String> failedReferenceTaskNames) { this.failedReferenceTaskNames = failedReferenceTaskNames; } public WorkflowDef getWorkflowDefinition() { return workflowDefinition; } public void setWorkflowDefinition(WorkflowDef workflowDefinition) { this.workflowDefinition = workflowDefinition; } /** * @return the external storage path of the workflow input payload */ public String getExternalInputPayloadStoragePath() { return externalInputPayloadStoragePath; } /** * @param externalInputPayloadStoragePath the external storage path where the workflow input * payload is stored */ public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; } /** * @return the external storage path of the workflow output payload */ public String getExternalOutputPayloadStoragePath() { return externalOutputPayloadStoragePath; } /** * @return the priority to define on tasks */ public int getPriority() { return priority; } /** * @param priority priority of tasks (between 0 and 99) */ public void setPriority(int priority) { if (priority < 0 || priority > 99) { throw new IllegalArgumentException("priority MUST be between 0 and 99 (inclusive)"); } this.priority = priority; } /** * Convenience method for accessing the workflow definition name. * * @return the workflow definition name. */ public String getWorkflowName() { if (workflowDefinition == null) { throw new NullPointerException("Workflow definition is null"); } return workflowDefinition.getName(); } /** * Convenience method for accessing the workflow definition version. * * @return the workflow definition version. */ public int getWorkflowVersion() { if (workflowDefinition == null) { throw new NullPointerException("Workflow definition is null"); } return workflowDefinition.getVersion(); } /** * @param externalOutputPayloadStoragePath the external storage path where the workflow output * payload is stored */ public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) { this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath; } /** * @return the global workflow variables */ public Map<String, Object> getVariables() { return variables; } /** * @param variables the set of global workflow variables to set */ public void setVariables(Map<String, Object> variables) { this.variables = variables; } /** * Captures the last time the workflow was retried * * @return the last retried time of the workflow */ public long getLastRetriedTime() { return lastRetriedTime; } /** * @param lastRetriedTime time in milliseconds when the workflow is retried */ public void setLastRetriedTime(long lastRetriedTime) { this.lastRetriedTime = lastRetriedTime; } public boolean hasParent() { return StringUtils.isNotEmpty(parentWorkflowId); } public Set<String> getFailedTaskNames() { return failedTaskNames; } public void setFailedTaskNames(Set<String> failedTaskNames) { this.failedTaskNames = failedTaskNames; } public Task getTaskByRefName(String refName) { if (refName == null) { throw new RuntimeException( "refName passed is null. Check the workflow execution. For dynamic tasks, make sure referenceTaskName is set to a not null value"); } LinkedList<Task> found = new LinkedList<>(); for (Task t : tasks) { if (t.getReferenceTaskName() == null) { throw new RuntimeException( "Task " + t.getTaskDefName() + ", seq=" + t.getSeq() + " does not have reference name specified."); } if (t.getReferenceTaskName().equals(refName)) { found.add(t); } } if (found.isEmpty()) { return null; } return found.getLast(); } /** * @return a deep copy of the workflow instance */ public Workflow copy() { Workflow copy = new Workflow(); copy.setInput(input); copy.setOutput(output); copy.setStatus(status); copy.setWorkflowId(workflowId); copy.setParentWorkflowId(parentWorkflowId); copy.setParentWorkflowTaskId(parentWorkflowTaskId); copy.setReRunFromWorkflowId(reRunFromWorkflowId); copy.setCorrelationId(correlationId); copy.setEvent(event); copy.setReasonForIncompletion(reasonForIncompletion); copy.setWorkflowDefinition(workflowDefinition); copy.setPriority(priority); copy.setTasks(tasks.stream().map(Task::deepCopy).collect(Collectors.toList())); copy.setVariables(variables); copy.setEndTime(endTime); copy.setLastRetriedTime(lastRetriedTime); copy.setTaskToDomain(taskToDomain); copy.setFailedReferenceTaskNames(failedReferenceTaskNames); copy.setExternalInputPayloadStoragePath(externalInputPayloadStoragePath); copy.setExternalOutputPayloadStoragePath(externalOutputPayloadStoragePath); return copy; } @Override public String toString() { String name = workflowDefinition != null ? workflowDefinition.getName() : null; Integer version = workflowDefinition != null ? workflowDefinition.getVersion() : null; return String.format("%s.%s/%s.%s", name, version, workflowId, status); } /** * A string representation of all relevant fields that identify this workflow. Intended for use * in log and other system generated messages. */ public String toShortString() { String name = workflowDefinition != null ? workflowDefinition.getName() : null; Integer version = workflowDefinition != null ? workflowDefinition.getVersion() : null; return String.format("%s.%s/%s", name, version, workflowId); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Workflow workflow = (Workflow) o; return Objects.equals(getWorkflowId(), workflow.getWorkflowId()); } @Override public int hashCode() { return Objects.hash(getWorkflowId()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/WorkflowSummary.java
common/src/main/java/com/netflix/conductor/common/run/WorkflowSummary.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TimeZone; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.common.run.Workflow.WorkflowStatus; import com.netflix.conductor.common.utils.SummaryUtil; /** Captures workflow summary info to be indexed in Elastic Search. */ @ProtoMessage public class WorkflowSummary { /** The time should be stored as GMT */ private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); @ProtoField(id = 1) private String workflowType; @ProtoField(id = 2) private int version; @ProtoField(id = 3) private String workflowId; @ProtoField(id = 4) private String correlationId; @ProtoField(id = 5) private String startTime; @ProtoField(id = 6) private String updateTime; @ProtoField(id = 7) private String endTime; @ProtoField(id = 8) private Workflow.WorkflowStatus status; @ProtoField(id = 9) private String input; @ProtoField(id = 10) private String output; @ProtoField(id = 11) private String reasonForIncompletion; @ProtoField(id = 12) private long executionTime; @ProtoField(id = 13) private String event; @ProtoField(id = 14) private String failedReferenceTaskNames = ""; @ProtoField(id = 15) private String externalInputPayloadStoragePath; @ProtoField(id = 16) private String externalOutputPayloadStoragePath; @ProtoField(id = 17) private int priority; @ProtoField(id = 18) private Set<String> failedTaskNames = new HashSet<>(); @ProtoField(id = 19) private String createdBy; @ProtoField(id = 20) private Map<String, String> taskToDomain = new HashMap<>(); @ProtoField(id = 21) private String idempotencyKey; public WorkflowSummary() {} public WorkflowSummary(Workflow workflow) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); sdf.setTimeZone(GMT); this.workflowType = workflow.getWorkflowName(); this.version = workflow.getWorkflowVersion(); this.workflowId = workflow.getWorkflowId(); this.priority = workflow.getPriority(); this.correlationId = workflow.getCorrelationId(); this.idempotencyKey = workflow.getIdempotencyKey(); if (workflow.getCreateTime() != null) { this.startTime = sdf.format(new Date(workflow.getCreateTime())); } if (workflow.getEndTime() > 0) { this.endTime = sdf.format(new Date(workflow.getEndTime())); } if (workflow.getUpdateTime() != null) { this.updateTime = sdf.format(new Date(workflow.getUpdateTime())); } this.status = workflow.getStatus(); if (workflow.getInput() != null) { this.input = SummaryUtil.serializeInputOutput(workflow.getInput()); } if (workflow.getOutput() != null) { this.output = SummaryUtil.serializeInputOutput(workflow.getOutput()); } this.reasonForIncompletion = workflow.getReasonForIncompletion(); if (workflow.getEndTime() > 0) { this.executionTime = workflow.getEndTime() - workflow.getStartTime(); } this.event = workflow.getEvent(); this.failedReferenceTaskNames = workflow.getFailedReferenceTaskNames().stream().collect(Collectors.joining(",")); this.failedTaskNames = workflow.getFailedTaskNames(); if (StringUtils.isNotBlank(workflow.getExternalInputPayloadStoragePath())) { this.externalInputPayloadStoragePath = workflow.getExternalInputPayloadStoragePath(); } if (StringUtils.isNotBlank(workflow.getExternalOutputPayloadStoragePath())) { this.externalOutputPayloadStoragePath = workflow.getExternalOutputPayloadStoragePath(); } if (workflow.getTaskToDomain() != null) { this.taskToDomain = workflow.getTaskToDomain(); } this.createdBy = workflow.getCreatedBy(); } /** * @return the workflowType */ public String getWorkflowType() { return workflowType; } /** * @return the version */ public int getVersion() { return version; } /** * @return the workflowId */ public String getWorkflowId() { return workflowId; } /** * @return the correlationId */ public String getCorrelationId() { return correlationId; } /** * @return the startTime */ public String getStartTime() { return startTime; } /** * @return the endTime */ public String getEndTime() { return endTime; } /** * @return the status */ public WorkflowStatus getStatus() { return status; } /** * @return the input */ public String getInput() { return input; } public long getInputSize() { return input != null ? input.length() : 0; } /** * @return the output */ public String getOutput() { return output; } public long getOutputSize() { return output != null ? output.length() : 0; } /** * @return the reasonForIncompletion */ public String getReasonForIncompletion() { return reasonForIncompletion; } /** * @return the executionTime */ public long getExecutionTime() { return executionTime; } /** * @return the updateTime */ public String getUpdateTime() { return updateTime; } /** * @return The event */ public String getEvent() { return event; } /** * @param event The event */ public void setEvent(String event) { this.event = event; } public String getFailedReferenceTaskNames() { return failedReferenceTaskNames; } public void setFailedReferenceTaskNames(String failedReferenceTaskNames) { this.failedReferenceTaskNames = failedReferenceTaskNames; } public Set<String> getFailedTaskNames() { return failedTaskNames; } public void setFailedTaskNames(Set<String> failedTaskNames) { this.failedTaskNames = failedTaskNames; } public void setWorkflowType(String workflowType) { this.workflowType = workflowType; } public void setVersion(int version) { this.version = version; } public void setWorkflowId(String workflowId) { this.workflowId = workflowId; } public void setCorrelationId(String correlationId) { this.correlationId = correlationId; } public void setStartTime(String startTime) { this.startTime = startTime; } public void setUpdateTime(String updateTime) { this.updateTime = updateTime; } public void setEndTime(String endTime) { this.endTime = endTime; } public void setStatus(WorkflowStatus status) { this.status = status; } public void setInput(String input) { this.input = input; } public void setOutput(String output) { this.output = output; } public void setReasonForIncompletion(String reasonForIncompletion) { this.reasonForIncompletion = reasonForIncompletion; } public void setExecutionTime(long executionTime) { this.executionTime = executionTime; } /** * @return the external storage path of the workflow input payload */ public String getExternalInputPayloadStoragePath() { return externalInputPayloadStoragePath; } /** * @param externalInputPayloadStoragePath the external storage path where the workflow input * payload is stored */ public void setExternalInputPayloadStoragePath(String externalInputPayloadStoragePath) { this.externalInputPayloadStoragePath = externalInputPayloadStoragePath; } /** * @return the external storage path of the workflow output payload */ public String getExternalOutputPayloadStoragePath() { return externalOutputPayloadStoragePath; } /** * @param externalOutputPayloadStoragePath the external storage path where the workflow output * payload is stored */ public void setExternalOutputPayloadStoragePath(String externalOutputPayloadStoragePath) { this.externalOutputPayloadStoragePath = externalOutputPayloadStoragePath; } /** * @return the priority to define on tasks */ public int getPriority() { return priority; } /** * @param priority priority of tasks (between 0 and 99) */ public void setPriority(int priority) { this.priority = priority; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Map<String, String> getTaskToDomain() { return taskToDomain; } public void setTaskToDomain(Map<String, String> taskToDomain) { this.taskToDomain = taskToDomain; } public String getIdempotencyKey() { return idempotencyKey; } public void setIdempotencyKey(String idempotencyKey) { this.idempotencyKey = idempotencyKey; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WorkflowSummary that = (WorkflowSummary) o; return getVersion() == that.getVersion() && getExecutionTime() == that.getExecutionTime() && getPriority() == that.getPriority() && getWorkflowType().equals(that.getWorkflowType()) && getWorkflowId().equals(that.getWorkflowId()) && Objects.equals(getCorrelationId(), that.getCorrelationId()) && Objects.equals(getIdempotencyKey(), that.getIdempotencyKey()) && StringUtils.equals(getStartTime(), that.getStartTime()) && StringUtils.equals(getUpdateTime(), that.getUpdateTime()) && StringUtils.equals(getEndTime(), that.getEndTime()) && getStatus() == that.getStatus() && Objects.equals(getReasonForIncompletion(), that.getReasonForIncompletion()) && Objects.equals(getEvent(), that.getEvent()) && Objects.equals(getCreatedBy(), that.getCreatedBy()) && Objects.equals(getTaskToDomain(), that.getTaskToDomain()); } @Override public int hashCode() { return Objects.hash( getWorkflowType(), getVersion(), getWorkflowId(), getCorrelationId(), getIdempotencyKey(), getStartTime(), getUpdateTime(), getEndTime(), getStatus(), getReasonForIncompletion(), getExecutionTime(), getEvent(), getPriority(), getCreatedBy(), getTaskToDomain()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/run/SearchResult.java
common/src/main/java/com/netflix/conductor/common/run/SearchResult.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.run; import java.util.List; public class SearchResult<T> { private long totalHits; private List<T> results; public SearchResult() {} public SearchResult(long totalHits, List<T> results) { super(); this.totalHits = totalHits; this.results = results; } /** * @return the totalHits */ public long getTotalHits() { return totalHits; } /** * @return the results */ public List<T> getResults() { return results; } /** * @param totalHits the totalHits to set */ public void setTotalHits(long totalHits) { this.totalHits = totalHits; } /** * @param results the results to set */ public void setResults(List<T> results) { this.results = results; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperProvider.java
common/src/main/java/com/netflix/conductor/common/config/ObjectMapperProvider.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.config; import com.netflix.conductor.common.jackson.JsonProtoModule; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import com.fasterxml.jackson.module.kotlin.KotlinModule; /** * A Factory class for creating a customized {@link ObjectMapper}. This is only used by the * conductor-client module and tests that rely on {@link ObjectMapper}. See * TestObjectMapperConfiguration. */ public class ObjectMapperProvider { private static final ObjectMapper objectMapper = _getObjectMapper(); /** * The customizations in this method are configured using {@link * org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration} * * <p>Customizations are spread across, 1. {@link ObjectMapperBuilderConfiguration} 2. {@link * ObjectMapperConfiguration} 3. {@link JsonProtoModule} * * <p>IMPORTANT: Changes in this method need to be also performed in the default {@link * ObjectMapper} that Spring Boot creates. * * @see org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration */ public ObjectMapper getObjectMapper() { return objectMapper; } private static ObjectMapper _getObjectMapper() { final ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false); objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false); objectMapper.setDefaultPropertyInclusion( JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS)); objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); objectMapper.registerModule(new JsonProtoModule()); objectMapper.registerModule(new JavaTimeModule()); objectMapper.registerModule(new AfterburnerModule()); objectMapper.registerModule(new KotlinModule.Builder().build()); return objectMapper; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperBuilderConfiguration.java
common/src/main/java/com/netflix/conductor/common/config/ObjectMapperBuilderConfiguration.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.config; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES; import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES; @Configuration public class ObjectMapperBuilderConfiguration { /** Disable features like {@link ObjectMapperProvider#getObjectMapper()}. */ @Bean public Jackson2ObjectMapperBuilderCustomizer conductorJackson2ObjectMapperBuilderCustomizer() { return builder -> builder.featuresToDisable( FAIL_ON_UNKNOWN_PROPERTIES, FAIL_ON_IGNORED_PROPERTIES, FAIL_ON_NULL_FOR_PRIMITIVES); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/config/ObjectMapperConfiguration.java
common/src/main/java/com/netflix/conductor/common/config/ObjectMapperConfiguration.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.config; import org.springframework.context.annotation.Configuration; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.module.afterburner.AfterburnerModule; import jakarta.annotation.PostConstruct; @Configuration public class ObjectMapperConfiguration { private final ObjectMapper objectMapper; public ObjectMapperConfiguration(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** Set default property inclusion like {@link ObjectMapperProvider#getObjectMapper()}. */ @PostConstruct public void customizeDefaultObjectMapper() { objectMapper.setDefaultPropertyInclusion( JsonInclude.Value.construct( JsonInclude.Include.NON_NULL, JsonInclude.Include.ALWAYS)); objectMapper.registerModule(new AfterburnerModule()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/common/src/main/java/com/netflix/conductor/common/jackson/JsonProtoModule.java
common/src/main/java/com/netflix/conductor/common/jackson/JsonProtoModule.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.common.jackson; import java.io.IOException; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.Message; /** * JsonProtoModule can be registered into an {@link ObjectMapper} to enable the serialization and * deserialization of ProtoBuf objects from/to JSON. * * <p>Right now this module only provides (de)serialization for the {@link Any} ProtoBuf type, as * this is the only ProtoBuf object which we're currently exposing through the REST API. * * <p>Annotated as {@link Component} so Spring can register it with {@link ObjectMapper} * * @see AnySerializer * @see AnyDeserializer * @see org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration */ @Component(JsonProtoModule.NAME) public class JsonProtoModule extends SimpleModule { public static final String NAME = "ConductorJsonProtoModule"; private static final String JSON_TYPE = "@type"; private static final String JSON_VALUE = "@value"; /** * AnySerializer converts a ProtoBuf {@link Any} object into its JSON representation. * * <p>This is <b>not</b> a canonical ProtoBuf JSON representation. Let us explain what we're * trying to accomplish here: * * <p>The {@link Any} ProtoBuf message is a type in the PB standard library that can store any * other arbitrary ProtoBuf message in a type-safe way, even when the server has no knowledge of * the schema of the stored message. * * <p>It accomplishes this by storing a tuple of information: an URL-like type declaration for * the stored message, and the serialized binary encoding of the stored message itself. Language * specific implementations of ProtoBuf provide helper methods to encode and decode arbitrary * messages into an {@link Any} object ({@link Any#pack(Message)} in Java). * * <p>We want to expose these {@link Any} objects in the REST API because they've been * introduced as part of the new GRPC interface to Conductor, but unfortunately we cannot encode * them using their canonical ProtoBuf JSON encoding. According to the docs: * * <p>The JSON representation of an `Any` value uses the regular representation of the * deserialized, embedded message, with an additional field `@type` which contains the type URL. * Example: * * <p>package google.profile; message Person { string first_name = 1; string last_name = 2; } { * "@type": "type.googleapis.com/google.profile.Person", "firstName": <string>, "lastName": * <string> } * * <p>In order to accomplish this representation, the PB-JSON encoder needs to have knowledge of * all the ProtoBuf messages that could be serialized inside the {@link Any} message. This is * not possible to accomplish inside the Conductor server, which is simply passing through * arbitrary payloads from/to clients. * * <p>Consequently, to actually expose the Message through the REST API, we must create a custom * encoding that contains the raw data of the serialized message, as we are not able to * deserialize it on the server. We simply return a dictionary with '@type' and '@value' keys, * where '@type' is identical to the canonical representation, but '@value' contains a base64 * encoded string with the binary data of the serialized message. * * <p>Since all the provided Conductor clients are required to know this encoding, it's always * possible to re-build the original {@link Any} message regardless of the client's language. * * <p>{@see AnyDeserializer} */ @SuppressWarnings("InnerClassMayBeStatic") protected class AnySerializer extends JsonSerializer<Any> { @Override public void serialize(Any value, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeStringField(JSON_TYPE, value.getTypeUrl()); jgen.writeBinaryField(JSON_VALUE, value.getValue().toByteArray()); jgen.writeEndObject(); } } /** * AnyDeserializer converts the custom JSON representation of an {@link Any} value into its * original form. * * <p>{@see AnySerializer} for details on this representation. */ @SuppressWarnings("InnerClassMayBeStatic") protected class AnyDeserializer extends JsonDeserializer<Any> { @Override public Any deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonNode root = p.getCodec().readTree(p); JsonNode type = root.get(JSON_TYPE); JsonNode value = root.get(JSON_VALUE); if (type == null || !type.isTextual()) { ctxt.reportBadDefinition( type.getClass(), "invalid '@type' field when deserializing ProtoBuf Any object"); } if (value == null || !value.isTextual()) { ctxt.reportBadDefinition( type.getClass(), "invalid '@value' field when deserializing ProtoBuf Any object"); } return Any.newBuilder() .setTypeUrl(type.textValue()) .setValue(ByteString.copyFrom(value.binaryValue())) .build(); } } public JsonProtoModule() { super(NAME); addSerializer(Any.class, new AnySerializer()); addDeserializer(Any.class, new AnyDeserializer()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/test/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGenTest.java
annotations-processor/src/test/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGenTest.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.io.File; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.common.io.Resources; import static org.junit.Assert.*; public class ProtoGenTest { private static final Charset charset = StandardCharsets.UTF_8; @Rule public TemporaryFolder folder = new TemporaryFolder(); @Test public void happyPath() throws Exception { File rootDir = folder.getRoot(); String protoPackage = "protoPackage"; String javaPackage = "abc.protogen.example"; String goPackage = "goPackage"; String sourcePackage = "com.example"; String mapperPackage = "mapperPackage"; File jarFile = new File("./build/libs/example.jar"); assertTrue(jarFile.exists()); File mapperDir = new File(rootDir, "mapperDir"); mapperDir.mkdirs(); File protosDir = new File(rootDir, "protosDir"); protosDir.mkdirs(); File modelDir = new File(protosDir, "model"); modelDir.mkdirs(); ProtoGen generator = new ProtoGen(protoPackage, javaPackage, goPackage); generator.processPackage(jarFile, sourcePackage); generator.writeMapper(mapperDir, mapperPackage); generator.writeProtos(protosDir); List<File> models = Lists.newArrayList(modelDir.listFiles()); assertEquals(1, models.size()); File exampleProtoFile = models.stream().filter(f -> f.getName().equals("example.proto")).findFirst().get(); assertTrue(exampleProtoFile.length() > 0); assertEquals( Resources.asCharSource(Resources.getResource("example.proto.txt"), charset).read(), Files.asCharSource(exampleProtoFile, charset).read()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoFile.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoFile.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.util.HashSet; import java.util.Set; import com.netflix.conductor.annotationsprocessor.protogen.types.TypeMapper; import com.squareup.javapoet.ClassName; public class ProtoFile { public static String PROTO_SUFFIX = "Pb"; private ClassName baseClass; private AbstractMessage message; private String filePath; private String protoPackageName; private String javaPackageName; private String goPackageName; public ProtoFile( Class<?> object, String protoPackageName, String javaPackageName, String goPackageName) { this.protoPackageName = protoPackageName; this.javaPackageName = javaPackageName; this.goPackageName = goPackageName; String className = object.getSimpleName() + PROTO_SUFFIX; this.filePath = "model/" + object.getSimpleName().toLowerCase() + ".proto"; this.baseClass = ClassName.get(this.javaPackageName, className); this.message = new Message(object, TypeMapper.INSTANCE.baseClass(baseClass, filePath)); } public String getJavaClassName() { return baseClass.simpleName(); } public String getFilePath() { return filePath; } public String getProtoPackageName() { return protoPackageName; } public String getJavaPackageName() { return javaPackageName; } public String getGoPackageName() { return goPackageName; } public AbstractMessage getMessage() { return message; } public Set<String> getIncludes() { Set<String> includes = new HashSet<>(); message.findDependencies(includes); includes.remove(this.getFilePath()); return includes; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/Enum.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/Enum.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import javax.lang.model.element.Modifier; import com.netflix.conductor.annotationsprocessor.protogen.types.MessageType; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; public class Enum extends AbstractMessage { public enum MapType { FROM_PROTO("fromProto"), TO_PROTO("toProto"); private final String methodName; MapType(String m) { methodName = m; } public String getMethodName() { return methodName; } } public Enum(Class cls, MessageType parent) { super(cls, parent); int protoIndex = 0; for (java.lang.reflect.Field field : cls.getDeclaredFields()) { if (field.isEnumConstant()) fields.add(new EnumField(protoIndex++, field)); } } @Override public String getProtoClass() { return "enum"; } private MethodSpec javaMap(MapType mt, TypeName from, TypeName to) { MethodSpec.Builder method = MethodSpec.methodBuilder(mt.getMethodName()); method.addModifiers(Modifier.PUBLIC); method.returns(to); method.addParameter(from, "from"); method.addStatement("$T to", to); method.beginControlFlow("switch (from)"); for (Field field : fields) { String fromName = (mt == MapType.TO_PROTO) ? field.getName() : field.getProtoName(); String toName = (mt == MapType.TO_PROTO) ? field.getProtoName() : field.getName(); method.addStatement("case $L: to = $T.$L; break", fromName, to, toName); } method.addStatement( "default: throw new $T(\"Unexpected enum constant: \" + from)", IllegalArgumentException.class); method.endControlFlow(); method.addStatement("return to"); return method.build(); } @Override protected void javaMapFromProto(TypeSpec.Builder type) { type.addMethod( javaMap( MapType.FROM_PROTO, this.type.getJavaProtoType(), TypeName.get(this.clazz))); } @Override protected void javaMapToProto(TypeSpec.Builder type) { type.addMethod( javaMap(MapType.TO_PROTO, TypeName.get(this.clazz), this.type.getJavaProtoType())); } public class EnumField extends Field { protected EnumField(int index, java.lang.reflect.Field field) { super(index, field); } @Override public String getProtoTypeDeclaration() { return String.format("%s = %d", getProtoName(), getProtoIndex()); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/AbstractMessage.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/AbstractMessage.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.netflix.conductor.annotations.protogen.ProtoEnum; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.annotationsprocessor.protogen.types.MessageType; import com.netflix.conductor.annotationsprocessor.protogen.types.TypeMapper; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; public abstract class AbstractMessage { protected Class<?> clazz; protected MessageType type; protected List<Field> fields = new ArrayList<Field>(); protected List<AbstractMessage> nested = new ArrayList<>(); public AbstractMessage(Class<?> cls, MessageType parentType) { assert cls.isAnnotationPresent(ProtoMessage.class) || cls.isAnnotationPresent(ProtoEnum.class); this.clazz = cls; this.type = TypeMapper.INSTANCE.declare(cls, parentType); for (Class<?> nested : clazz.getDeclaredClasses()) { if (nested.isEnum()) addNestedEnum(nested); else addNestedClass(nested); } } private void addNestedEnum(Class<?> cls) { ProtoEnum ann = (ProtoEnum) cls.getAnnotation(ProtoEnum.class); if (ann != null) { nested.add(new Enum(cls, this.type)); } } private void addNestedClass(Class<?> cls) { ProtoMessage ann = (ProtoMessage) cls.getAnnotation(ProtoMessage.class); if (ann != null) { nested.add(new Message(cls, this.type)); } } public abstract String getProtoClass(); protected abstract void javaMapToProto(TypeSpec.Builder builder); protected abstract void javaMapFromProto(TypeSpec.Builder builder); public void generateJavaMapper(TypeSpec.Builder builder) { javaMapToProto(builder); javaMapFromProto(builder); for (AbstractMessage abstractMessage : this.nested) { abstractMessage.generateJavaMapper(builder); } } public void generateAbstractMethods(Set<MethodSpec> specs) { for (Field field : fields) { field.generateAbstractMethods(specs); } for (AbstractMessage elem : nested) { elem.generateAbstractMethods(specs); } } public void findDependencies(Set<String> dependencies) { for (Field field : fields) { field.getDependencies(dependencies); } for (AbstractMessage elem : nested) { elem.findDependencies(dependencies); } } public List<AbstractMessage> getNested() { return nested; } public List<Field> getFields() { return fields; } public String getName() { return clazz.getSimpleName(); } public abstract static class Field { protected int protoIndex; protected java.lang.reflect.Field field; protected Field(int index, java.lang.reflect.Field field) { this.protoIndex = index; this.field = field; } public abstract String getProtoTypeDeclaration(); public int getProtoIndex() { return protoIndex; } public String getName() { return field.getName(); } public String getProtoName() { return field.getName().toUpperCase(); } public void getDependencies(Set<String> deps) {} public void generateAbstractMethods(Set<MethodSpec> specs) {} } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGen.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGen.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import javax.lang.model.element.Modifier; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.github.jknack.handlebars.EscapingStrategy; import com.github.jknack.handlebars.Handlebars; import com.github.jknack.handlebars.Template; import com.github.jknack.handlebars.io.ClassPathTemplateLoader; import com.github.jknack.handlebars.io.TemplateLoader; import com.google.common.reflect.ClassPath; import com.squareup.javapoet.AnnotationSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import jakarta.annotation.Generated; public class ProtoGen { private static final String GENERATOR_NAME = "com.netflix.conductor.annotationsprocessor.protogen"; private String protoPackageName; private String javaPackageName; private String goPackageName; private List<ProtoFile> protoFiles = new ArrayList<>(); public ProtoGen(String protoPackageName, String javaPackageName, String goPackageName) { this.protoPackageName = protoPackageName; this.javaPackageName = javaPackageName; this.goPackageName = goPackageName; } public void writeMapper(File root, String mapperPackageName) throws IOException { TypeSpec.Builder protoMapper = TypeSpec.classBuilder("AbstractProtoMapper") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .addAnnotation( AnnotationSpec.builder(Generated.class) .addMember("value", "$S", GENERATOR_NAME) .build()); Set<MethodSpec> abstractMethods = new HashSet<>(); protoFiles.sort( new Comparator<ProtoFile>() { public int compare(ProtoFile p1, ProtoFile p2) { String n1 = p1.getMessage().getName(); String n2 = p2.getMessage().getName(); return n1.compareTo(n2); } }); for (ProtoFile protoFile : protoFiles) { AbstractMessage elem = protoFile.getMessage(); elem.generateJavaMapper(protoMapper); elem.generateAbstractMethods(abstractMethods); } protoMapper.addMethods(abstractMethods); JavaFile javaFile = JavaFile.builder(mapperPackageName, protoMapper.build()).indent(" ").build(); File filename = new File(root, "AbstractProtoMapper.java"); try (Writer writer = new FileWriter(filename.toString())) { System.out.printf("protogen: writing '%s'...\n", filename); javaFile.writeTo(writer); } } public void writeProtos(File root) throws IOException { TemplateLoader loader = new ClassPathTemplateLoader("/templates", ".proto"); Handlebars handlebars = new Handlebars(loader) .infiniteLoops(true) .prettyPrint(true) .with(EscapingStrategy.NOOP); Template protoFile = handlebars.compile("file"); for (ProtoFile file : protoFiles) { File filename = new File(root, file.getFilePath()); try (Writer writer = new FileWriter(filename)) { System.out.printf("protogen: writing '%s'...\n", filename); protoFile.apply(file, writer); } } } public void processPackage(File jarFile, String packageName) throws IOException { if (!jarFile.isFile()) throw new IOException("missing Jar file " + jarFile); URL[] urls = new URL[] {jarFile.toURI().toURL()}; ClassLoader loader = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); ClassPath cp = ClassPath.from(loader); System.out.printf("protogen: processing Jar '%s'\n", jarFile); for (ClassPath.ClassInfo info : cp.getTopLevelClassesRecursive(packageName)) { try { processClass(info.load()); } catch (NoClassDefFoundError ignored) { } } } public void processClass(Class<?> obj) { if (obj.isAnnotationPresent(ProtoMessage.class)) { System.out.printf("protogen: found %s\n", obj.getCanonicalName()); protoFiles.add(new ProtoFile(obj, protoPackageName, javaPackageName, goPackageName)); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/Message.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/Message.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.lang.model.element.Modifier; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; import com.netflix.conductor.annotationsprocessor.protogen.types.AbstractType; import com.netflix.conductor.annotationsprocessor.protogen.types.MessageType; import com.netflix.conductor.annotationsprocessor.protogen.types.TypeMapper; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; public class Message extends AbstractMessage { public Message(Class<?> cls, MessageType parent) { super(cls, parent); for (java.lang.reflect.Field field : clazz.getDeclaredFields()) { ProtoField ann = field.getAnnotation(ProtoField.class); if (ann == null) continue; fields.add(new MessageField(ann.id(), field)); } } protected ProtoMessage getAnnotation() { return (ProtoMessage) this.clazz.getAnnotation(ProtoMessage.class); } @Override public String getProtoClass() { return "message"; } @Override protected void javaMapToProto(TypeSpec.Builder type) { if (!getAnnotation().toProto() || getAnnotation().wrapper()) return; ClassName javaProtoType = (ClassName) this.type.getJavaProtoType(); MethodSpec.Builder method = MethodSpec.methodBuilder("toProto"); method.addModifiers(Modifier.PUBLIC); method.returns(javaProtoType); method.addParameter(this.clazz, "from"); method.addStatement( "$T to = $T.newBuilder()", javaProtoType.nestedClass("Builder"), javaProtoType); for (Field field : this.fields) { if (field instanceof MessageField) { AbstractType fieldType = ((MessageField) field).getAbstractType(); fieldType.mapToProto(field.getName(), method); } } method.addStatement("return to.build()"); type.addMethod(method.build()); } @Override protected void javaMapFromProto(TypeSpec.Builder type) { if (!getAnnotation().fromProto() || getAnnotation().wrapper()) return; MethodSpec.Builder method = MethodSpec.methodBuilder("fromProto"); method.addModifiers(Modifier.PUBLIC); method.returns(this.clazz); method.addParameter(this.type.getJavaProtoType(), "from"); method.addStatement("$T to = new $T()", this.clazz, this.clazz); for (Field field : this.fields) { if (field instanceof MessageField) { AbstractType fieldType = ((MessageField) field).getAbstractType(); fieldType.mapFromProto(field.getName(), method); } } method.addStatement("return to"); type.addMethod(method.build()); } public static class MessageField extends Field { protected AbstractType type; protected MessageField(int index, java.lang.reflect.Field field) { super(index, field); } public AbstractType getAbstractType() { if (type == null) { type = TypeMapper.INSTANCE.get(field.getGenericType()); } return type; } private static Pattern CAMEL_CASE_RE = Pattern.compile("(?<=[a-z])[A-Z]"); private static String toUnderscoreCase(String input) { Matcher m = CAMEL_CASE_RE.matcher(input); StringBuilder sb = new StringBuilder(); while (m.find()) { m.appendReplacement(sb, "_" + m.group()); } m.appendTail(sb); return sb.toString().toLowerCase(); } @Override public String getProtoTypeDeclaration() { return String.format( "%s %s = %d", getAbstractType().getProtoType(), toUnderscoreCase(getName()), getProtoIndex()); } @Override public void getDependencies(Set<String> deps) { getAbstractType().getDependencies(deps); } @Override public void generateAbstractMethods(Set<MethodSpec> specs) { getAbstractType().generateAbstractMethods(specs); } } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGenTask.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/ProtoGenTask.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen; import java.io.File; import java.io.IOException; public class ProtoGenTask { private String protoPackage; private String javaPackage; private String goPackage; private File protosDir; private File mapperDir; private String mapperPackage; private File sourceJar; private String sourcePackage; public String getProtoPackage() { return protoPackage; } public void setProtoPackage(String protoPackage) { this.protoPackage = protoPackage; } public String getJavaPackage() { return javaPackage; } public void setJavaPackage(String javaPackage) { this.javaPackage = javaPackage; } public String getGoPackage() { return goPackage; } public void setGoPackage(String goPackage) { this.goPackage = goPackage; } public File getProtosDir() { return protosDir; } public void setProtosDir(File protosDir) { this.protosDir = protosDir; } public File getMapperDir() { return mapperDir; } public void setMapperDir(File mapperDir) { this.mapperDir = mapperDir; } public String getMapperPackage() { return mapperPackage; } public void setMapperPackage(String mapperPackage) { this.mapperPackage = mapperPackage; } public File getSourceJar() { return sourceJar; } public void setSourceJar(File sourceJar) { this.sourceJar = sourceJar; } public String getSourcePackage() { return sourcePackage; } public void setSourcePackage(String sourcePackage) { this.sourcePackage = sourcePackage; } public void generate() { ProtoGen generator = new ProtoGen(protoPackage, javaPackage, goPackage); try { generator.processPackage(sourceJar, sourcePackage); generator.writeMapper(mapperDir, mapperPackage); generator.writeProtos(protosDir); } catch (IOException e) { System.err.printf("protogen: failed with %s\n", e); } } public static void main(String[] args) { if (args == null || args.length < 8) { throw new RuntimeException( "protogen configuration incomplete, please provide all required (8) inputs"); } ProtoGenTask task = new ProtoGenTask(); int argsId = 0; task.setProtoPackage(args[argsId++]); task.setJavaPackage(args[argsId++]); task.setGoPackage(args[argsId++]); task.setProtosDir(new File(args[argsId++])); task.setMapperDir(new File(args[argsId++])); task.setMapperPackage(args[argsId++]); task.setSourceJar(new File(args[argsId++])); task.setSourcePackage(args[argsId]); System.out.println("Running protogen with arguments: " + task); task.generate(); System.out.println("protogen completed."); } @Override public String toString() { return "ProtoGenTask{" + "protoPackage='" + protoPackage + '\'' + ", javaPackage='" + javaPackage + '\'' + ", goPackage='" + goPackage + '\'' + ", protosDir=" + protosDir + ", mapperDir=" + mapperDir + ", mapperPackage='" + mapperPackage + '\'' + ", sourceJar=" + sourceJar + ", sourcePackage='" + sourcePackage + '\'' + '}'; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ListType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ListType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.stream.Collectors; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; public class ListType extends GenericType { private AbstractType valueType; public ListType(Type type) { super(type); } @Override public String getWrapperSuffix() { return "List"; } @Override public AbstractType getValueType() { if (valueType == null) { valueType = resolveGenericParam(0); } return valueType; } @Override public void mapToProto(String field, MethodSpec.Builder method) { AbstractType subtype = getValueType(); if (subtype instanceof ScalarType) { method.addStatement( "to.$L( from.$L() )", protoMethodName("addAll", field), javaMethodName("get", field)); } else { method.beginControlFlow( "for ($T elem : from.$L())", subtype.getJavaType(), javaMethodName("get", field)); method.addStatement("to.$L( toProto(elem) )", protoMethodName("add", field)); method.endControlFlow(); } } @Override public void mapFromProto(String field, MethodSpec.Builder method) { AbstractType subtype = getValueType(); Type entryType = subtype.getJavaType(); Class collector = TypeMapper.PROTO_LIST_TYPES.get(getRawType()); if (subtype instanceof ScalarType) { if (entryType.equals(String.class)) { method.addStatement( "to.$L( from.$L().stream().collect($T.toCollection($T::new)) )", javaMethodName("set", field), protoMethodName("get", field) + "List", Collectors.class, collector); } else { method.addStatement( "to.$L( from.$L() )", javaMethodName("set", field), protoMethodName("get", field) + "List"); } } else { method.addStatement( "to.$L( from.$L().stream().map(this::fromProto).collect($T.toCollection($T::new)) )", javaMethodName("set", field), protoMethodName("get", field) + "List", Collectors.class, collector); } } @Override public TypeName resolveJavaProtoType() { return ParameterizedTypeName.get( (ClassName) getRawJavaType(), getValueType().getJavaProtoType()); } @Override public String getProtoType() { return "repeated " + getValueType().getProtoType(); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/TypeMapper.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/TypeMapper.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; import com.google.protobuf.Any; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.TypeName; public class TypeMapper { static Map<Type, Class> PROTO_LIST_TYPES = new HashMap<>(); static { PROTO_LIST_TYPES.put(List.class, ArrayList.class); PROTO_LIST_TYPES.put(Set.class, HashSet.class); PROTO_LIST_TYPES.put(LinkedList.class, LinkedList.class); } public static TypeMapper INSTANCE = new TypeMapper(); private Map<Type, AbstractType> types = new HashMap<>(); public void addScalarType(Type t, String protoType) { types.put(t, new ScalarType(t, TypeName.get(t), protoType)); } public void addMessageType(Class<?> t, MessageType message) { types.put(t, message); } public TypeMapper() { addScalarType(int.class, "int32"); addScalarType(Integer.class, "int32"); addScalarType(long.class, "int64"); addScalarType(Long.class, "int64"); addScalarType(String.class, "string"); addScalarType(boolean.class, "bool"); addScalarType(Boolean.class, "bool"); addMessageType( Object.class, new ExternMessageType( Object.class, ClassName.get("com.google.protobuf", "Value"), "google.protobuf.Value", "google/protobuf/struct.proto")); addMessageType( Any.class, new ExternMessageType( Any.class, ClassName.get(Any.class), "google.protobuf.Any", "google/protobuf/any.proto")); } public AbstractType get(Type t) { if (!types.containsKey(t)) { if (t instanceof ParameterizedType) { Type raw = ((ParameterizedType) t).getRawType(); if (PROTO_LIST_TYPES.containsKey(raw)) { types.put(t, new ListType(t)); } else if (raw.equals(Map.class)) { types.put(t, new MapType(t)); } } } if (!types.containsKey(t)) { throw new IllegalArgumentException("Cannot map type: " + t); } return types.get(t); } public MessageType get(String className) { for (Map.Entry<Type, AbstractType> pair : types.entrySet()) { AbstractType t = pair.getValue(); if (t instanceof MessageType) { if (((Class) t.getJavaType()).getSimpleName().equals(className)) return (MessageType) t; } } return null; } public MessageType declare(Class type, MessageType parent) { return declare(type, (ClassName) parent.getJavaProtoType(), parent.getProtoFilePath()); } public MessageType declare(Class type, ClassName parentType, String protoFilePath) { String simpleName = type.getSimpleName(); MessageType t = new MessageType(type, parentType.nestedClass(simpleName), protoFilePath); if (types.containsKey(type)) { throw new IllegalArgumentException("duplicate type declaration: " + type); } types.put(type, t); return t; } public MessageType baseClass(ClassName className, String protoFilePath) { return new MessageType(Object.class, className, protoFilePath); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/MessageType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/MessageType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.List; import java.util.Set; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public class MessageType extends AbstractType { private String protoFilePath; public MessageType(Type javaType, ClassName javaProtoType, String protoFilePath) { super(javaType, javaProtoType); this.protoFilePath = protoFilePath; } @Override public String getProtoType() { List<String> classes = ((ClassName) getJavaProtoType()).simpleNames(); return String.join(".", classes.subList(1, classes.size())); } public String getProtoFilePath() { return protoFilePath; } @Override public TypeName getRawJavaType() { return getJavaProtoType(); } @Override public void mapToProto(String field, MethodSpec.Builder method) { final String getter = javaMethodName("get", field); method.beginControlFlow("if (from.$L() != null)", getter); method.addStatement("to.$L( toProto( from.$L() ) )", protoMethodName("set", field), getter); method.endControlFlow(); } private boolean isEnum() { Type clazz = getJavaType(); return (clazz instanceof Class<?>) && ((Class) clazz).isEnum(); } @Override public void mapFromProto(String field, MethodSpec.Builder method) { if (!isEnum()) method.beginControlFlow("if (from.$L())", protoMethodName("has", field)); method.addStatement( "to.$L( fromProto( from.$L() ) )", javaMethodName("set", field), protoMethodName("get", field)); if (!isEnum()) method.endControlFlow(); } @Override public void getDependencies(Set<String> deps) { deps.add(protoFilePath); } @Override public void generateAbstractMethods(Set<MethodSpec> specs) {} }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/AbstractType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/AbstractType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.Set; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public abstract class AbstractType { Type javaType; TypeName javaProtoType; AbstractType(Type javaType, TypeName javaProtoType) { this.javaType = javaType; this.javaProtoType = javaProtoType; } public Type getJavaType() { return javaType; } public TypeName getJavaProtoType() { return javaProtoType; } public abstract String getProtoType(); public abstract TypeName getRawJavaType(); public abstract void mapToProto(String field, MethodSpec.Builder method); public abstract void mapFromProto(String field, MethodSpec.Builder method); public abstract void getDependencies(Set<String> deps); public abstract void generateAbstractMethods(Set<MethodSpec> specs); protected String javaMethodName(String m, String field) { String fieldName = field.substring(0, 1).toUpperCase() + field.substring(1); return m + fieldName; } private static class ProtoCase { static String convert(String s) { StringBuilder out = new StringBuilder(s.length()); final int len = s.length(); int i = 0; int j = -1; while ((j = findWordBoundary(s, ++j)) != -1) { out.append(normalizeWord(s.substring(i, j))); if (j < len && s.charAt(j) == '_') j++; i = j; } if (i == 0) return normalizeWord(s); if (i < len) out.append(normalizeWord(s.substring(i))); return out.toString(); } private static boolean isWordBoundary(char c) { return (c >= 'A' && c <= 'Z'); } private static int findWordBoundary(CharSequence sequence, int start) { int length = sequence.length(); if (start >= length) return -1; if (isWordBoundary(sequence.charAt(start))) { int i = start; while (i < length && isWordBoundary(sequence.charAt(i))) i++; return i; } else { for (int i = start; i < length; i++) { final char c = sequence.charAt(i); if (c == '_' || isWordBoundary(c)) return i; } return -1; } } private static String normalizeWord(String word) { if (word.length() < 2) return word.toUpperCase(); return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); } } protected String protoMethodName(String m, String field) { return m + ProtoCase.convert(field); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/MapType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/MapType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; import com.squareup.javapoet.TypeName; public class MapType extends GenericType { private AbstractType keyType; private AbstractType valueType; public MapType(Type type) { super(type); } @Override public String getWrapperSuffix() { return "Map"; } @Override public AbstractType getValueType() { if (valueType == null) { valueType = resolveGenericParam(1); } return valueType; } public AbstractType getKeyType() { if (keyType == null) { keyType = resolveGenericParam(0); } return keyType; } @Override public void mapToProto(String field, MethodSpec.Builder method) { AbstractType valueType = getValueType(); if (valueType instanceof ScalarType) { method.addStatement( "to.$L( from.$L() )", protoMethodName("putAll", field), javaMethodName("get", field)); } else { TypeName typeName = ParameterizedTypeName.get( Map.Entry.class, getKeyType().getJavaType(), getValueType().getJavaType()); method.beginControlFlow( "for ($T pair : from.$L().entrySet())", typeName, javaMethodName("get", field)); method.addStatement( "to.$L( pair.getKey(), toProto( pair.getValue() ) )", protoMethodName("put", field)); method.endControlFlow(); } } @Override public void mapFromProto(String field, MethodSpec.Builder method) { AbstractType valueType = getValueType(); if (valueType instanceof ScalarType) { method.addStatement( "to.$L( from.$L() )", javaMethodName("set", field), protoMethodName("get", field) + "Map"); } else { Type keyType = getKeyType().getJavaType(); Type valueTypeJava = getValueType().getJavaType(); TypeName valueTypePb = getValueType().getJavaProtoType(); ParameterizedTypeName entryType = ParameterizedTypeName.get( ClassName.get(Map.Entry.class), TypeName.get(keyType), valueTypePb); ParameterizedTypeName mapType = ParameterizedTypeName.get(Map.class, keyType, valueTypeJava); ParameterizedTypeName hashMapType = ParameterizedTypeName.get(HashMap.class, keyType, valueTypeJava); String mapName = field + "Map"; method.addStatement("$T $L = new $T()", mapType, mapName, hashMapType); method.beginControlFlow( "for ($T pair : from.$L().entrySet())", entryType, protoMethodName("get", field) + "Map"); method.addStatement("$L.put( pair.getKey(), fromProto( pair.getValue() ) )", mapName); method.endControlFlow(); method.addStatement("to.$L($L)", javaMethodName("set", field), mapName); } } @Override public TypeName resolveJavaProtoType() { return ParameterizedTypeName.get( (ClassName) getRawJavaType(), getKeyType().getJavaProtoType(), getValueType().getJavaProtoType()); } @Override public String getProtoType() { AbstractType keyType = getKeyType(); AbstractType valueType = getValueType(); if (!(keyType instanceof ScalarType)) { throw new IllegalArgumentException( "cannot map non-scalar map key: " + this.getJavaType()); } return String.format("map<%s, %s>", keyType.getProtoType(), valueType.getProtoType()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/GenericType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/GenericType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Set; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; abstract class GenericType extends AbstractType { public GenericType(Type type) { super(type, null); } protected Class getRawType() { ParameterizedType tt = (ParameterizedType) this.getJavaType(); return (Class) tt.getRawType(); } protected AbstractType resolveGenericParam(int idx) { ParameterizedType tt = (ParameterizedType) this.getJavaType(); Type[] types = tt.getActualTypeArguments(); AbstractType abstractType = TypeMapper.INSTANCE.get(types[idx]); if (abstractType instanceof GenericType) { return WrappedType.wrap((GenericType) abstractType); } return abstractType; } public abstract String getWrapperSuffix(); public abstract AbstractType getValueType(); public abstract TypeName resolveJavaProtoType(); @Override public TypeName getRawJavaType() { return ClassName.get(getRawType()); } @Override public void getDependencies(Set<String> deps) { getValueType().getDependencies(deps); } @Override public void generateAbstractMethods(Set<MethodSpec> specs) { getValueType().generateAbstractMethods(specs); } @Override public TypeName getJavaProtoType() { if (javaProtoType == null) { javaProtoType = resolveJavaProtoType(); } return javaProtoType; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ExternMessageType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ExternMessageType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.Set; import javax.lang.model.element.Modifier; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.MethodSpec; public class ExternMessageType extends MessageType { private String externProtoType; public ExternMessageType( Type javaType, ClassName javaProtoType, String externProtoType, String protoFilePath) { super(javaType, javaProtoType, protoFilePath); this.externProtoType = externProtoType; } @Override public String getProtoType() { return externProtoType; } @Override public void generateAbstractMethods(Set<MethodSpec> specs) { MethodSpec fromProto = MethodSpec.methodBuilder("fromProto") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(this.getJavaType()) .addParameter(this.getJavaProtoType(), "in") .build(); MethodSpec toProto = MethodSpec.methodBuilder("toProto") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(this.getJavaProtoType()) .addParameter(this.getJavaType(), "in") .build(); specs.add(fromProto); specs.add(toProto); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ScalarType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/ScalarType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.Set; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public class ScalarType extends AbstractType { private String protoType; public ScalarType(Type javaType, TypeName javaProtoType, String protoType) { super(javaType, javaProtoType); this.protoType = protoType; } @Override public String getProtoType() { return protoType; } @Override public TypeName getRawJavaType() { return getJavaProtoType(); } @Override public void mapFromProto(String field, MethodSpec.Builder method) { method.addStatement( "to.$L( from.$L() )", javaMethodName("set", field), protoMethodName("get", field)); } private boolean isNullableType() { final Type jt = getJavaType(); return jt.equals(Boolean.class) || jt.equals(Byte.class) || jt.equals(Character.class) || jt.equals(Short.class) || jt.equals(Integer.class) || jt.equals(Long.class) || jt.equals(Double.class) || jt.equals(Float.class) || jt.equals(String.class); } @Override public void mapToProto(String field, MethodSpec.Builder method) { final boolean nullable = isNullableType(); String getter = (getJavaType().equals(boolean.class) || getJavaType().equals(Boolean.class)) ? javaMethodName("is", field) : javaMethodName("get", field); if (nullable) method.beginControlFlow("if (from.$L() != null)", getter); method.addStatement("to.$L( from.$L() )", protoMethodName("set", field), getter); if (nullable) method.endControlFlow(); } @Override public void getDependencies(Set<String> deps) {} @Override public void generateAbstractMethods(Set<MethodSpec> specs) {} }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/WrappedType.java
annotations-processor/src/main/java/com/netflix/conductor/annotationsprocessor/protogen/types/WrappedType.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.annotationsprocessor.protogen.types; import java.lang.reflect.Type; import java.util.Set; import javax.lang.model.element.Modifier; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeName; public class WrappedType extends AbstractType { private AbstractType realType; private MessageType wrappedType; public static WrappedType wrap(GenericType realType) { Type valueType = realType.getValueType().getJavaType(); if (!(valueType instanceof Class)) throw new IllegalArgumentException("cannot wrap primitive type: " + valueType); String className = ((Class) valueType).getSimpleName() + realType.getWrapperSuffix(); MessageType wrappedType = TypeMapper.INSTANCE.get(className); if (wrappedType == null) throw new IllegalArgumentException("missing wrapper class: " + className); return new WrappedType(realType, wrappedType); } public WrappedType(AbstractType realType, MessageType wrappedType) { super(realType.getJavaType(), wrappedType.getJavaProtoType()); this.realType = realType; this.wrappedType = wrappedType; } @Override public String getProtoType() { return wrappedType.getProtoType(); } @Override public TypeName getRawJavaType() { return realType.getRawJavaType(); } @Override public void mapToProto(String field, MethodSpec.Builder method) { wrappedType.mapToProto(field, method); } @Override public void mapFromProto(String field, MethodSpec.Builder method) { wrappedType.mapFromProto(field, method); } @Override public void getDependencies(Set<String> deps) { this.realType.getDependencies(deps); this.wrappedType.getDependencies(deps); } @Override public void generateAbstractMethods(Set<MethodSpec> specs) { MethodSpec fromProto = MethodSpec.methodBuilder("fromProto") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(this.realType.getJavaType()) .addParameter(this.wrappedType.getJavaProtoType(), "in") .build(); MethodSpec toProto = MethodSpec.methodBuilder("toProto") .addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT) .returns(this.wrappedType.getJavaProtoType()) .addParameter(this.realType.getJavaType(), "in") .build(); specs.add(fromProto); specs.add(toProto); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/annotations-processor/src/example/java/com/example/Example.java
annotations-processor/src/example/java/com/example/Example.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.example; import com.netflix.conductor.annotations.protogen.ProtoField; import com.netflix.conductor.annotations.protogen.ProtoMessage; @ProtoMessage public class Example { @ProtoField(id = 1) public String name; @ProtoField(id = 2) public Long count; }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/BaseDynoDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/BaseDynoDAOTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class BaseDynoDAOTest { @Mock private JedisProxy jedisProxy; @Mock private ObjectMapper objectMapper; private RedisProperties properties; private ConductorProperties conductorProperties; private BaseDynoDAO baseDynoDAO; @Before public void setUp() { properties = mock(RedisProperties.class); conductorProperties = mock(ConductorProperties.class); this.baseDynoDAO = new BaseDynoDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Test public void testNsKey() { assertEquals("", baseDynoDAO.nsKey()); String[] keys = {"key1", "key2"}; assertEquals("key1.key2", baseDynoDAO.nsKey(keys)); when(properties.getWorkflowNamespacePrefix()).thenReturn("test"); assertEquals("test", baseDynoDAO.nsKey()); assertEquals("test.key1.key2", baseDynoDAO.nsKey(keys)); when(conductorProperties.getStack()).thenReturn("stack"); assertEquals("test.stack.key1.key2", baseDynoDAO.nsKey(keys)); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisRateLimitDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisRateLimitDAOTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.commands.JedisCommands; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class RedisRateLimitDAOTest { private RedisRateLimitingDAO rateLimitingDao; @Autowired private ObjectMapper objectMapper; @Before public void init() { ConductorProperties conductorProperties = mock(ConductorProperties.class); RedisProperties properties = mock(RedisProperties.class); JedisCommands jedisMock = new JedisMock(); JedisProxy jedisProxy = new JedisProxy(jedisMock); rateLimitingDao = new RedisRateLimitingDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Test public void testExceedsRateLimitWhenNoRateLimitSet() { TaskDef taskDef = new TaskDef("TestTaskDefinition"); TaskModel task = new TaskModel(); task.setTaskId(UUID.randomUUID().toString()); task.setTaskDefName(taskDef.getName()); assertFalse(rateLimitingDao.exceedsRateLimitPerFrequency(task, taskDef)); } @Test public void testExceedsRateLimitWithinLimit() { TaskDef taskDef = new TaskDef("TestTaskDefinition"); taskDef.setRateLimitFrequencyInSeconds(60); taskDef.setRateLimitPerFrequency(20); TaskModel task = new TaskModel(); task.setTaskId(UUID.randomUUID().toString()); task.setTaskDefName(taskDef.getName()); assertFalse(rateLimitingDao.exceedsRateLimitPerFrequency(task, taskDef)); } @Test public void testExceedsRateLimitOutOfLimit() { TaskDef taskDef = new TaskDef("TestTaskDefinition"); taskDef.setRateLimitFrequencyInSeconds(60); taskDef.setRateLimitPerFrequency(1); TaskModel task = new TaskModel(); task.setTaskId(UUID.randomUUID().toString()); task.setTaskDefName(taskDef.getName()); assertFalse(rateLimitingDao.exceedsRateLimitPerFrequency(task, taskDef)); assertTrue(rateLimitingDao.exceedsRateLimitPerFrequency(task, taskDef)); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisExecutionDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisExecutionDAOTest.java
/* * Copyright 2022 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import java.time.Duration; import java.util.Collections; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.dao.ExecutionDAO; import com.netflix.conductor.dao.ExecutionDAOTest; import com.netflix.conductor.model.TaskModel; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.commands.JedisCommands; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class RedisExecutionDAOTest extends ExecutionDAOTest { private RedisExecutionDAO executionDAO; @Autowired private ObjectMapper objectMapper; @Before public void init() { ConductorProperties conductorProperties = mock(ConductorProperties.class); RedisProperties properties = mock(RedisProperties.class); when(properties.getEventExecutionPersistenceTTL()).thenReturn(Duration.ofSeconds(5)); JedisCommands jedisMock = new JedisMock(); JedisProxy jedisProxy = new JedisProxy(jedisMock); executionDAO = new RedisExecutionDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Test public void testCorrelateTaskToWorkflowInDS() { String workflowId = "workflowId"; String taskId = "taskId1"; String taskDefName = "task1"; TaskDef def = new TaskDef(); def.setName("task1"); def.setConcurrentExecLimit(1); TaskModel task = new TaskModel(); task.setTaskId(taskId); task.setWorkflowInstanceId(workflowId); task.setReferenceTaskName("ref_name"); task.setTaskDefName(taskDefName); task.setTaskType(taskDefName); task.setStatus(TaskModel.Status.IN_PROGRESS); List<TaskModel> tasks = executionDAO.createTasks(Collections.singletonList(task)); assertNotNull(tasks); assertEquals(1, tasks.size()); executionDAO.correlateTaskToWorkflowInDS(taskId, workflowId); tasks = executionDAO.getTasksForWorkflow(workflowId); assertNotNull(tasks); assertEquals(workflowId, tasks.get(0).getWorkflowInstanceId()); assertEquals(taskId, tasks.get(0).getTaskId()); } @Override protected ExecutionDAO getExecutionDAO() { return executionDAO; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/DynoQueueDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/DynoQueueDAOTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import com.netflix.conductor.dao.QueueDAO; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.dynoqueue.RedisQueuesShardingStrategyProvider; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.dyno.connectionpool.Host; import com.netflix.dyno.queues.ShardSupplier; import com.netflix.dyno.queues.redis.RedisQueues; import com.netflix.dyno.queues.redis.sharding.ShardingStrategy; import redis.clients.jedis.commands.JedisCommands; import static com.netflix.conductor.redis.dynoqueue.RedisQueuesShardingStrategyProvider.LOCAL_ONLY_STRATEGY; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class DynoQueueDAOTest { private QueueDAO queueDAO; @Before public void init() { RedisProperties properties = mock(RedisProperties.class); when(properties.getQueueShardingStrategy()).thenReturn(LOCAL_ONLY_STRATEGY); JedisCommands jedisMock = new JedisMock(); ShardSupplier shardSupplier = new ShardSupplier() { @Override public Set<String> getQueueShards() { return new HashSet<>(Collections.singletonList("a")); } @Override public String getCurrentShard() { return "a"; } @Override public String getShardForHost(Host host) { return "a"; } }; ShardingStrategy shardingStrategy = new RedisQueuesShardingStrategyProvider(shardSupplier, properties).get(); RedisQueues redisQueues = new RedisQueues( jedisMock, jedisMock, "", shardSupplier, 60_000, 60_000, shardingStrategy); queueDAO = new DynoQueueDAO(redisQueues); } @Rule public ExpectedException expected = ExpectedException.none(); @Test public void test() { String queueName = "TestQueue"; long offsetTimeInSecond = 0; for (int i = 0; i < 10; i++) { String messageId = "msg" + i; queueDAO.push(queueName, messageId, offsetTimeInSecond); } int size = queueDAO.getSize(queueName); assertEquals(10, size); Map<String, Long> details = queueDAO.queuesDetail(); assertEquals(1, details.size()); assertEquals(10L, details.get(queueName).longValue()); for (int i = 0; i < 10; i++) { String messageId = "msg" + i; queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond); } List<String> popped = queueDAO.pop(queueName, 10, 100); assertNotNull(popped); assertEquals(10, popped.size()); Map<String, Map<String, Map<String, Long>>> verbose = queueDAO.queuesDetailVerbose(); assertEquals(1, verbose.size()); long shardSize = verbose.get(queueName).get("a").get("size"); long unackedSize = verbose.get(queueName).get("a").get("uacked"); assertEquals(0, shardSize); assertEquals(10, unackedSize); popped.forEach(messageId -> queueDAO.ack(queueName, messageId)); verbose = queueDAO.queuesDetailVerbose(); assertEquals(1, verbose.size()); shardSize = verbose.get(queueName).get("a").get("size"); unackedSize = verbose.get(queueName).get("a").get("uacked"); assertEquals(0, shardSize); assertEquals(0, unackedSize); popped = queueDAO.pop(queueName, 10, 100); assertNotNull(popped); assertEquals(0, popped.size()); for (int i = 0; i < 10; i++) { String messageId = "msg" + i; queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond); } size = queueDAO.getSize(queueName); assertEquals(10, size); for (int i = 0; i < 10; i++) { String messageId = "msg" + i; queueDAO.remove(queueName, messageId); } size = queueDAO.getSize(queueName); assertEquals(0, size); for (int i = 0; i < 10; i++) { String messageId = "msg" + i; queueDAO.pushIfNotExists(queueName, messageId, offsetTimeInSecond); } queueDAO.flush(queueName); size = queueDAO.getSize(queueName); assertEquals(0, size); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisEventHandlerDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisEventHandlerDAOTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import java.util.List; import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.events.EventHandler; import com.netflix.conductor.common.metadata.events.EventHandler.Action; import com.netflix.conductor.common.metadata.events.EventHandler.Action.Type; import com.netflix.conductor.common.metadata.events.EventHandler.StartWorkflow; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.commands.JedisCommands; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class RedisEventHandlerDAOTest { private RedisEventHandlerDAO redisEventHandlerDAO; @Autowired private ObjectMapper objectMapper; @Before public void init() { ConductorProperties conductorProperties = mock(ConductorProperties.class); RedisProperties properties = mock(RedisProperties.class); JedisCommands jedisMock = new JedisMock(); JedisProxy jedisProxy = new JedisProxy(jedisMock); redisEventHandlerDAO = new RedisEventHandlerDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Test public void testEventHandlers() { String event1 = "SQS::arn:account090:sqstest1"; String event2 = "SQS::arn:account090:sqstest2"; EventHandler eventHandler = new EventHandler(); eventHandler.setName(UUID.randomUUID().toString()); eventHandler.setActive(false); Action action = new Action(); action.setAction(Type.start_workflow); action.setStart_workflow(new StartWorkflow()); action.getStart_workflow().setName("test_workflow"); eventHandler.getActions().add(action); eventHandler.setEvent(event1); redisEventHandlerDAO.addEventHandler(eventHandler); List<EventHandler> allEventHandlers = redisEventHandlerDAO.getAllEventHandlers(); assertNotNull(allEventHandlers); assertEquals(1, allEventHandlers.size()); assertEquals(eventHandler.getName(), allEventHandlers.get(0).getName()); assertEquals(eventHandler.getEvent(), allEventHandlers.get(0).getEvent()); List<EventHandler> byEvents = redisEventHandlerDAO.getEventHandlersForEvent(event1, true); assertNotNull(byEvents); assertEquals(0, byEvents.size()); // event is marked as in-active eventHandler.setActive(true); eventHandler.setEvent(event2); redisEventHandlerDAO.updateEventHandler(eventHandler); allEventHandlers = redisEventHandlerDAO.getAllEventHandlers(); assertNotNull(allEventHandlers); assertEquals(1, allEventHandlers.size()); byEvents = redisEventHandlerDAO.getEventHandlersForEvent(event1, true); assertNotNull(byEvents); assertEquals(0, byEvents.size()); byEvents = redisEventHandlerDAO.getEventHandlersForEvent(event2, true); assertNotNull(byEvents); assertEquals(1, byEvents.size()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisMetadataDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisMetadataDAOTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import java.time.Duration; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.function.Function; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.common.metadata.tasks.TaskDef; import com.netflix.conductor.common.metadata.tasks.TaskDef.RetryLogic; import com.netflix.conductor.common.metadata.tasks.TaskDef.TimeoutPolicy; import com.netflix.conductor.common.metadata.workflow.WorkflowDef; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.core.exception.ConflictException; import com.netflix.conductor.core.exception.NotFoundException; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.commands.JedisCommands; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class RedisMetadataDAOTest { private RedisMetadataDAO redisMetadataDAO; @Autowired private ObjectMapper objectMapper; @Before public void init() { ConductorProperties conductorProperties = mock(ConductorProperties.class); RedisProperties properties = mock(RedisProperties.class); when(properties.getTaskDefCacheRefreshInterval()).thenReturn(Duration.ofSeconds(60)); JedisCommands jedisMock = new JedisMock(); JedisProxy jedisProxy = new JedisProxy(jedisMock); redisMetadataDAO = new RedisMetadataDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Test(expected = ConflictException.class) public void testDup() { WorkflowDef def = new WorkflowDef(); def.setName("testDup"); def.setVersion(1); redisMetadataDAO.createWorkflowDef(def); redisMetadataDAO.createWorkflowDef(def); } @Test public void testWorkflowDefOperations() { WorkflowDef def = new WorkflowDef(); def.setName("test"); def.setVersion(1); def.setDescription("description"); def.setCreatedBy("unit_test"); def.setCreateTime(1L); def.setOwnerApp("ownerApp"); def.setUpdatedBy("unit_test2"); def.setUpdateTime(2L); redisMetadataDAO.createWorkflowDef(def); List<WorkflowDef> all = redisMetadataDAO.getAllWorkflowDefs(); assertNotNull(all); assertEquals(1, all.size()); assertEquals("test", all.get(0).getName()); assertEquals(1, all.get(0).getVersion()); WorkflowDef found = redisMetadataDAO.getWorkflowDef("test", 1).get(); assertEquals(def, found); def.setVersion(2); redisMetadataDAO.createWorkflowDef(def); all = redisMetadataDAO.getAllWorkflowDefs(); assertNotNull(all); assertEquals(2, all.size()); assertEquals("test", all.get(0).getName()); assertEquals(1, all.get(0).getVersion()); found = redisMetadataDAO.getLatestWorkflowDef(def.getName()).get(); assertEquals(def.getName(), found.getName()); assertEquals(def.getVersion(), found.getVersion()); assertEquals(2, found.getVersion()); all = redisMetadataDAO.getAllVersions(def.getName()); assertNotNull(all); assertEquals(2, all.size()); assertEquals("test", all.get(0).getName()); assertEquals("test", all.get(1).getName()); assertEquals(1, all.get(0).getVersion()); assertEquals(2, all.get(1).getVersion()); def.setDescription("updated"); redisMetadataDAO.updateWorkflowDef(def); found = redisMetadataDAO.getWorkflowDef(def.getName(), def.getVersion()).get(); assertEquals(def.getDescription(), found.getDescription()); List<String> allnames = redisMetadataDAO.findAll(); assertNotNull(allnames); assertEquals(1, allnames.size()); assertEquals(def.getName(), allnames.get(0)); redisMetadataDAO.removeWorkflowDef("test", 1); Optional<WorkflowDef> deleted = redisMetadataDAO.getWorkflowDef("test", 1); assertFalse(deleted.isPresent()); redisMetadataDAO.removeWorkflowDef("test", 2); Optional<WorkflowDef> latestDef = redisMetadataDAO.getLatestWorkflowDef("test"); assertFalse(latestDef.isPresent()); WorkflowDef[] workflowDefsArray = new WorkflowDef[3]; for (int i = 1; i <= 3; i++) { workflowDefsArray[i - 1] = new WorkflowDef(); workflowDefsArray[i - 1].setName("test"); workflowDefsArray[i - 1].setVersion(i); workflowDefsArray[i - 1].setDescription("description"); workflowDefsArray[i - 1].setCreatedBy("unit_test"); workflowDefsArray[i - 1].setCreateTime(1L); workflowDefsArray[i - 1].setOwnerApp("ownerApp"); workflowDefsArray[i - 1].setUpdatedBy("unit_test2"); workflowDefsArray[i - 1].setUpdateTime(2L); redisMetadataDAO.createWorkflowDef(workflowDefsArray[i - 1]); } redisMetadataDAO.removeWorkflowDef("test", 1); redisMetadataDAO.removeWorkflowDef("test", 2); WorkflowDef workflow = redisMetadataDAO.getLatestWorkflowDef("test").get(); assertEquals(workflow.getVersion(), 3); } @Test public void testGetAllWorkflowDefsLatestVersions() { WorkflowDef def = new WorkflowDef(); def.setName("test1"); def.setVersion(1); def.setDescription("description"); def.setCreatedBy("unit_test"); def.setCreateTime(1L); def.setOwnerApp("ownerApp"); def.setUpdatedBy("unit_test2"); def.setUpdateTime(2L); redisMetadataDAO.createWorkflowDef(def); def.setName("test2"); redisMetadataDAO.createWorkflowDef(def); def.setVersion(2); redisMetadataDAO.createWorkflowDef(def); def.setName("test3"); def.setVersion(1); redisMetadataDAO.createWorkflowDef(def); def.setVersion(2); redisMetadataDAO.createWorkflowDef(def); def.setVersion(3); redisMetadataDAO.createWorkflowDef(def); // Placed the values in a map because they might not be stored in order of defName. // To test, needed to confirm that the versions are correct for the definitions. Map<String, WorkflowDef> allMap = redisMetadataDAO.getAllWorkflowDefsLatestVersions().stream() .collect(Collectors.toMap(WorkflowDef::getName, Function.identity())); assertNotNull(allMap); assertEquals(3, allMap.size()); assertEquals(1, allMap.get("test1").getVersion()); assertEquals(2, allMap.get("test2").getVersion()); assertEquals(3, allMap.get("test3").getVersion()); } @Test(expected = NotFoundException.class) public void removeInvalidWorkflowDef() { redisMetadataDAO.removeWorkflowDef("hello", 1); } @Test public void testTaskDefOperations() { TaskDef def = new TaskDef("taskA"); def.setDescription("description"); def.setCreatedBy("unit_test"); def.setCreateTime(1L); def.setInputKeys(Arrays.asList("a", "b", "c")); def.setOutputKeys(Arrays.asList("01", "o2")); def.setOwnerApp("ownerApp"); def.setRetryCount(3); def.setRetryDelaySeconds(100); def.setRetryLogic(RetryLogic.FIXED); def.setTimeoutPolicy(TimeoutPolicy.ALERT_ONLY); def.setUpdatedBy("unit_test2"); def.setUpdateTime(2L); def.setRateLimitPerFrequency(50); def.setRateLimitFrequencyInSeconds(1); redisMetadataDAO.createTaskDef(def); TaskDef found = redisMetadataDAO.getTaskDef(def.getName()); assertEquals(def, found); def.setDescription("updated description"); redisMetadataDAO.updateTaskDef(def); found = redisMetadataDAO.getTaskDef(def.getName()); assertEquals(def, found); assertEquals("updated description", found.getDescription()); for (int i = 0; i < 9; i++) { TaskDef tdf = new TaskDef("taskA" + i); redisMetadataDAO.createTaskDef(tdf); } List<TaskDef> all = redisMetadataDAO.getAllTaskDefs(); assertNotNull(all); assertEquals(10, all.size()); Set<String> allnames = all.stream().map(TaskDef::getName).collect(Collectors.toSet()); assertEquals(10, allnames.size()); List<String> sorted = allnames.stream().sorted().collect(Collectors.toList()); assertEquals(def.getName(), sorted.get(0)); for (int i = 0; i < 9; i++) { assertEquals(def.getName() + i, sorted.get(i + 1)); } for (int i = 0; i < 9; i++) { redisMetadataDAO.removeTaskDef(def.getName() + i); } all = redisMetadataDAO.getAllTaskDefs(); assertNotNull(all); assertEquals(1, all.size()); assertEquals(def.getName(), all.get(0).getName()); } @Test(expected = NotFoundException.class) public void testRemoveTaskDef() { redisMetadataDAO.removeTaskDef("test" + UUID.randomUUID()); } @Test public void testDefaultsAreSetForResponseTimeout() { TaskDef def = new TaskDef("taskA"); def.setDescription("description"); def.setCreatedBy("unit_test"); def.setCreateTime(1L); def.setInputKeys(Arrays.asList("a", "b", "c")); def.setOutputKeys(Arrays.asList("01", "o2")); def.setOwnerApp("ownerApp"); def.setRetryCount(3); def.setRetryDelaySeconds(100); def.setRetryLogic(RetryLogic.FIXED); def.setTimeoutPolicy(TimeoutPolicy.ALERT_ONLY); def.setUpdatedBy("unit_test2"); def.setUpdateTime(2L); def.setRateLimitPerFrequency(50); def.setRateLimitFrequencyInSeconds(1); def.setResponseTimeoutSeconds(0); redisMetadataDAO.createTaskDef(def); TaskDef found = redisMetadataDAO.getTaskDef(def.getName()); assertEquals(found.getResponseTimeoutSeconds(), 3600); found.setTimeoutSeconds(200); found.setResponseTimeoutSeconds(0); redisMetadataDAO.updateTaskDef(found); TaskDef foundNew = redisMetadataDAO.getTaskDef(def.getName()); assertEquals(foundNew.getResponseTimeoutSeconds(), 199); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisPollDataDAOTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/dao/RedisPollDataDAOTest.java
/* * Copyright 2021 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.dao; import org.junit.Before; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import com.netflix.conductor.common.config.TestObjectMapperConfiguration; import com.netflix.conductor.core.config.ConductorProperties; import com.netflix.conductor.dao.PollDataDAO; import com.netflix.conductor.dao.PollDataDAOTest; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.jedis.JedisMock; import com.netflix.conductor.redis.jedis.JedisProxy; import com.fasterxml.jackson.databind.ObjectMapper; import redis.clients.jedis.commands.JedisCommands; import static org.mockito.Mockito.mock; @ContextConfiguration(classes = {TestObjectMapperConfiguration.class}) @RunWith(SpringRunner.class) public class RedisPollDataDAOTest extends PollDataDAOTest { private PollDataDAO redisPollDataDAO; @Autowired private ObjectMapper objectMapper; @Before public void init() { ConductorProperties conductorProperties = mock(ConductorProperties.class); RedisProperties properties = mock(RedisProperties.class); JedisCommands jedisMock = new JedisMock(); JedisProxy jedisProxy = new JedisProxy(jedisMock); redisPollDataDAO = new RedisPollDataDAO(jedisProxy, objectMapper, conductorProperties, properties); } @Override protected PollDataDAO getPollDataDAO() { return redisPollDataDAO; } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/ConfigurationHostSupplierTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/ConfigurationHostSupplierTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.jedis; import java.util.List; import org.junit.Before; import org.junit.Test; import com.netflix.conductor.redis.config.RedisProperties; import com.netflix.conductor.redis.dynoqueue.ConfigurationHostSupplier; import com.netflix.dyno.connectionpool.Host; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConfigurationHostSupplierTest { private RedisProperties properties; private ConfigurationHostSupplier configurationHostSupplier; @Before public void setUp() { properties = mock(RedisProperties.class); configurationHostSupplier = new ConfigurationHostSupplier(properties); } @Test public void getHost() { when(properties.getHosts()).thenReturn("dyno1:8102:us-east-1c"); List<Host> hosts = configurationHostSupplier.getHosts(); assertEquals(1, hosts.size()); Host firstHost = hosts.get(0); assertEquals("dyno1", firstHost.getHostName()); assertEquals(8102, firstHost.getPort()); assertEquals("us-east-1c", firstHost.getRack()); assertTrue(firstHost.isUp()); } @Test public void getMultipleHosts() { when(properties.getHosts()).thenReturn("dyno1:8102:us-east-1c;dyno2:8103:us-east-1c"); List<Host> hosts = configurationHostSupplier.getHosts(); assertEquals(2, hosts.size()); Host firstHost = hosts.get(0); assertEquals("dyno1", firstHost.getHostName()); assertEquals(8102, firstHost.getPort()); assertEquals("us-east-1c", firstHost.getRack()); assertTrue(firstHost.isUp()); Host secondHost = hosts.get(1); assertEquals("dyno2", secondHost.getHostName()); assertEquals(8103, secondHost.getPort()); assertEquals("us-east-1c", secondHost.getRack()); assertTrue(secondHost.isUp()); } @Test public void getAuthenticatedHost() { when(properties.getHosts()).thenReturn("redis1:6432:us-east-1c:password"); List<Host> hosts = configurationHostSupplier.getHosts(); assertEquals(1, hosts.size()); Host firstHost = hosts.get(0); assertEquals("redis1", firstHost.getHostName()); assertEquals(6432, firstHost.getPort()); assertEquals("us-east-1c", firstHost.getRack()); assertEquals("password", firstHost.getPassword()); assertTrue(firstHost.isUp()); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/JedisClusterTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/JedisClusterTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.jedis; import java.util.AbstractMap; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.junit.Test; import org.mockito.Mockito; import redis.clients.jedis.GeoUnit; import redis.clients.jedis.ListPosition; import redis.clients.jedis.ScanParams; import redis.clients.jedis.ScanResult; import redis.clients.jedis.SortingParams; import redis.clients.jedis.params.GeoRadiusParam; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.ZAddParams; import redis.clients.jedis.params.ZIncrByParams; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JedisClusterTest { private final redis.clients.jedis.JedisCluster mockCluster = mock(redis.clients.jedis.JedisCluster.class); private final JedisCluster jedisCluster = new JedisCluster(mockCluster); @Test public void testSet() { jedisCluster.set("key", "value"); jedisCluster.set("key", "value", SetParams.setParams()); } @Test public void testGet() { jedisCluster.get("key"); } @Test public void testExists() { jedisCluster.exists("key"); } @Test public void testPersist() { jedisCluster.persist("key"); } @Test public void testType() { jedisCluster.type("key"); } @Test public void testExpire() { jedisCluster.expire("key", 1337); } @Test public void testPexpire() { jedisCluster.pexpire("key", 1337); } @Test public void testExpireAt() { jedisCluster.expireAt("key", 1337); } @Test public void testPexpireAt() { jedisCluster.pexpireAt("key", 1337); } @Test public void testTtl() { jedisCluster.ttl("key"); } @Test public void testPttl() { jedisCluster.pttl("key"); } @Test public void testSetbit() { jedisCluster.setbit("key", 1337, "value"); jedisCluster.setbit("key", 1337, true); } @Test public void testGetbit() { jedisCluster.getbit("key", 1337); } @Test public void testSetrange() { jedisCluster.setrange("key", 1337, "value"); } @Test public void testGetrange() { jedisCluster.getrange("key", 1337, 1338); } @Test public void testGetSet() { jedisCluster.getSet("key", "value"); } @Test public void testSetnx() { jedisCluster.setnx("test", "value"); } @Test public void testSetex() { jedisCluster.setex("key", 1337, "value"); } @Test public void testPsetex() { jedisCluster.psetex("key", 1337, "value"); } @Test public void testDecrBy() { jedisCluster.decrBy("key", 1337); } @Test public void testDecr() { jedisCluster.decr("key"); } @Test public void testIncrBy() { jedisCluster.incrBy("key", 1337); } @Test public void testIncrByFloat() { jedisCluster.incrByFloat("key", 1337); } @Test public void testIncr() { jedisCluster.incr("key"); } @Test public void testAppend() { jedisCluster.append("key", "value"); } @Test public void testSubstr() { jedisCluster.substr("key", 1337, 1338); } @Test public void testHset() { jedisCluster.hset("key", "field", "value"); } @Test public void testHget() { jedisCluster.hget("key", "field"); } @Test public void testHsetnx() { jedisCluster.hsetnx("key", "field", "value"); } @Test public void testHmset() { jedisCluster.hmset("key", new HashMap<>()); } @Test public void testHmget() { jedisCluster.hmget("key", "fields"); } @Test public void testHincrBy() { jedisCluster.hincrBy("key", "field", 1337); } @Test public void testHincrByFloat() { jedisCluster.hincrByFloat("key", "field", 1337); } @Test public void testHexists() { jedisCluster.hexists("key", "field"); } @Test public void testHdel() { jedisCluster.hdel("key", "field"); } @Test public void testHlen() { jedisCluster.hlen("key"); } @Test public void testHkeys() { jedisCluster.hkeys("key"); } @Test public void testHvals() { jedisCluster.hvals("key"); } @Test public void testGgetAll() { jedisCluster.hgetAll("key"); } @Test public void testRpush() { jedisCluster.rpush("key", "string"); } @Test public void testLpush() { jedisCluster.lpush("key", "string"); } @Test public void testLlen() { jedisCluster.llen("key"); } @Test public void testLrange() { jedisCluster.lrange("key", 1337, 1338); } @Test public void testLtrim() { jedisCluster.ltrim("key", 1337, 1338); } @Test public void testLindex() { jedisCluster.lindex("key", 1337); } @Test public void testLset() { jedisCluster.lset("key", 1337, "value"); } @Test public void testLrem() { jedisCluster.lrem("key", 1337, "value"); } @Test public void testLpop() { jedisCluster.lpop("key"); } @Test public void testRpop() { jedisCluster.rpop("key"); } @Test public void testSadd() { jedisCluster.sadd("key", "member"); } @Test public void testSmembers() { jedisCluster.smembers("key"); } @Test public void testSrem() { jedisCluster.srem("key", "member"); } @Test public void testSpop() { jedisCluster.spop("key"); jedisCluster.spop("key", 1337); } @Test public void testScard() { jedisCluster.scard("key"); } @Test public void testSismember() { jedisCluster.sismember("key", "member"); } @Test public void testSrandmember() { jedisCluster.srandmember("key"); jedisCluster.srandmember("key", 1337); } @Test public void testStrlen() { jedisCluster.strlen("key"); } @Test public void testZadd() { jedisCluster.zadd("key", new HashMap<>()); jedisCluster.zadd("key", new HashMap<>(), ZAddParams.zAddParams()); jedisCluster.zadd("key", 1337, "members"); jedisCluster.zadd("key", 1337, "members", ZAddParams.zAddParams()); } @Test public void testZrange() { jedisCluster.zrange("key", 1337, 1338); } @Test public void testZrem() { jedisCluster.zrem("key", "member"); } @Test public void testZincrby() { jedisCluster.zincrby("key", 1337, "member"); jedisCluster.zincrby("key", 1337, "member", ZIncrByParams.zIncrByParams()); } @Test public void testZrank() { jedisCluster.zrank("key", "member"); } @Test public void testZrevrank() { jedisCluster.zrevrank("key", "member"); } @Test public void testZrevrange() { jedisCluster.zrevrange("key", 1337, 1338); } @Test public void testZrangeWithScores() { jedisCluster.zrangeWithScores("key", 1337, 1338); } @Test public void testZrevrangeWithScores() { jedisCluster.zrevrangeWithScores("key", 1337, 1338); } @Test public void testZcard() { jedisCluster.zcard("key"); } @Test public void testZscore() { jedisCluster.zscore("key", "member"); } @Test public void testSort() { jedisCluster.sort("key"); jedisCluster.sort("key", new SortingParams()); } @Test public void testZcount() { jedisCluster.zcount("key", "min", "max"); jedisCluster.zcount("key", 1337, 1338); } @Test public void testZrangeByScore() { jedisCluster.zrangeByScore("key", "min", "max"); jedisCluster.zrangeByScore("key", 1337, 1338); jedisCluster.zrangeByScore("key", "min", "max", 1337, 1338); jedisCluster.zrangeByScore("key", 1337, 1338, 1339, 1340); } @Test public void testZrevrangeByScore() { jedisCluster.zrevrangeByScore("key", "max", "min"); jedisCluster.zrevrangeByScore("key", 1337, 1338); jedisCluster.zrevrangeByScore("key", "max", "min", 1337, 1338); jedisCluster.zrevrangeByScore("key", 1337, 1338, 1339, 1340); } @Test public void testZrangeByScoreWithScores() { jedisCluster.zrangeByScoreWithScores("key", "min", "max"); jedisCluster.zrangeByScoreWithScores("key", "min", "max", 1337, 1338); jedisCluster.zrangeByScoreWithScores("key", 1337, 1338); jedisCluster.zrangeByScoreWithScores("key", 1337, 1338, 1339, 1340); } @Test public void testZrevrangeByScoreWithScores() { jedisCluster.zrevrangeByScoreWithScores("key", "max", "min"); jedisCluster.zrevrangeByScoreWithScores("key", "max", "min", 1337, 1338); jedisCluster.zrevrangeByScoreWithScores("key", 1337, 1338); jedisCluster.zrevrangeByScoreWithScores("key", 1337, 1338, 1339, 1340); } @Test public void testZremrangeByRank() { jedisCluster.zremrangeByRank("key", 1337, 1338); } @Test public void testZremrangeByScore() { jedisCluster.zremrangeByScore("key", "start", "end"); jedisCluster.zremrangeByScore("key", 1337, 1338); } @Test public void testZlexcount() { jedisCluster.zlexcount("key", "min", "max"); } @Test public void testZrangeByLex() { jedisCluster.zrangeByLex("key", "min", "max"); jedisCluster.zrangeByLex("key", "min", "max", 1337, 1338); } @Test public void testZrevrangeByLex() { jedisCluster.zrevrangeByLex("key", "max", "min"); jedisCluster.zrevrangeByLex("key", "max", "min", 1337, 1338); } @Test public void testZremrangeByLex() { jedisCluster.zremrangeByLex("key", "min", "max"); } @Test public void testLinsert() { jedisCluster.linsert("key", ListPosition.AFTER, "pivot", "value"); } @Test public void testLpushx() { jedisCluster.lpushx("key", "string"); } @Test public void testRpushx() { jedisCluster.rpushx("key", "string"); } @Test public void testBlpop() { jedisCluster.blpop(1337, "arg"); } @Test public void testBrpop() { jedisCluster.brpop(1337, "arg"); } @Test public void testDel() { jedisCluster.del("key"); } @Test public void testEcho() { jedisCluster.echo("string"); } @Test(expected = UnsupportedOperationException.class) public void testMove() { jedisCluster.move("key", 1337); } @Test public void testBitcount() { jedisCluster.bitcount("key"); jedisCluster.bitcount("key", 1337, 1338); } @Test(expected = UnsupportedOperationException.class) public void testBitpos() { jedisCluster.bitpos("key", true); } @Test public void testHscan() { jedisCluster.hscan("key", "cursor"); ScanResult<Entry<byte[], byte[]>> scanResult = new ScanResult<>( "cursor".getBytes(), Arrays.asList( new AbstractMap.SimpleEntry<>("key1".getBytes(), "val1".getBytes()), new AbstractMap.SimpleEntry<>( "key2".getBytes(), "val2".getBytes()))); when(mockCluster.hscan(Mockito.any(), Mockito.any(), Mockito.any(ScanParams.class))) .thenReturn(scanResult); ScanResult<Map.Entry<String, String>> result = jedisCluster.hscan("key", "cursor", new ScanParams()); assertEquals("cursor", result.getCursor()); assertEquals(2, result.getResult().size()); assertEquals("val1", result.getResult().get(0).getValue()); } @Test public void testSscan() { jedisCluster.sscan("key", "cursor"); ScanResult<byte[]> scanResult = new ScanResult<>( "sscursor".getBytes(), Arrays.asList("val1".getBytes(), "val2".getBytes())); when(mockCluster.sscan(Mockito.any(), Mockito.any(), Mockito.any(ScanParams.class))) .thenReturn(scanResult); ScanResult<String> result = jedisCluster.sscan("key", "cursor", new ScanParams()); assertEquals("sscursor", result.getCursor()); assertEquals(2, result.getResult().size()); assertEquals("val1", result.getResult().get(0)); } @Test public void testZscan() { jedisCluster.zscan("key", "cursor"); jedisCluster.zscan("key", "cursor", new ScanParams()); } @Test public void testPfadd() { jedisCluster.pfadd("key", "elements"); } @Test public void testPfcount() { jedisCluster.pfcount("key"); } @Test public void testGeoadd() { jedisCluster.geoadd("key", new HashMap<>()); jedisCluster.geoadd("key", 1337, 1338, "member"); } @Test public void testGeodist() { jedisCluster.geodist("key", "member1", "member2"); jedisCluster.geodist("key", "member1", "member2", GeoUnit.KM); } @Test public void testGeohash() { jedisCluster.geohash("key", "members"); } @Test public void testGeopos() { jedisCluster.geopos("key", "members"); } @Test public void testGeoradius() { jedisCluster.georadius("key", 1337, 1338, 32, GeoUnit.KM); jedisCluster.georadius("key", 1337, 1338, 32, GeoUnit.KM, GeoRadiusParam.geoRadiusParam()); } @Test public void testGeoradiusByMember() { jedisCluster.georadiusByMember("key", "member", 1337, GeoUnit.KM); jedisCluster.georadiusByMember( "key", "member", 1337, GeoUnit.KM, GeoRadiusParam.geoRadiusParam()); } @Test public void testBitfield() { jedisCluster.bitfield("key", "arguments"); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false
conductor-oss/conductor
https://github.com/conductor-oss/conductor/blob/aa7de922578fe59d1d145881299b1a8306dde3b0/redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/JedisSentinelTest.java
redis-persistence/src/test/java/com/netflix/conductor/redis/jedis/JedisSentinelTest.java
/* * Copyright 2020 Conductor Authors. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.netflix.conductor.redis.jedis; import java.util.HashMap; import org.junit.Before; import org.junit.Test; import redis.clients.jedis.GeoUnit; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisSentinelPool; import redis.clients.jedis.ListPosition; import redis.clients.jedis.ScanParams; import redis.clients.jedis.SortingParams; import redis.clients.jedis.params.GeoRadiusParam; import redis.clients.jedis.params.SetParams; import redis.clients.jedis.params.ZAddParams; import redis.clients.jedis.params.ZIncrByParams; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class JedisSentinelTest { private final Jedis jedis = mock(Jedis.class); private final JedisSentinelPool jedisPool = mock(JedisSentinelPool.class); private final JedisSentinel jedisSentinel = new JedisSentinel(jedisPool); @Before public void init() { when(this.jedisPool.getResource()).thenReturn(this.jedis); } @Test public void testSet() { jedisSentinel.set("key", "value"); jedisSentinel.set("key", "value", SetParams.setParams()); } @Test public void testGet() { jedisSentinel.get("key"); } @Test public void testExists() { jedisSentinel.exists("key"); } @Test public void testPersist() { jedisSentinel.persist("key"); } @Test public void testType() { jedisSentinel.type("key"); } @Test public void testExpire() { jedisSentinel.expire("key", 1337); } @Test public void testPexpire() { jedisSentinel.pexpire("key", 1337); } @Test public void testExpireAt() { jedisSentinel.expireAt("key", 1337); } @Test public void testPexpireAt() { jedisSentinel.pexpireAt("key", 1337); } @Test public void testTtl() { jedisSentinel.ttl("key"); } @Test public void testPttl() { jedisSentinel.pttl("key"); } @Test public void testSetbit() { jedisSentinel.setbit("key", 1337, "value"); jedisSentinel.setbit("key", 1337, true); } @Test public void testGetbit() { jedisSentinel.getbit("key", 1337); } @Test public void testSetrange() { jedisSentinel.setrange("key", 1337, "value"); } @Test public void testGetrange() { jedisSentinel.getrange("key", 1337, 1338); } @Test public void testGetSet() { jedisSentinel.getSet("key", "value"); } @Test public void testSetnx() { jedisSentinel.setnx("test", "value"); } @Test public void testSetex() { jedisSentinel.setex("key", 1337, "value"); } @Test public void testPsetex() { jedisSentinel.psetex("key", 1337, "value"); } @Test public void testDecrBy() { jedisSentinel.decrBy("key", 1337); } @Test public void testDecr() { jedisSentinel.decr("key"); } @Test public void testIncrBy() { jedisSentinel.incrBy("key", 1337); } @Test public void testIncrByFloat() { jedisSentinel.incrByFloat("key", 1337); } @Test public void testIncr() { jedisSentinel.incr("key"); } @Test public void testAppend() { jedisSentinel.append("key", "value"); } @Test public void testSubstr() { jedisSentinel.substr("key", 1337, 1338); } @Test public void testHset() { jedisSentinel.hset("key", "field", "value"); } @Test public void testHget() { jedisSentinel.hget("key", "field"); } @Test public void testHsetnx() { jedisSentinel.hsetnx("key", "field", "value"); } @Test public void testHmset() { jedisSentinel.hmset("key", new HashMap<>()); } @Test public void testHmget() { jedisSentinel.hmget("key", "fields"); } @Test public void testHincrBy() { jedisSentinel.hincrBy("key", "field", 1337); } @Test public void testHincrByFloat() { jedisSentinel.hincrByFloat("key", "field", 1337); } @Test public void testHexists() { jedisSentinel.hexists("key", "field"); } @Test public void testHdel() { jedisSentinel.hdel("key", "field"); } @Test public void testHlen() { jedisSentinel.hlen("key"); } @Test public void testHkeys() { jedisSentinel.hkeys("key"); } @Test public void testHvals() { jedisSentinel.hvals("key"); } @Test public void testGgetAll() { jedisSentinel.hgetAll("key"); } @Test public void testRpush() { jedisSentinel.rpush("key", "string"); } @Test public void testLpush() { jedisSentinel.lpush("key", "string"); } @Test public void testLlen() { jedisSentinel.llen("key"); } @Test public void testLrange() { jedisSentinel.lrange("key", 1337, 1338); } @Test public void testLtrim() { jedisSentinel.ltrim("key", 1337, 1338); } @Test public void testLindex() { jedisSentinel.lindex("key", 1337); } @Test public void testLset() { jedisSentinel.lset("key", 1337, "value"); } @Test public void testLrem() { jedisSentinel.lrem("key", 1337, "value"); } @Test public void testLpop() { jedisSentinel.lpop("key"); } @Test public void testRpop() { jedisSentinel.rpop("key"); } @Test public void testSadd() { jedisSentinel.sadd("key", "member"); } @Test public void testSmembers() { jedisSentinel.smembers("key"); } @Test public void testSrem() { jedisSentinel.srem("key", "member"); } @Test public void testSpop() { jedisSentinel.spop("key"); jedisSentinel.spop("key", 1337); } @Test public void testScard() { jedisSentinel.scard("key"); } @Test public void testSismember() { jedisSentinel.sismember("key", "member"); } @Test public void testSrandmember() { jedisSentinel.srandmember("key"); jedisSentinel.srandmember("key", 1337); } @Test public void testStrlen() { jedisSentinel.strlen("key"); } @Test public void testZadd() { jedisSentinel.zadd("key", new HashMap<>()); jedisSentinel.zadd("key", new HashMap<>(), ZAddParams.zAddParams()); jedisSentinel.zadd("key", 1337, "members"); jedisSentinel.zadd("key", 1337, "members", ZAddParams.zAddParams()); } @Test public void testZrange() { jedisSentinel.zrange("key", 1337, 1338); } @Test public void testZrem() { jedisSentinel.zrem("key", "member"); } @Test public void testZincrby() { jedisSentinel.zincrby("key", 1337, "member"); jedisSentinel.zincrby("key", 1337, "member", ZIncrByParams.zIncrByParams()); } @Test public void testZrank() { jedisSentinel.zrank("key", "member"); } @Test public void testZrevrank() { jedisSentinel.zrevrank("key", "member"); } @Test public void testZrevrange() { jedisSentinel.zrevrange("key", 1337, 1338); } @Test public void testZrangeWithScores() { jedisSentinel.zrangeWithScores("key", 1337, 1338); } @Test public void testZrevrangeWithScores() { jedisSentinel.zrevrangeWithScores("key", 1337, 1338); } @Test public void testZcard() { jedisSentinel.zcard("key"); } @Test public void testZscore() { jedisSentinel.zscore("key", "member"); } @Test public void testSort() { jedisSentinel.sort("key"); jedisSentinel.sort("key", new SortingParams()); } @Test public void testZcount() { jedisSentinel.zcount("key", "min", "max"); jedisSentinel.zcount("key", 1337, 1338); } @Test public void testZrangeByScore() { jedisSentinel.zrangeByScore("key", "min", "max"); jedisSentinel.zrangeByScore("key", 1337, 1338); jedisSentinel.zrangeByScore("key", "min", "max", 1337, 1338); jedisSentinel.zrangeByScore("key", 1337, 1338, 1339, 1340); } @Test public void testZrevrangeByScore() { jedisSentinel.zrevrangeByScore("key", "max", "min"); jedisSentinel.zrevrangeByScore("key", 1337, 1338); jedisSentinel.zrevrangeByScore("key", "max", "min", 1337, 1338); jedisSentinel.zrevrangeByScore("key", 1337, 1338, 1339, 1340); } @Test public void testZrangeByScoreWithScores() { jedisSentinel.zrangeByScoreWithScores("key", "min", "max"); jedisSentinel.zrangeByScoreWithScores("key", "min", "max", 1337, 1338); jedisSentinel.zrangeByScoreWithScores("key", 1337, 1338); jedisSentinel.zrangeByScoreWithScores("key", 1337, 1338, 1339, 1340); } @Test public void testZrevrangeByScoreWithScores() { jedisSentinel.zrevrangeByScoreWithScores("key", "max", "min"); jedisSentinel.zrevrangeByScoreWithScores("key", "max", "min", 1337, 1338); jedisSentinel.zrevrangeByScoreWithScores("key", 1337, 1338); jedisSentinel.zrevrangeByScoreWithScores("key", 1337, 1338, 1339, 1340); } @Test public void testZremrangeByRank() { jedisSentinel.zremrangeByRank("key", 1337, 1338); } @Test public void testZremrangeByScore() { jedisSentinel.zremrangeByScore("key", "start", "end"); jedisSentinel.zremrangeByScore("key", 1337, 1338); } @Test public void testZlexcount() { jedisSentinel.zlexcount("key", "min", "max"); } @Test public void testZrangeByLex() { jedisSentinel.zrangeByLex("key", "min", "max"); jedisSentinel.zrangeByLex("key", "min", "max", 1337, 1338); } @Test public void testZrevrangeByLex() { jedisSentinel.zrevrangeByLex("key", "max", "min"); jedisSentinel.zrevrangeByLex("key", "max", "min", 1337, 1338); } @Test public void testZremrangeByLex() { jedisSentinel.zremrangeByLex("key", "min", "max"); } @Test public void testLinsert() { jedisSentinel.linsert("key", ListPosition.AFTER, "pivot", "value"); } @Test public void testLpushx() { jedisSentinel.lpushx("key", "string"); } @Test public void testRpushx() { jedisSentinel.rpushx("key", "string"); } @Test public void testBlpop() { jedisSentinel.blpop(1337, "arg"); } @Test public void testBrpop() { jedisSentinel.brpop(1337, "arg"); } @Test public void testDel() { jedisSentinel.del("key"); } @Test public void testEcho() { jedisSentinel.echo("string"); } @Test public void testMove() { jedisSentinel.move("key", 1337); } @Test public void testBitcount() { jedisSentinel.bitcount("key"); jedisSentinel.bitcount("key", 1337, 1338); } @Test public void testBitpos() { jedisSentinel.bitpos("key", true); } @Test public void testHscan() { jedisSentinel.hscan("key", "cursor"); jedisSentinel.hscan("key", "cursor", new ScanParams()); } @Test public void testSscan() { jedisSentinel.sscan("key", "cursor"); jedisSentinel.sscan("key", "cursor", new ScanParams()); } @Test public void testZscan() { jedisSentinel.zscan("key", "cursor"); jedisSentinel.zscan("key", "cursor", new ScanParams()); } @Test public void testPfadd() { jedisSentinel.pfadd("key", "elements"); } @Test public void testPfcount() { jedisSentinel.pfcount("key"); } @Test public void testGeoadd() { jedisSentinel.geoadd("key", new HashMap<>()); jedisSentinel.geoadd("key", 1337, 1338, "member"); } @Test public void testGeodist() { jedisSentinel.geodist("key", "member1", "member2"); jedisSentinel.geodist("key", "member1", "member2", GeoUnit.KM); } @Test public void testGeohash() { jedisSentinel.geohash("key", "members"); } @Test public void testGeopos() { jedisSentinel.geopos("key", "members"); } @Test public void testGeoradius() { jedisSentinel.georadius("key", 1337, 1338, 32, GeoUnit.KM); jedisSentinel.georadius("key", 1337, 1338, 32, GeoUnit.KM, GeoRadiusParam.geoRadiusParam()); } @Test public void testGeoradiusByMember() { jedisSentinel.georadiusByMember("key", "member", 1337, GeoUnit.KM); jedisSentinel.georadiusByMember( "key", "member", 1337, GeoUnit.KM, GeoRadiusParam.geoRadiusParam()); } @Test public void testBitfield() { jedisSentinel.bitfield("key", "arguments"); } }
java
Apache-2.0
aa7de922578fe59d1d145881299b1a8306dde3b0
2026-01-04T14:46:58.351252Z
false