Skip to content

Replace hand-written infrastructure code with Spring Boot built-ins #4052

Backlog

Description

@Macbet

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 @Value into @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.
  • ExecutionLease and ContextWriteLock: 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 external terrakube-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). The spring.quartz.* entries in api/src/main/resources/application.properties therefore look like dead configuration, including spring.quartz.properties.org.quartz.jobStore.clusterCheckinInterval=20000. This needs to be confirmed on a running instance.
  • Eleven *Scheduler / *Service classes repeat the same @PostConstruct "delete the job, build JobDetail + Trigger, schedule it" block (~60 lines each): NotificationOutboxPollerScheduler, NotificationOutboxRetentionScheduler, RunTriggerEventPollerScheduler, RunTriggerEventRetentionScheduler, RepoWebhookDeliveryPollerScheduler, RepoWebhookDeliveryRetentionScheduler, DeleteJobLogStreamScheduler, PolicyDriftEvaluationScheduler, PolicyEvaluationRetentionScheduler, InactiveJobsService, JobReconciliationSweepService.

Proposal

  • Drop the custom SchedulerFactoryBean and job factory; configure Quartz through spring.quartz.* (job store, clustering, thread count, driver delegate) so the properties already in the file take effect.
  • Keep io.terrakube.scheduler.thread-count and io.terrakube.api.plugin.scheduler.instanceName working by mapping them onto the spring.quartz.properties.* keys.
  • Replace the fixed-schedule registration classes with JobDetail and Trigger beans plus spring.quartz.overwrite-existing-jobs=true.
  • Leave dynamic, per-entity jobs (ScheduleJobService, ScheduleServiceBase, RepoWebhookSyncScheduler, SpoolRecoveryScheduler) on the programmatic Scheduler API.

Acceptance

  • Job and trigger keys stay the same, so an upgraded cluster does not end up with duplicated or orphaned rows in QRTZ_*.
  • SchedulerThreadPoolValidation still 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.java
  • api/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 RedisTemplate wiring in both modules and rely on spring.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 in application.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.java checks instanceof JedisConnectionFactory; keep Jedis as the client (spring.data.redis.client-type=jedis) or adjust that code.
  • SubscriptionRedisConfiguration and ExecutorAvailabilityListener already depend on the generic RedisConnectionFactory.

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:

  • StorageRetryMetrics exists twice, in api/.../plugin/storage/ and executor/.../plugin/tfstate/.
  • executor/.../configuration/ResilientTerrakubeClientConfiguration.java is a BeanPostProcessor that wraps TerrakubeClient in a JDK proxy only to retry three times with backoff.
  • JobContextService, JobVersionPinner, PlanStructuredOutputService, ApplyStructuredOutputService and StructuredOutputPersistenceQueue in 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 / @Retryable and a small number of named policies (attempts, backoff, retryable exceptions).
  • Keep the existing Micrometer metrics (terrakube.api.storage.duration, terrakube.api.storage.failures and the executor equivalents) by recording them from a RetryListener.
  • Keep the current behaviour on exhaustion: StorageUnavailableException for storage, and the original cause for TerrakubeClient.

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:

  • RestTemplate in 16 files, built three different ways (SimpleClientHttpRequestFactory, Apache HttpClient 5, JDK HttpClient)
  • WebClient in 14 files
  • RestClient in 7 files
  • raw java.net.http.HttpClient

Specific issues:

  • plugin/proxy/RestTemplateFactory.java exists only to set timeouts and disable redirects.
  • GitLabRepositoryDiscoveryService, BitbucketRepositoryDiscoveryService, AzDevOpsRepositoryDiscoveryService and GitLabWebhookService create a new RestTemplate per request.
  • importer/tfcloud/services/WorkspaceService.java uses new RestTemplate() with no timeouts.
  • 14 classes import org.apache.hc.core5.http.HttpStatus only for status constants.

Proposal

  • Standardise blocking calls on RestClient, built from the auto-configured RestClient.Builder so clients get shared timeouts, redirect policy and Micrometer observations. Use spring.http.clients.* for the defaults.
  • Remove RestTemplateFactory and the per-request RestTemplate instances.
  • Keep WebClient where reactive timeouts are part of the contract (see .agents/rules/http-client-conventions.md); this issue is not about removing it.
  • Replace the Apache HttpStatus imports with org.springframework.http.HttpStatus.

Must stay

  • WebhookHttpClientConfig.SameOriginRedirectStrategy (cross-origin redirect blocking).
  • DestinationUrlValidator / VcsApiUrlValidator SSRF 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()) in PatService, TeamTokenService, PersistentExecutorService, GitHubTokenService, DynamicCredentialsService, WorkspaceSecurityImpl (executor) and RegistryTokenService (registry), while validation already uses NimbusJwtDecoder.
  • Three AuthenticationManagerResolver implementations pick the decoder by splitting the bearer token, Base64-decoding the payload and parsing it with new 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 NimbusJwtEncoder and drop the three jjwt artifacts.
  • Select the decoder with JwtIssuerAuthenticationManagerResolver and 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 OAuth2TokenValidator implementations 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.
  • ActiveStepTokenValidator keeps revoking internal step tokens through Step status.
  • 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 @Component and @ConfigurationProperties instead 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 example WebhookHttpClientConfig, QuartzAutoConfiguration, the Quartz retention jobs).

Proposal

  • Remove the redundant @PropertySource annotations.
  • Register properties classes through @ConfigurationPropertiesScan.
  • Group related @Value keys into @ConfigurationProperties classes, 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-processor metadata 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 ObjectMapper bean instead of constructing one.
  • Where a deliberately different configuration is needed (the Feign clients in TerrakubeClientConfiguration use NON_NULL and ignore unknown properties), build it once from the shared mapper with copy() 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_RENEWAL scheduler in ScheduleJob, AzDevOpsPollingService, ContextReadService
  • Executor: StructuredOutputPersistenceQueue, StepOutputPartWriter, BashEngine, GroovyEngine (Executors.newWorkStealingPool()), InfracostExecutorServiceImpl
  • executor/.../configuration/SpringAsyncAutoConfiguration.java hand-builds the single-thread @Async executor that spring.task.execution.* can describe.

Proposal

  • Replace them with Spring-managed TaskExecutor / TaskScheduler beans (named, bounded, instrumented), following the existing pattern of NotificationDispatchExecutorConfig and ModuleRefreshExecutorConfig.
  • Configure the executor's @Async pool through spring.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.
  • ExecutorCapacityGate behaviour 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 @RestControllerAdvice classes, 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-After on storage failures) are unchanged for every existing test.

Activity

  1. Macbet commented on Nov 29, 2026

    @Macbet
    ContributorAuthor

    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:

    • NimbusJwtEncoder cannot reproduce the current tokens. It writes a one-element aud as a string, while PAT, team, dispatch and registry tokens carry an array. It also adds a kid header 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.
    • Removing jjwt therefore meant writing our own signing helper on Nimbus JOSE, copied into three modules, plus a port of jjwt's Base64URL decoder to keep secret handling identical. That replaces a library with more hand-written code in a security-sensitive place.
    • jjwt stays on the executor and registry classpath anyway, because terrakube-client calls it at runtime.
    • JwtIssuerAuthenticationManagerResolver only 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 ObjectMapper into 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.

  2. 41 remaining items

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    technical debtterrakube-apiterrakube-executorterrakube-registrytype/refactor

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions