Repository navigation
Description
The backend (api, executor, registry, Spring Boot 4.1.2) carries a fair amount of hand-written infrastructure code that Spring Boot or Spring Framework already provides. This issue tracks replacing it, one pull request per item, in the order below.
Items 1-5 remove the most code. Items 6-9 are smaller clean-ups.
Tasks
- 1. Quartz: use Spring Boot auto-configuration and declarative job beans
- 2. Redis: use
spring.data.redis.*and SSL bundles - 3. Retries: use Spring Framework 7
RetryTemplate/@Retryable - 4. HTTP clients: standardise the API module on
RestClient - 5. JWT: issue with
NimbusJwtEncoder, resolve issuers with Spring Security - 6. Configuration: drop redundant
@PropertySource, group@Valueinto@ConfigurationProperties - 7. Jackson: inject the shared
ObjectMapper - 8. Threads: move raw pools to Spring-managed executors
- 9. Errors: centralise controller exception handling
Not in scope
EncryptionService: its ciphertext format is already stored in the database and differs from Spring Security Crypto.ExecutionLeaseandContextWriteLock: the lease semantics are a documented scheduler invariant.- The three transactional outboxes (notifications, run triggers, repo webhooks).
- The Feign-based
TerrakubeClient, which comes from the externalterrakube-spring-boot-starter.
1. Quartz: use Spring Boot auto-configuration and declarative job beans
Problem
api/src/main/java/io/terrakube/api/plugin/scheduler/configuration/QuartzAutoConfiguration.java declares its own SchedulerFactoryBean and a private copy of AutowireCapableBeanJobFactory (Spring Boot already ships one).
- Because the application defines its own
SchedulerFactoryBean, Spring Boot's Quartz auto-configuration backs off (@ConditionalOnMissingBean). Thespring.quartz.*entries inapi/src/main/resources/application.propertiestherefore look like dead configuration, includingspring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=20000. This needs to be confirmed on a running instance. - Eleven
*Scheduler/*Serviceclasses repeat the same@PostConstruct"delete the job, buildJobDetail+Trigger, schedule it" block (~60 lines each):NotificationOutboxPollerScheduler,NotificationOutboxRetentionScheduler,RunTriggerEventPollerScheduler,RunTriggerEventRetentionScheduler,RepoWebhookDeliveryPollerScheduler,RepoWebhookDeliveryRetentionScheduler,DeleteJobLogStreamScheduler,PolicyDriftEvaluationScheduler,PolicyEvaluationRetentionScheduler,InactiveJobsService,JobReconciliationSweepService.
Proposal
- Drop the custom
SchedulerFactoryBeanand job factory; configure Quartz throughspring.quartz.*(job store, clustering, thread count, driver delegate) so the properties already in the file take effect. - Keep
io.terrakube.scheduler.thread-countandio.terrakube.api.plugin.scheduler.instanceNameworking by mapping them onto thespring.quartz.properties.*keys. - Replace the fixed-schedule registration classes with
JobDetailandTriggerbeans plusspring.quartz.overwrite-existing-jobs=true. - Leave dynamic, per-entity jobs (
ScheduleJobService,ScheduleServiceBase,RepoWebhookSyncScheduler,SpoolRecoveryScheduler) on the programmaticSchedulerAPI.
Acceptance
- Job and trigger keys stay the same, so an upgraded cluster does not end up with duplicated or orphaned rows in
QRTZ_*. SchedulerThreadPoolValidationstill fails startup when the Quartz pool is not smaller than the Hikari pool.- Clustered single-fire behaviour is unchanged with two API replicas.
2. Redis: use spring.data.redis.* and SSL bundles
Problem
Two near-identical classes assemble the Redis connection by hand (~350 lines together):
executor/src/main/java/io/terrakube/executor/configuration/RedisAutoConfiguration.javaapi/src/main/java/io/terrakube/api/plugin/streaming/StreamingConfiguration.java
Each one loads a JKS trust store, builds an SSLSocketFactory, and picks between standalone, sentinel and cluster JedisConnectionFactory setups. Spring Boot's Redis auto-configuration covers all of this through spring.data.redis.* and SSL bundles.
There is also a bug in the hand-written path: when the trust store cannot be loaded, the exception is only logged and the connection is built with an empty trust store.
Proposal
- Remove the custom connection factory, trust store and
RedisTemplatewiring in both modules and rely onspring.data.redis.*(host, port, username, password,sentinel.*,cluster.*,jedis.pool.*,ssl.bundle). - Keep the existing
io.terrakube.executor.redis.*/ streaming property names and environment variables working by mapping them with placeholders inapplication.properties. This is an operator-facing contract and must not break. - Fail startup when a configured trust store cannot be read.
Notes
api/.../plugin/logs/LogsService.javachecksinstanceof JedisConnectionFactory; keep Jedis as the client (spring.data.redis.client-type=jedis) or adjust that code.SubscriptionRedisConfigurationandExecutorAvailabilityListeneralready depend on the genericRedisConnectionFactory.
Acceptance
- Standalone, sentinel, cluster and TLS setups work with the same environment variables as before.
- Existing Helm values and the devcontainer start without changes.
3. Retries: use Spring Framework 7 RetryTemplate / @Retryable
Problem
Retries are implemented by hand in several places, with Thread.sleep loops and no shared policy:
StorageRetryMetricsexists twice, inapi/.../plugin/storage/andexecutor/.../plugin/tfstate/.executor/.../configuration/ResilientTerrakubeClientConfiguration.javais aBeanPostProcessorthat wrapsTerrakubeClientin a JDK proxy only to retry three times with backoff.JobContextService,JobVersionPinner,PlanStructuredOutputService,ApplyStructuredOutputServiceandStructuredOutputPersistenceQueuein the executor each carry their own loop.
Spring Framework 7 ships retry support in core (org.springframework.core.retry.RetryTemplate, @Retryable, @EnableResilientMethods); no extra dependency is needed.
Proposal
- Replace the loops with
RetryTemplate/@Retryableand a small number of named policies (attempts, backoff, retryable exceptions). - Keep the existing Micrometer metrics (
terrakube.api.storage.duration,terrakube.api.storage.failuresand the executor equivalents) by recording them from aRetryListener. - Keep the current behaviour on exhaustion:
StorageUnavailableExceptionfor storage, and the original cause forTerrakubeClient.
Out of scope
DispatchRetry* in the scheduler is a persisted, database-driven retry schedule and stays as it is.
Acceptance
- Same attempt counts and backoff as today.
- Interrupts are still propagated instead of swallowed.
- Existing retry tests pass without relaxing their assertions.
4. HTTP clients: standardise the API module on RestClient
Problem
The API module talks HTTP through four different stacks:
RestTemplatein 16 files, built three different ways (SimpleClientHttpRequestFactory, Apache HttpClient 5, JDKHttpClient)WebClientin 14 filesRestClientin 7 files- raw
java.net.http.HttpClient
Specific issues:
plugin/proxy/RestTemplateFactory.javaexists only to set timeouts and disable redirects.GitLabRepositoryDiscoveryService,BitbucketRepositoryDiscoveryService,AzDevOpsRepositoryDiscoveryServiceandGitLabWebhookServicecreate a newRestTemplateper request.importer/tfcloud/services/WorkspaceService.javausesnew RestTemplate()with no timeouts.- 14 classes import
org.apache.hc.core5.http.HttpStatusonly for status constants.
Proposal
- Standardise blocking calls on
RestClient, built from the auto-configuredRestClient.Builderso clients get shared timeouts, redirect policy and Micrometer observations. Usespring.http.clients.*for the defaults. - Remove
RestTemplateFactoryand the per-requestRestTemplateinstances. - Keep
WebClientwhere reactive timeouts are part of the contract (see.agents/rules/http-client-conventions.md); this issue is not about removing it. - Replace the Apache
HttpStatusimports withorg.springframework.http.HttpStatus.
Must stay
WebhookHttpClientConfig.SameOriginRedirectStrategy(cross-origin redirect blocking).DestinationUrlValidator/VcsApiUrlValidatorSSRF checks before every outbound call.- Notification delivery outside database transactions.
Acceptance
- No outbound client without connect and read timeouts.
- Redirects stay disabled wherever they are disabled today.
- This can be split per area (notifications, VCS discovery, VCS providers, importer) into separate pull requests.
5. JWT: issue with NimbusJwtEncoder, resolve issuers with Spring Security
Problem
JWT handling mixes jjwt and Spring Security, and part of it is hand-written:
- Tokens are issued with jjwt (
Jwts.builder()) inPatService,TeamTokenService,PersistentExecutorService,GitHubTokenService,DynamicCredentialsService,WorkspaceSecurityImpl(executor) andRegistryTokenService(registry), while validation already usesNimbusJwtDecoder. - Three
AuthenticationManagerResolverimplementations pick the decoder by splitting the bearer token, Base64-decoding the payload and parsing it withnew ObjectMapper(), and each keeps its own decoder cache:api/.../security/authentication/dex/DexAuthenticationManagerResolver.java(247 lines)registry/.../authentication/dex/RegistryAuthenticationManagerResolver.java(484 lines)executor/.../configuration/security/ExecutorManagerResolver.java(131 lines)
Proposal
- Issue tokens with
NimbusJwtEncoderand drop the three jjwt artifacts. - Select the decoder with
JwtIssuerAuthenticationManagerResolverand a custom issuer-to-manager resolver instead of parsing the payload manually. - Move PAT / team-token revocation, federated claim matching and the Dex audience check into
OAuth2TokenValidatorimplementations attached to the decoders.
Constraints
This is security-critical and must follow .agents/rules/security-authorization.md:
- Fail closed on missing or malformed tokens.
- A federated issuer/audience match with failed claim conditions stays an explicit denial and never falls back to Dex.
ActiveStepTokenValidatorkeeps revoking internal step tokens throughStepstatus.- Internal token classification (
InternalTokenClassifier) and the executor's dispatch-token checks are unchanged. - Tokens already issued (PATs, team tokens) must keep validating: same algorithm selection by key length, same claims.
Acceptance
- Existing authentication tests pass unchanged, and tokens minted by the previous release are accepted.
- Needs a dedicated security review before merge.
6. Configuration: drop redundant @PropertySource, group @Value into @ConfigurationProperties
Problem
- 31 properties classes carry
@PropertySource("classpath:application.properties")and@PropertySource("classpath:application-${spring.profiles.active}.properties"). Spring Boot already loads both, and the second form resolves to a non-existent file when more than one profile is active. - Some of them are both
@Componentand@ConfigurationPropertiesinstead of being registered with@EnableConfigurationProperties/@ConfigurationPropertiesScan. - In the API module 65 files read configuration with
@Value, often several keys of the same prefix in one constructor (for exampleWebhookHttpClientConfig,QuartzAutoConfiguration, the Quartz retention jobs).
Proposal
- Remove the redundant
@PropertySourceannotations. - Register properties classes through
@ConfigurationPropertiesScan. - Group related
@Valuekeys into@ConfigurationPropertiesclasses, starting with the prefixes that have the most keys. Property names and environment variables stay the same.
Acceptance
- No change in effective configuration with a single profile, with several profiles, and with no profile.
spring-boot-configuration-processormetadata covers the migrated keys.
7. Jackson: inject the shared ObjectMapper
Problem
new ObjectMapper() appears in 23 production files across api, executor and registry, including per-request construction (for example in the authentication resolvers) and a bare new ObjectMapper() bean in ServerApplication. Mappers created this way ignore the application's Jackson configuration and are needlessly re-created.
Proposal
- Inject the shared
ObjectMapperbean instead of constructing one. - Where a deliberately different configuration is needed (the Feign clients in
TerrakubeClientConfigurationuseNON_NULLand ignore unknown properties), build it once from the shared mapper withcopy()and keep it in a field.
Related
The code base is on Jackson 2 (com.fasterxml.jackson), while Spring Boot 4 defaults to Jackson 3 (tools.jackson). Moving to Jackson 3 is a separate, larger migration; centralising mapper creation first makes it much smaller.
Acceptance
- No
new ObjectMapper()left outside configuration classes. - JSON output of the public endpoints is byte-for-byte unchanged in existing tests.
8. Threads: move raw pools to Spring-managed executors
Problem
Several components create and own raw threads or java.util.concurrent pools, outside Spring's lifecycle, graceful shutdown and metrics:
- API: static
LOCK_RENEWALscheduler inScheduleJob,AzDevOpsPollingService,ContextReadService - Executor:
StructuredOutputPersistenceQueue,StepOutputPartWriter,BashEngine,GroovyEngine(Executors.newWorkStealingPool()),InfracostExecutorServiceImpl executor/.../configuration/SpringAsyncAutoConfiguration.javahand-builds the single-thread@Asyncexecutor thatspring.task.execution.*can describe.
Proposal
- Replace them with Spring-managed
TaskExecutor/TaskSchedulerbeans (named, bounded, instrumented), following the existing pattern ofNotificationDispatchExecutorConfigandModuleRefreshExecutorConfig. - Configure the executor's
@Asyncpool throughspring.task.execution.*and keep its semantics: one job at a time, no queue.
Must stay
- The execution-lease renewal keeps its 30s cadence and must not be starved by other work.
ExecutorCapacityGatebehaviour in the executor is unchanged.
Acceptance
- All pools are shut down on context close, and in-flight work is drained or cancelled explicitly.
- Thread names stay recognisable in thread dumps.
9. Errors: centralise controller exception handling
Problem
Several REST controllers translate exceptions into HTTP responses inline, with repeated try/catch blocks that build ResponseEntity by hand: ContextController (11 catch blocks), OAuthBrokerController (8), WebHookController, VcsRepositoryController, TerraformStateController, TfCloudController, and OnlineModeServiceImpl in the executor. Only storage failures go through a shared handler (StorageExceptionHandler).
Proposal
- Move the exception-to-status mapping into
@RestControllerAdviceclasses, one per protocol surface. - Use
ProblemDetail(spring.mvc.problemdetails.enabled=true) for Terrakube's own endpoints.
Must stay
/remote/tfe/v2/*and the registry protocol endpoints keep the error shapes the Terraform CLI expects.- Elide (
/api/v1,/graphql/api/v1) error handling is not touched. - Unauthenticated endpoints keep returning no internal identifiers.
Acceptance
- Status codes and headers (for example
Retry-Afteron storage failures) are unchanged for every existing test.
Activity
Macbet commentedon Nov 29, 2026
Progress on the first items:
The pull requests are stacked in that order.
Item 5 (JWT) is not worth doing as written. It was implemented on a local branch and then left out of the stack, for these reasons:
NimbusJwtEncodercannot reproduce the current tokens. It writes a one-elementaudas a string, while PAT, team, dispatch and registry tokens carry an array. It also adds akidheader to HMAC tokens and needs the RSA public key, which the GitHub App and dynamic-credential configuration does not have. Tokens would stop being interchangeable between old and new pods and with third-party verifiers.terrakube-clientcalls it at runtime.JwtIssuerAuthenticationManagerResolveronly passes the issuer to its delegate. The resolvers here choose a decoder from the audience, the federated claim conditions and the PAT revocation check before any signature is verified. Moving those checks into validators would change the order of rejections and the error responses.A smaller follow-up that would still be useful: inject the shared
ObjectMapperinto the three resolvers instead of creating one per request (covered by item 7).Items 6-9 are on hold until the first four are merged, since item 6 touches many files and would conflict with them.
fix(api,executor): keep Redis cluster node parsing and start with max…
refactor(api,executor): drive retries with Spring's RetryTemplate
refactor(executor): share the final snapshot retry between plan and a…
refactor(api): move blocking HTTP calls from RestTemplate to RestClient
build: add a common module and move the shared Redis wiring into it
refactor(api,executor): drive retries with Spring's RetryTemplate
refactor(executor): share the final snapshot retry between plan and a…
refactor(api,executor): share the storage retry and metrics code
refactor(api): move blocking HTTP calls from RestTemplate to RestClient
41 remaining items
refactor(api): move blocking HTTP calls from RestTemplate to RestClient
refactor(api,executor): drive retries with Spring's RetryTemplate
refactor(executor): share the final snapshot retry between plan and a…
refactor(api,executor): share the storage retry and metrics code
docs: describe the shared storage retry class and the -am build rule
refactor(api): move blocking HTTP calls from RestTemplate to RestClient
refactor(api,executor): configure Redis through Spring Boot auto-conf…
fix(api,executor): keep Redis cluster node parsing and start with max…
build: add a common module and move the shared Redis wiring into it
build: name the shared artifact terrakube-common and tidy its build
refactor(api,executor): drive retries with Spring's RetryTemplate
refactor(executor): share the final snapshot retry between plan and a…
refactor(api,executor): share the storage retry and metrics code
docs: describe the shared storage retry class and the -am build rule
refactor(api): move blocking HTTP calls from RestTemplate to RestClient