refactor: 리펙토링 진행중 의존성 gradle은 얇게 유지, 각 모듈에서 처리하고 있는 부분에 대해서 리펙토링
This commit is contained in:
@@ -5,6 +5,8 @@ plugins {
|
||||
id 'ca.config-contract'
|
||||
id 'ca.auxiliary-source-set'
|
||||
id 'ca.bootrun-dotenv'
|
||||
id 'ca.strict-qualification'
|
||||
id 'ca.dependency-policy'
|
||||
}
|
||||
|
||||
def contractRegistriesDirectory = rootProject.projectDir.parentFile.toPath()
|
||||
@@ -83,19 +85,48 @@ dependencies {
|
||||
implementation project(':domain-core')
|
||||
implementation project(':application-core')
|
||||
implementation project(':application-notification')
|
||||
implementation project(':application-fileserver')
|
||||
implementation project(':adapter:outbound:persistence-jpa')
|
||||
|
||||
// The JPA rule pack, for the production architecture suite. Test scope only: the rules are
|
||||
// ArchUnit assertions, and the composition root is the one place that can see every runtime
|
||||
// leaf at once — which is what makes it the right consumer and the wrong shipper.
|
||||
// Fileserver is not selected by the minimal composition (see the dependencyPolicy block at the
|
||||
// end of this file). These lanes select it, because they are what proves the capability still
|
||||
// assembles and still stays off — a contract that cannot be verified from an artifact that does
|
||||
// not contain it. Object storage already works exactly this way.
|
||||
testImplementation project(':composition:fileserver-platform')
|
||||
// The leaf as well as the composition: a handful of bootstrap tests name the adapter's own
|
||||
// types — the off-state gating inventory and the entity-scan registration among them — and a
|
||||
// composition that re-exported them would be an `api` edge this module does not want.
|
||||
testImplementation project(':adapter:outbound:fileserver')
|
||||
testImplementation project(':application-fileserver')
|
||||
integrationTestImplementation project(':composition:fileserver-platform')
|
||||
integrationTestImplementation project(':adapter:inbound:web-fileserver')
|
||||
|
||||
testImplementation(testFixtures(project(':adapter:outbound:persistence-jpa')))
|
||||
testImplementation(testFixtures(project(':adapter:inbound:web')))
|
||||
// The three capabilities above are runtimeOnly for main, and these tests name their types —
|
||||
// the import filters, the deployment-mode enum, the settings records. Declared here rather than
|
||||
// widened back to `implementation`, so the composition root's own sources still cannot reach
|
||||
// them. The Mongo exclusions are repeated because MongoShippedCompositionContractTest asserts
|
||||
// the shape of the classpath it runs on, not only the shape of the shipped one.
|
||||
testImplementation(project(':adapter:outbound:persistence-mongo')) {
|
||||
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-data-mongodb-reactive'
|
||||
exclude group: 'org.mongodb', module: 'mongodb-driver-reactivestreams'
|
||||
}
|
||||
testImplementation project(':adapter:outbound:httpclient')
|
||||
testImplementation project(':adapter:inbound:graphql')
|
||||
// Shipped so an operator can enable it with one environment variable. An adapter that is
|
||||
// absent is not the same contract as one that is off: absence cannot be reversed at deploy time,
|
||||
// and it hides every gating defect, because code that is not there holds no beans whatever its
|
||||
// conditions say.
|
||||
implementation(project(':adapter:outbound:persistence-mongo')) {
|
||||
//
|
||||
// runtimeOnly, not implementation: no source under src/main names a type from this leaf, so the
|
||||
// composition root has no compile-time business with it, and saying so in the build makes that
|
||||
// a rule the compiler keeps rather than a habit. It also states which capabilities a fork can
|
||||
// drop from its artifact by deleting one line — the step the composition-ownership work has to
|
||||
// reach for the capabilities bootstrap still imports.
|
||||
runtimeOnly(project(':adapter:outbound:persistence-mongo')) {
|
||||
// Reactive Mongo is not in the shipped Stable scope: there is no reactive port, no resource
|
||||
// budget for a second client, and no qualification. Leaving the starter on the runtime
|
||||
// classpath would let Boot's reactive auto-configuration build a second client and pool from
|
||||
@@ -118,14 +149,15 @@ dependencies {
|
||||
implementation project(':adapter:outbound:cache-redis')
|
||||
implementation project(':adapter:outbound:redis-runtime')
|
||||
implementation project(':adapter:outbound:notification')
|
||||
implementation project(':adapter:outbound:fileserver')
|
||||
implementation project(':adapter:outbound:httpclient')
|
||||
// runtimeOnly for the same reason as persistence-mongo: no main source names an HTTP client type.
|
||||
runtimeOnly project(':adapter:outbound:httpclient')
|
||||
implementation project(':adapter:outbound:identifier')
|
||||
// Shipped so an operator can enable the transport with one environment variable. The platform
|
||||
// configuration carried no master condition at all, so this edge is only safe now that
|
||||
// GraphQlRootAutoConfiguration owns the switch and the import filter holds Spring GraphQL's own
|
||||
// auto-configurations back — without both, adding the jar would publish /graphql.
|
||||
implementation project(':adapter:inbound:graphql')
|
||||
// runtimeOnly: the switch and the import filter are the leaf's, and no main source names either.
|
||||
runtimeOnly project(':adapter:inbound:graphql')
|
||||
implementation project(':adapter:inbound:web')
|
||||
implementation project(':shared-contract')
|
||||
implementation 'org.springframework.boot:spring-boot-starter'
|
||||
@@ -319,3 +351,40 @@ tasks.register('bootRunH2', org.springframework.boot.gradle.tasks.run.BootRun) {
|
||||
// The environment configuration contract. Owned here because the question it answers — what must a
|
||||
// deployment of this application be given — is the composition root's, and reached through
|
||||
// `configContractCheck` rather than through every leaf's `check`.
|
||||
|
||||
// The Build Composition contract.
|
||||
//
|
||||
// Three questions the repository kept answering with one answer:
|
||||
//
|
||||
// Does this repository support Fileserver? -> the capability catalog, modules.json
|
||||
// Does this build ship Fileserver? -> here
|
||||
// Is the shipped Fileserver switched on? -> app.fileserver-platform.enabled
|
||||
//
|
||||
// Only the second one is a dependency question, and until now nothing asked it. Lowering a
|
||||
// capability to `runtimeOnly` answered a different question — it left the compile classpath and
|
||||
// stayed in the jar — so "we do not ship it" and "we ship it switched off" were the same build.
|
||||
// They are not the same artifact, and they are not the same risk: code that is absent holds no
|
||||
// beans, opens no ports and carries no CVE, whatever its conditions say.
|
||||
//
|
||||
// Declared as an absence on `runtimeClasspath` rather than as a test, because `runtimeClasspath` is
|
||||
// what `bootJar` packages. `ca.dependency-policy` already resolves a named configuration and fails
|
||||
// on a forbidden coordinate, so this needs no verifier of its own — which is the point: a build
|
||||
// composition rule that required new build tooling would be trading one coupling for another.
|
||||
//
|
||||
// A fork that wants the capability adds the project dependency back and deletes the matching line
|
||||
// here, the same two-line act that object storage already documents in docs/capability-status.md.
|
||||
dependencyPolicy {
|
||||
absent 'dev.caskeleton:fileserver',
|
||||
'Fileserver is an optional capability. The minimal composition does not ship it; a deployment that wants it selects :composition:fileserver-platform.'
|
||||
absent 'dev.caskeleton:application-fileserver',
|
||||
'Fileserver use cases ship with the capability that drives them, not with every application.'
|
||||
// The capability is four modules, so the contract names four. Listing only the ones that were
|
||||
// easy to remove would have left the rule true and the artifact unchanged: `application-fileserver`
|
||||
// stayed on the classpath through `adapter:inbound:web`, `adapter:outbound:persistence-jpa` and
|
||||
// `adapter:outbound:identifier` long after the composition root stopped naming Fileserver, because
|
||||
// the capability's code was inside those three leaves rather than merely wired by bootstrap.
|
||||
absent 'dev.caskeleton:web-fileserver',
|
||||
'The Fileserver HTTP surface ships with the capability, not with every application that has an HTTP API.'
|
||||
absent 'dev.caskeleton:persistence-fileserver',
|
||||
'The Fileserver schema and stores ship with the capability, not with every application that has a database.'
|
||||
}
|
||||
|
||||
+6
-1
@@ -102,7 +102,12 @@ class ArchRuleDiscoveryContractTest {
|
||||
"DOMAIN_EVENTS_ARE_TRANSPORT_FREE",
|
||||
"DOMAIN_HAS_NO_LOGGER",
|
||||
"DOMAIN_IS_PURE",
|
||||
"FILESERVER_CONFIGURATIONS_DECLARE_AT_MOST_EIGHT_BEANS",
|
||||
// FILESERVER_CONFIGURATIONS_DECLARE_AT_MOST_EIGHT_BEANS is deliberately not here any
|
||||
// more. BOOT-007 governs the Fileserver composition, and that composition is no longer
|
||||
// app-bootstrap's: it is :composition:fileserver-platform, which owns the rule now and
|
||||
// runs it without allowEmptyShould. Kept in this suite it would have analysed an empty
|
||||
// package and passed for having nothing to look at — the removal is recorded here
|
||||
// rather than made by deleting a field, which is what BOOT-012 asks.
|
||||
"EXTERNAL_OUTBOUND_CALLS_REQUIRE_EXTERNAL_OUTBOUND_ALLOWED_CAPABILITY",
|
||||
"IDENTIFIER_ADAPTER_DOES_NOT_DEPEND_ON_OTHER_ADAPTERS_OR_BOOTSTRAP",
|
||||
"INBOUND_ADAPTERS_DEPEND_ON_PORTS_NOT_APPLICATION_SERVICES",
|
||||
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.architecture;
|
||||
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
|
||||
import com.tngtech.archunit.core.domain.JavaClass;
|
||||
import com.tngtech.archunit.core.domain.JavaMethod;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchCondition;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
import com.tngtech.archunit.lang.ConditionEvents;
|
||||
import com.tngtech.archunit.lang.SimpleConditionEvent;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
/** BOOT-007: Fileserver composition stays split by concern instead of regrowing god configs. */
|
||||
@AnalyzeClasses(
|
||||
packages = "dev.caskeleton.bootstrap.autoconfigure.fileserver",
|
||||
importOptions = ProductionClassImportOption.class)
|
||||
class FileserverCompositionArchitectureTest {
|
||||
|
||||
@ArchTest
|
||||
static final ArchRule FILESERVER_CONFIGURATIONS_DECLARE_AT_MOST_EIGHT_BEANS =
|
||||
classes()
|
||||
.that()
|
||||
.resideInAPackage("dev.caskeleton.bootstrap.autoconfigure.fileserver")
|
||||
.should(declareAtMostEightBeanMethods())
|
||||
.as(
|
||||
"BOOT-007: one Fileserver composition class declares at most eight @Bean methods; "
|
||||
+ "larger or mixed port families split into package-private concern configs")
|
||||
.allowEmptyShould(true);
|
||||
|
||||
private static ArchCondition<JavaClass> declareAtMostEightBeanMethods() {
|
||||
return new ArchCondition<>("declare at most eight @Bean methods") {
|
||||
@Override
|
||||
public void check(JavaClass item, ConditionEvents events) {
|
||||
long count =
|
||||
item.getMethods().stream()
|
||||
.filter(FileserverCompositionArchitectureTest::isBeanMethod)
|
||||
.count();
|
||||
if (count > 8) {
|
||||
events.add(
|
||||
SimpleConditionEvent.violated(
|
||||
item, item.getFullName() + " declares " + count + " @Bean methods"));
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static boolean isBeanMethod(JavaMethod method) {
|
||||
return method.isAnnotatedWith(Bean.class);
|
||||
}
|
||||
}
|
||||
+2
-1
@@ -67,7 +67,8 @@ class ForbiddenApiArchitectureTest {
|
||||
// tenancy.shared package of its own and only began tripping this rule when that leaf
|
||||
// joined the composition root's analysis scope.
|
||||
"dev.caskeleton.adapter.outbound.mongo.advanced.tenancy.shared",
|
||||
// The registered master switches and their strict parse. Operational rather than domain:
|
||||
// The registered master switches and their strict parse. Operational rather than
|
||||
// domain:
|
||||
// it names environment keys and rejects unreadable values, and it lives here because
|
||||
// the environment post-processor needs it before a Spring context exists, so it must
|
||||
// not depend on Spring.
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
import com.tngtech.archunit.junit.AnalyzeClasses;
|
||||
import com.tngtech.archunit.junit.ArchTest;
|
||||
import com.tngtech.archunit.lang.ArchRule;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/** BOOT-002: Spring active-profile extraction has one composition-root owner. */
|
||||
|
||||
+8
-1
@@ -62,8 +62,15 @@ class StartupFailureContractArchitectureTest {
|
||||
* concern (BOOT-007) and the key digest moved to a type of its own. The rule caught the move,
|
||||
* which is the behaviour to want from it: an allowlist that silently followed a class around
|
||||
* would stop being a statement about which code is exempt.
|
||||
*
|
||||
* <p>It has moved again, out of the composition root entirely: the Redis semantic wiring is owned
|
||||
* by {@code adapter:outbound:cache-redis} now, and fails closed through the support leaf's {@code
|
||||
* CapabilityStartupValidationException} rather than through {@code StartupFailures}. The entry is
|
||||
* kept, pointing at the new name, because the rule scans every class it can see and an allowlist
|
||||
* that quietly emptied itself would be the same silence in the other direction.
|
||||
*/
|
||||
private static final String REDIS_KEYS = "dev.caskeleton.bootstrap.autoconfigure.redis.RedisKeys";
|
||||
private static final String REDIS_KEYS =
|
||||
"dev.caskeleton.adapter.outbound.cache.redis.capability.RedisKeys";
|
||||
|
||||
/**
|
||||
* {@code StartupFailures} itself — it constructs the typed exceptions this rule exists to
|
||||
|
||||
+1
-1
@@ -8,9 +8,9 @@ import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapp
|
||||
import dev.caskeleton.adapter.outbound.persistence.transaction.SpringTransactionPort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import dev.caskeleton.bootstrap.async.AsyncContextTaskDecorator;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.fileserver.FileserverPlatformAutoConfiguration;
|
||||
import dev.caskeleton.bootstrap.concurrency.DomainContextConfig;
|
||||
import dev.caskeleton.bootstrap.integration.PostgreSqlTestContainer;
|
||||
import dev.caskeleton.composition.fileserver.FileserverPlatformAutoConfiguration;
|
||||
import dev.caskeleton.shared.concurrency.DomainContextPropagator;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
|
||||
+12
-2
@@ -58,13 +58,17 @@ import org.springframework.context.annotation.FilterType;
|
||||
@ConfigurationPropertiesScan(
|
||||
basePackages = {
|
||||
"dev.caskeleton.bootstrap.async",
|
||||
"dev.caskeleton.bootstrap.autoconfigure.fileserver",
|
||||
"dev.caskeleton.bootstrap.concurrency",
|
||||
"dev.caskeleton.bootstrap.runtime",
|
||||
"dev.caskeleton.bootstrap.security",
|
||||
"dev.caskeleton.bootstrap.settings",
|
||||
"dev.caskeleton.adapter.inbound.web",
|
||||
"dev.caskeleton.adapter.outbound.cache.redis",
|
||||
// Not the whole redis tree. `...cache.redis.capability` holds RedisCapabilitySettings, which
|
||||
// the capability's own gated root binds with @EnableConfigurationProperties; scanning it here
|
||||
// bound the settings while every switch was off, which is the one thing the off-state
|
||||
// contract forbids — and the shipped-composition test caught it by name the moment the
|
||||
// capability moved into this package.
|
||||
"dev.caskeleton.adapter.outbound.cache.redis.sdk",
|
||||
"dev.caskeleton.adapter.outbound.objectstorage",
|
||||
"dev.caskeleton.application",
|
||||
"dev.caskeleton.domain",
|
||||
@@ -93,6 +97,12 @@ public class CaSkeletonApplication {
|
||||
"dev\\.caskeleton\\.bootstrap\\.autoconfigure\\..*"
|
||||
+ "|dev\\.caskeleton\\.bootstrap\\.notification\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.inbound\\.web\\.fileserver\\.admin\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.outbound\\.fileserver\\.platform\\.autoconfigure\\..*"
|
||||
// Capability composition modules. They are never in `basePackages`, so the scan
|
||||
// cannot reach them anyway — named here because the parity test asks the regex,
|
||||
// not the scan, whether an imported child could ever be found twice.
|
||||
+ "|dev\\.caskeleton\\.composition\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.outbound\\.cache\\.redis\\.capability\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.outbound\\.httpclient\\.autoconfigure\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.outbound\\.mongo\\..*"
|
||||
+ "|dev\\.caskeleton\\.adapter\\.outbound\\.messaging\\..*"
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.caskeleton.bootstrap.activation;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.jpa.DataSourceRequirement;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.shared.activation.MasterSwitch;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
+13
-4
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.activation;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupPhase;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext;
|
||||
import dev.caskeleton.shared.activation.MasterSwitch;
|
||||
@@ -60,11 +60,20 @@ public final class CapabilityDependencyValidator {
|
||||
+ MasterSwitch.PERSISTENCE_JPA.property()
|
||||
+ "=true or turn the outbox off.");
|
||||
}
|
||||
if (outbox && !messaging) {
|
||||
// Only a *relaying* outbox needs somewhere to publish. An outbox with the relay off writes rows
|
||||
// inside the application's own transactions and publishes nothing, which is the configuration
|
||||
// an
|
||||
// operator uses to park events until a transport exists — the very state
|
||||
// OutboxRelayBrokerRequirementValidator documents as one of the two coherent ones. Requiring
|
||||
// messaging for the capability rather than for the relay contradicted that, and in a
|
||||
// broker-neutral artifact it made the outbox unreachable: messaging on demands a broker, and a
|
||||
// broker demands a starter the default composition deliberately does not ship.
|
||||
if (outbox && relay && !messaging) {
|
||||
violations.reject(
|
||||
"ca-skeleton.outbox.enabled=true needs somewhere to publish; set "
|
||||
"ca-skeleton.outbox.relay-enabled=true needs somewhere to publish; set "
|
||||
+ MasterSwitch.MESSAGING.property()
|
||||
+ "=true or turn the outbox off.");
|
||||
+ "=true, or set ca-skeleton.outbox.relay-enabled=false to keep writing rows without"
|
||||
+ " a transport.");
|
||||
}
|
||||
if (relay && !outbox) {
|
||||
violations.reject(
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.activation;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupOrder;
|
||||
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
|
||||
@@ -18,9 +18,9 @@ import org.springframework.core.env.ConfigurableEnvironment;
|
||||
* meant an in-memory database that loses every write on restart. The failure had no symptom until
|
||||
* the data was already gone.
|
||||
*
|
||||
* <p>Feature selection is not expressed here. That is what the registered master switches are for, and a
|
||||
* supplementary profile used as a feature flag is how a profile list stops being a statement about
|
||||
* where the application is running.
|
||||
* <p>Feature selection is not expressed here. That is what the registered master switches are for,
|
||||
* and a supplementary profile used as a feature flag is how a profile list stops being a statement
|
||||
* about where the application is running.
|
||||
*
|
||||
* <p>Scoped to the deployable artifact, which means contexts whose main class is {@link
|
||||
* dev.caskeleton.bootstrap.CaSkeletonApplication}. Slice tests boot minimal applications with no
|
||||
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.admin.FileserverAdminController;
|
||||
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration;
|
||||
import org.springframework.boot.actuate.autoconfigure.web.ManagementContextType;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* Serves the management plane from the management context, not the public one.
|
||||
*
|
||||
* <p>{@code /internal/fileserver/**} was a set of ordinary controller routes on the application
|
||||
* connector. A role check kept unauthorised callers out, but the surface was still reachable by
|
||||
* anything that could open a socket to the public port — which means every misconfigured ingress,
|
||||
* every port-forward, and every future route added to this controller without its own guard.
|
||||
*
|
||||
* <p>Registered as a management-context configuration instead, so when a deployment gives the
|
||||
* management server its own port the admin routes move with it and never appear on the public
|
||||
* listener at all. Boot falls back to the same context when the ports are equal, which is why the
|
||||
* role gate contributed by {@link FileserverAdminPlaneConfiguration} stays: the two guards cover
|
||||
* different deployments rather than duplicating each other.
|
||||
*
|
||||
* <p>The management context is a child of the application context, so the admin service, the policy
|
||||
* and the audit port are all inherited rather than rebuilt.
|
||||
*/
|
||||
@ManagementContextConfiguration(value = ManagementContextType.ANY, proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform",
|
||||
name = {"enabled", "admin.enabled"},
|
||||
havingValue = "true")
|
||||
@Import(FileserverAdminController.class)
|
||||
public class FileserverAdminManagementContextConfiguration {}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.auth.RestrictedPathRule;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Puts the management plane behind the admin role at the transport, not only in application policy.
|
||||
*
|
||||
* <p>The base chain ends in {@code anyRequest().authenticated()}. Under it, {@code
|
||||
* /internal/fileserver/**} was reachable by every authenticated caller, and the only thing standing
|
||||
* between an ordinary user and a force-delete was an authorization check inside the service. That
|
||||
* check is real, but it runs after the request has been accepted, parsed and dispatched — and any
|
||||
* future admin endpoint that forgets to call it is open.
|
||||
*
|
||||
* <p>The roles come from the same setting the application policy uses, so the two cannot describe
|
||||
* different administrators.
|
||||
*
|
||||
* <p>This is the in-process half of the isolation. Serving the management plane on a separate port
|
||||
* or network remains an operational requirement — see the module README — because a shared port
|
||||
* still exposes the surface to anything that can reach the public listener.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.admin",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class FileserverAdminPlaneConfiguration {
|
||||
|
||||
/** Every route the admin controller owns lives under this prefix. */
|
||||
static final String ADMIN_PATH_PATTERN = "/internal/fileserver/**";
|
||||
|
||||
@Bean
|
||||
RestrictedPathRule fileserverAdminPathRule(FileserverPlatformSettings settings) {
|
||||
return new RestrictedPathRule(ADMIN_PATH_PATTERN, settings.security().adminRoles());
|
||||
}
|
||||
}
|
||||
-53
@@ -1,53 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import java.time.Duration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.SchedulingConfigurer;
|
||||
|
||||
/**
|
||||
* Runs reclamation in the background when a deployment opts in.
|
||||
*
|
||||
* <p>Separate from the cleanup service itself, which the admin plane also drives on demand. The
|
||||
* service decides what may be deleted; this decides only whether anything drives it unattended, and
|
||||
* that is a deployment's call — a node without the worker still queues cleanup items, and another
|
||||
* node or an operator reclaims them.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableScheduling
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.cleanup",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
public class FileserverCleanupConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverCleanupWorker fileserverCleanupWorker(
|
||||
CleanupService cleanupService, FileserverPlatformSettings settings) {
|
||||
return new FileserverCleanupWorker(
|
||||
cleanupService, settings.cleanup().maxItems(), settings.cleanup().maxBytes().toBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the batch schedule from the bound interval.
|
||||
*
|
||||
* <p>Programmatic rather than a {@code @Scheduled} placeholder on the worker: a placeholder
|
||||
* carries its own default, so the interval would have two owners with two defaults and no way to
|
||||
* tell from the outside which one a running node used.
|
||||
*
|
||||
* <p>Fixed <em>delay</em>, not fixed rate. A batch that runs long because storage is slow must
|
||||
* not have the next one queued behind it; under a fixed rate a degraded volume turns into an
|
||||
* accumulating backlog of invocations.
|
||||
*/
|
||||
@Bean
|
||||
SchedulingConfigurer fileserverCleanupSchedule(
|
||||
FileserverCleanupWorker worker, FileserverPlatformSettings settings) {
|
||||
Duration interval = settings.cleanup().interval();
|
||||
return registrar -> registrar.addFixedDelayTask(worker::runBatch, interval);
|
||||
}
|
||||
}
|
||||
-76
@@ -1,76 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static net.logstash.logback.argument.StructuredArguments.kv;
|
||||
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Drives the bounded cleanup batch on a fixed delay.
|
||||
*
|
||||
* <p>Fixed <em>delay</em>, not fixed rate: a batch that runs long because storage is slow must not
|
||||
* have the next one queued behind it. Under fixed rate a degraded volume would accumulate pending
|
||||
* invocations and turn a slow filesystem into a thread-pool outage.
|
||||
*
|
||||
* <p>The batch bounds itself by item count and by bytes, so one invocation cannot monopolise the
|
||||
* scheduler however much work is queued. Whatever it does not reach stays queued for the next run.
|
||||
*
|
||||
* <p>A failing batch is logged and swallowed. An escaping exception cancels a scheduled task
|
||||
* permanently, which would silently stop all reclamation after one bad object — the failure mode
|
||||
* this worker exists to prevent.
|
||||
*
|
||||
* <p>The schedule itself is registered by {@link FileserverCleanupConfiguration} from the bound
|
||||
* interval rather than declared here with a property placeholder. Two declarations of the same
|
||||
* interval — one typed and validated, one a raw string with its own default — is one declaration
|
||||
* too many: they drift, and the one that wins is whichever the scheduler happened to read.
|
||||
*/
|
||||
public class FileserverCleanupWorker {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FileserverCleanupWorker.class);
|
||||
|
||||
private final CleanupService cleanupService;
|
||||
private final int maxItems;
|
||||
private final long maxBytes;
|
||||
|
||||
public FileserverCleanupWorker(CleanupService cleanupService, int maxItems, long maxBytes) {
|
||||
if (maxItems < 1 || maxBytes < 1) {
|
||||
throw new IllegalArgumentException("cleanup batch bounds must be positive");
|
||||
}
|
||||
this.cleanupService = cleanupService;
|
||||
this.maxItems = maxItems;
|
||||
this.maxBytes = maxBytes;
|
||||
}
|
||||
|
||||
public void runBatch() {
|
||||
try {
|
||||
CleanupBatchResult result = cleanupService.runBatch(maxItems, maxBytes);
|
||||
if (result.deleted() > 0 || result.failed() > 0) {
|
||||
LOG.info(
|
||||
"fileserver.cleanup deleted={} skippedActiveLease={} skippedStateChanged={} "
|
||||
+ "failed={} reclaimedBytes={}",
|
||||
result.deleted(),
|
||||
result.skippedActiveLease(),
|
||||
result.skippedStateChanged(),
|
||||
result.failed(),
|
||||
result.reclaimedBytes(),
|
||||
kv("capability", "fileserver"),
|
||||
kv("operation", "cleanup"),
|
||||
kv("cleanup.deleted", result.deleted()),
|
||||
kv("cleanup.skipped_active_lease", result.skippedActiveLease()),
|
||||
kv("cleanup.skipped_state_changed", result.skippedStateChanged()),
|
||||
kv("cleanup.failed", result.failed()),
|
||||
kv("cleanup.reclaimed_bytes", result.reclaimedBytes()));
|
||||
}
|
||||
} catch (RuntimeException failure) {
|
||||
LOG.warn(
|
||||
"fileserver.cleanup batch failed; the next run retries the same queue",
|
||||
kv("capability", "fileserver"),
|
||||
kv("operation", "cleanup"),
|
||||
kv("warning.kind", "scheduled-task-failed"),
|
||||
kv("retry.disposition", "next-run"),
|
||||
failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.TransferExecutorProperties;
|
||||
import dev.caskeleton.application.fileserver.api.StorageNamespace;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadPolicy;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverCorePolicyConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverWebProperties fileserverWebProperties(FileserverPlatformSettings properties) {
|
||||
return new FileserverWebProperties(
|
||||
StorageNamespace.of(properties.defaultNamespace()),
|
||||
properties.upload().ttl(),
|
||||
properties.upload().maxParts(),
|
||||
properties.upload().requireContentLength());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
TransferExecutorProperties fileserverTransferExecutorProperties(
|
||||
FileserverPlatformSettings properties) {
|
||||
return new TransferExecutorProperties(
|
||||
properties.transfer().coreSize(),
|
||||
properties.transfer().maxSize(),
|
||||
properties.transfer().queueCapacity(),
|
||||
properties.transfer().awaitSeconds());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadPolicy fileserverUploadPolicy(FileserverPlatformSettings properties) {
|
||||
return new UploadPolicy(
|
||||
properties.upload().maxFileSize().toBytes(),
|
||||
properties.upload().initialReservation().toBytes(),
|
||||
properties.upload().reservationTtl(),
|
||||
properties.upload().leaseDuration());
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueue;
|
||||
import dev.caskeleton.application.fileserver.download.DefaultDownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyDownloadGateway;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.CopyContentGateway;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.DefaultFileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.FileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadIdentifierFactory;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverDownloadLifecycleConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
DownloadApplicationService fileserverDownloadService(
|
||||
FileMetadataStore metadataStore,
|
||||
DownloadContentGateway contentGateway,
|
||||
FileAccessPolicy accessPolicy,
|
||||
ZeroCopyDownloadGateway zeroCopyGateway,
|
||||
ObjectProvider<FileserverMetricsPort> metrics) {
|
||||
return new DefaultDownloadApplicationService(
|
||||
metadataStore,
|
||||
contentGateway,
|
||||
accessPolicy,
|
||||
Optional.of(zeroCopyGateway),
|
||||
FileserverMetricsSupport.metricsOrNoop(metrics));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileLifecycleService fileserverLifecycleService(
|
||||
FileMetadataStore metadataStore,
|
||||
CopyContentGateway copyGateway,
|
||||
FileAccessPolicy accessPolicy,
|
||||
OriginalFilenamePolicy filenamePolicy,
|
||||
CleanupQueue cleanupQueue,
|
||||
UploadIdentifierFactory identifierFactory,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFileLifecycleService(
|
||||
metadataStore,
|
||||
copyGateway,
|
||||
accessPolicy,
|
||||
filenamePolicy,
|
||||
cleanupQueue,
|
||||
identifierFactory,
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
}
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
|
||||
/**
|
||||
* True when something in the graph will actually ask for a keyed fingerprint.
|
||||
*
|
||||
* <p>Two independent features consume one: telemetry, which pseudonymises file identifiers, and the
|
||||
* management-plane audit trail, which pseudonymises operators. Tying the bean to only one of them
|
||||
* meant the other silently fell back to an unkeyed hash, and requiring the key when neither is on
|
||||
* would demand a secret from deployments that have no use for it.
|
||||
*/
|
||||
class FileserverFingerprintConsumerCondition extends AnyNestedCondition {
|
||||
|
||||
FileserverFingerprintConsumerCondition() {
|
||||
super(ConfigurationPhase.REGISTER_BEAN);
|
||||
}
|
||||
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.observability",
|
||||
name = "metrics-enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
static class MetricsEnabled {}
|
||||
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.admin",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
static class AdminPlaneEnabled {}
|
||||
}
|
||||
-72
@@ -1,72 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.DefaultHttpRangeResolver;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpContentDispositionFactory;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadPlanner;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadPolicy;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangePolicy;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpRangeResolver;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcConditionalRequestFactory;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.MvcDownloadResponseWriter;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.ZeroCopyEligibility;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** HTTP-only download policy and rendering helpers. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverHttpDownloadConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
MvcConditionalRequestFactory fileserverConditionalRequestFactory() {
|
||||
return new MvcConditionalRequestFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
HttpRangeResolver fileserverHttpRangeResolver() {
|
||||
return new DefaultHttpRangeResolver();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
HttpContentDispositionFactory fileserverHttpContentDispositionFactory() {
|
||||
return new HttpContentDispositionFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
HttpDownloadPolicy fileserverHttpDownloadPolicy(FileserverPlatformSettings properties) {
|
||||
HttpRangePolicy rangePolicy =
|
||||
properties.download().maxRanges() <= 1
|
||||
? HttpRangePolicy.single(properties.download().maxRangeBytes().toBytes())
|
||||
: HttpRangePolicy.multi(
|
||||
properties.download().maxRanges(), properties.download().maxRangeBytes().toBytes());
|
||||
return new HttpDownloadPolicy(
|
||||
rangePolicy, properties.download().cacheControl(), properties.download().inlineAllowed());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
HttpDownloadPlanner fileserverHttpDownloadPlanner(
|
||||
HttpRangeResolver rangeResolver,
|
||||
HttpContentDispositionFactory dispositionFactory,
|
||||
HttpDownloadPolicy policy) {
|
||||
return new HttpDownloadPlanner(rangeResolver, dispositionFactory, policy);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
MvcDownloadResponseWriter fileserverDownloadResponseWriter() {
|
||||
return new MvcDownloadResponseWriter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
ZeroCopyEligibility fileserverZeroCopyEligibility(FileserverPlatformSettings properties) {
|
||||
return new ZeroCopyEligibility(
|
||||
properties.download().zeroCopyEnabled(),
|
||||
properties.download().zeroCopyMinimumBytes().toBytes());
|
||||
}
|
||||
}
|
||||
-111
@@ -1,111 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageCapabilityProbe;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProperties;
|
||||
import dev.caskeleton.adapter.outbound.persistence.fileserver.FileserverSchemaActivation;
|
||||
import dev.caskeleton.application.fileserver.api.content.PublishMode;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.core.JdbcOperations;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverLocalStorageCoreConfiguration {
|
||||
|
||||
/**
|
||||
* The three storage invariants are pinned, not configured.
|
||||
*
|
||||
* <p>Staging and content on one file store, a refusal to follow symbolic links, and a force
|
||||
* before publish are what make an atomic publish atomic and a namespace a boundary. A deployment
|
||||
* that could switch them off would be running a different capability under the same name and the
|
||||
* same tests, so they are constants here rather than settings.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
LocalStorageProperties fileserverStorageProperties(FileserverPlatformSettings settings) {
|
||||
FileserverPlatformSettings.Storage storage = settings.storage();
|
||||
requireStorageRootIsIsolated(storage);
|
||||
return new LocalStorageProperties(
|
||||
storage.root(),
|
||||
publishMode(storage.publishMode()),
|
||||
true,
|
||||
true,
|
||||
(int) storage.bufferSize().toBytes(),
|
||||
settings.upload().maxFileSize().toBytes(),
|
||||
true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to start until the Fileserver schema stream is applied and promoted.
|
||||
*
|
||||
* <p>Paired with the storage probe below: one proves the volume can hold the bytes, the other
|
||||
* proves the database sanctions the records. A capability that starts with either unproven fails
|
||||
* on a user's first upload instead of on the deployment that caused it.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnBean(JdbcOperations.class)
|
||||
FileserverSchemaActivation fileserverSchemaActivation(JdbcOperations jdbc) {
|
||||
FileserverSchemaActivation activation = new FileserverSchemaActivation(jdbc);
|
||||
activation.requireActive();
|
||||
return activation;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
LocalStorageProbeResult fileserverStorageProbeResult(LocalStorageProperties properties) {
|
||||
LocalStorageProbeResult result = new LocalStorageCapabilityProbe(properties).run();
|
||||
if (!result.mandatoryChecksPassed()) {
|
||||
throw StartupFailures.envValidation(
|
||||
"fileserver storage root failed a mandatory capability probe: "
|
||||
+ result.failures()
|
||||
+ "; the capability refuses to start rather than publish files it cannot place "
|
||||
+ "atomically");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
LocalBlockingContentStore fileserverContentStore(
|
||||
LocalStorageProperties properties, LocalStorageProbeResult probeResult) {
|
||||
return new LocalBlockingContentStore(properties, probeResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a storage root that overlaps something the process already serves or reads.
|
||||
*
|
||||
* <p>A root under a web root turns every upload into a published file; a root under a
|
||||
* configuration directory turns one into a configuration change. Both are checked here because
|
||||
* the path is only known once, at binding time.
|
||||
*/
|
||||
private static void requireStorageRootIsIsolated(FileserverPlatformSettings.Storage storage) {
|
||||
Path root = storage.root().toAbsolutePath().normalize();
|
||||
for (Path forbidden : storage.forbiddenRootAncestors()) {
|
||||
Path ancestor = forbidden.toAbsolutePath().normalize();
|
||||
if (root.startsWith(ancestor)) {
|
||||
throw StartupFailures.envValidation(
|
||||
"fileserver storage root must not live under a configured forbidden ancestor");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static PublishMode publishMode(String configured) {
|
||||
String canonical = configured.trim().toUpperCase(Locale.ROOT).replace('-', '_');
|
||||
try {
|
||||
return PublishMode.valueOf(canonical);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw StartupFailures.envValidation(
|
||||
FileserverPlatformSettings.PREFIX
|
||||
+ ".storage.publish-mode must be one of atomic-move-required, "
|
||||
+ "atomic-move-preferred, metadata-pointer",
|
||||
unknown);
|
||||
}
|
||||
}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.application.fileserver.admin.AdminAuditPort;
|
||||
import dev.caskeleton.application.fileserver.admin.DefaultFileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.FileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthPort;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionStore;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupContentGateway;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueue;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import dev.caskeleton.application.fileserver.cleanup.DefaultCleanupService;
|
||||
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimGateway;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint;
|
||||
import dev.caskeleton.application.fileserver.recovery.DefaultFileReconciliationService;
|
||||
import dev.caskeleton.application.fileserver.recovery.FileReconciliationService;
|
||||
import dev.caskeleton.application.fileserver.recovery.ReconciliationContentProbe;
|
||||
import dev.caskeleton.application.fileserver.recovery.RecoveryQueue;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverMaintenanceServiceConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
CleanupService fileserverCleanupService(
|
||||
CleanupQueue queue,
|
||||
CleanupContentGateway contentGateway,
|
||||
FileMetadataStore metadataStore,
|
||||
UploadSessionStore sessionStore,
|
||||
QuotaReclaimGateway quotaGateway,
|
||||
FileserverPlatformSettings settings,
|
||||
ObjectProvider<FileserverMetricsPort> metrics,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultCleanupService(
|
||||
queue,
|
||||
contentGateway,
|
||||
metadataStore,
|
||||
sessionStore,
|
||||
quotaGateway,
|
||||
settings.cleanup().retryBackoff(),
|
||||
FileserverMetricsSupport.metricsOrNoop(metrics),
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileReconciliationService fileserverReconciliationService(
|
||||
FileMetadataStore metadataStore,
|
||||
ReconciliationContentProbe contentProbe,
|
||||
RecoveryQueue recoveryQueue,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFileReconciliationService(
|
||||
metadataStore, contentProbe, recoveryQueue, transactions, clock);
|
||||
}
|
||||
|
||||
/**
|
||||
* The management plane, gated on its own switch.
|
||||
*
|
||||
* <p>Admin is a separate decision from the data plane: a deployment that serves files does not
|
||||
* automatically want an endpoint that can force-delete them.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = "app.fileserver-platform.admin",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
FileserverAdminService fileserverAdminService(
|
||||
StorageHealthPort healthPort,
|
||||
OrphanScanPort orphanScanPort,
|
||||
FileMetadataStore metadataStore,
|
||||
UploadSessionStore sessionStore,
|
||||
CleanupQueue cleanupQueue,
|
||||
CleanupService cleanupService,
|
||||
FileAccessPolicy accessPolicy,
|
||||
AdminAuditPort auditPort,
|
||||
SafeFileFingerprint fingerprint,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFileserverAdminService(
|
||||
healthPort,
|
||||
orphanScanPort,
|
||||
metadataStore,
|
||||
sessionStore,
|
||||
cleanupQueue,
|
||||
cleanupService,
|
||||
accessPolicy,
|
||||
auditPort,
|
||||
fingerprint,
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
}
|
||||
-22
@@ -1,22 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
|
||||
/** Shared optional-metrics selection for Fileserver application-service assembly. */
|
||||
final class FileserverMetricsSupport {
|
||||
|
||||
private FileserverMetricsSupport() {}
|
||||
|
||||
/**
|
||||
* Instrumentation is optional; the services are not.
|
||||
*
|
||||
* <p>Metrics can be switched off, and when they are there is no {@code FileserverMetricsPort}
|
||||
* bean. Injecting it directly would make every service depend on telemetry being enabled, so the
|
||||
* no-op stands in — which is also what stops the ports from being dead code the way they were
|
||||
* when nothing called them at all.
|
||||
*/
|
||||
static FileserverMetricsPort metricsOrNoop(ObjectProvider<FileserverMetricsPort> metrics) {
|
||||
return metrics.getIfAvailable(FileserverMetricsPort::noop);
|
||||
}
|
||||
}
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.DefaultNginxInternalUriMapper;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.NginxDelegationProperties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.NginxDownloadStrategy;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.NginxInternalUriMapper;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverNginxConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
NginxDelegationProperties fileserverNginxDelegationProperties(
|
||||
FileserverPlatformSettings properties) {
|
||||
return new NginxDelegationProperties(
|
||||
properties.nginx().enabled(),
|
||||
properties.nginx().internalPrefix(),
|
||||
properties.nginx().objectSuffix(),
|
||||
properties.nginx().minimumSize().toBytes());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
NginxInternalUriMapper fileserverNginxInternalUriMapper(NginxDelegationProperties properties) {
|
||||
return new DefaultNginxInternalUriMapper(properties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
NginxDownloadStrategy fileserverNginxDownloadStrategy(
|
||||
NginxDelegationProperties properties, NginxInternalUriMapper uriMapper) {
|
||||
return new NginxDownloadStrategy(properties, uriMapper);
|
||||
}
|
||||
}
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.observability.MicrometerFileserverMetrics;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Conditional;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverObservabilityConfiguration {
|
||||
|
||||
/**
|
||||
* Telemetry fingerprinting.
|
||||
*
|
||||
* <p>Absent a configured key the capability is not silently downgraded to an unkeyed hash — which
|
||||
* would be reversible for an enumerable identifier space. The key is required, and startup fails
|
||||
* without one — but only when something actually consumes a fingerprint. There are two such
|
||||
* consumers, telemetry and the management-plane audit trail, so the bean exists when either is on
|
||||
* rather than being tied to metrics alone: an audit trail that pseudonymised its actors with an
|
||||
* unkeyed 32-bit hash was the reason this had to be widened.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@Conditional(FileserverFingerprintConsumerCondition.class)
|
||||
SafeFileFingerprint fileserverFingerprint(FileserverPlatformSettings properties) {
|
||||
String key = properties.observability().fingerprintKey();
|
||||
if (key == null || key.isBlank()) {
|
||||
throw StartupFailures.envValidation(
|
||||
FileserverPlatformSettings.PREFIX
|
||||
+ ".observability.fingerprint-key must be configured while metrics are enabled: an "
|
||||
+ "unkeyed digest of an enumerable identifier is reversible");
|
||||
}
|
||||
return new SafeFileFingerprint(key.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX + ".observability",
|
||||
name = "metrics-enabled",
|
||||
havingValue = "true",
|
||||
matchIfMissing = true)
|
||||
FileserverMetricsPort fileserverMetrics(MeterRegistry registry) {
|
||||
return new MicrometerFileserverMetrics(registry);
|
||||
}
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Master-gated Fileserver platform entry point.
|
||||
*
|
||||
* <p>This class owns only activation and strict settings binding. Concern-specific assembly stays
|
||||
* in package-private child configurations reachable exclusively through this gated root.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX,
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
@Import({
|
||||
FileserverCorePolicyConfiguration.class,
|
||||
FileserverWebAssemblyConfiguration.class,
|
||||
FileserverHttpDownloadConfiguration.class,
|
||||
FileserverNginxConfiguration.class,
|
||||
FileserverProtocolConfiguration.class,
|
||||
FileserverObservabilityConfiguration.class,
|
||||
FileserverStorageConfiguration.class,
|
||||
FileserverSecurityConfiguration.class,
|
||||
FileserverServiceConfiguration.class,
|
||||
FileserverCleanupConfiguration.class,
|
||||
FileserverAdminPlaneConfiguration.class,
|
||||
FileserverStartupConfiguration.class
|
||||
})
|
||||
public class FileserverPlatformAutoConfiguration {
|
||||
|
||||
/**
|
||||
* Binds the platform settings once the master switch has already been proven true.
|
||||
*
|
||||
* <p>Binding is deliberately not delegated to {@code @ConfigurationPropertiesScan}: that would
|
||||
* bind — and reject — Fileserver detail settings in deployments that never switched the
|
||||
* capability on.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverPlatformSettings fileserverPlatformSettings(Environment environment) {
|
||||
return FileserverPlatformSettingsBinder.bind(environment);
|
||||
}
|
||||
}
|
||||
-354
@@ -1,354 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
import org.springframework.util.unit.DataSize;
|
||||
|
||||
/**
|
||||
* Bound configuration for the HTTP Fileserver platform.
|
||||
*
|
||||
* <p>Deliberately <em>not</em> annotated {@code @ConfigurationProperties}. A scanned properties
|
||||
* class is registered and bound whether or not the capability is switched on, which would make a
|
||||
* typo in a detail setting fail the startup of a deployment that never wanted the Fileserver at
|
||||
* all. This record is instead bound by {@link FileserverPlatformSettingsBinder} from inside the
|
||||
* master-gated auto-configuration, so "off" means "never bound".
|
||||
*
|
||||
* <p>Every default here is the conservative one. The capability is off, the admin plane is off, the
|
||||
* experimental protocol is off, delegation is off, and inline rendering is off. A deployment opts
|
||||
* into each of those explicitly, so no surface appears merely because the dependency is present.
|
||||
*
|
||||
* <p>Validation lives in the compact constructors rather than in bean-validation annotations. It
|
||||
* therefore runs on every construction — including the ones tests make by hand — and can express
|
||||
* the cross-field rules (a core pool larger than its maximum, a soft water mark above the hard one)
|
||||
* that per-field constraints cannot.
|
||||
*
|
||||
* @param enabled master switch for the whole capability
|
||||
* @param instanceId writer-lease owner for this node; must be unique per instance
|
||||
*/
|
||||
public record FileserverPlatformSettings(
|
||||
@DefaultValue("false") boolean enabled,
|
||||
@DefaultValue("local-node") String instanceId,
|
||||
@DefaultValue("default") String defaultNamespace,
|
||||
@DefaultValue Storage storage,
|
||||
@DefaultValue Upload upload,
|
||||
@DefaultValue Download download,
|
||||
@DefaultValue Transfer transfer,
|
||||
@DefaultValue Admin admin,
|
||||
@DefaultValue Tus tus,
|
||||
@DefaultValue Draft12 httpbisDraft12,
|
||||
@DefaultValue Nginx nginx,
|
||||
@DefaultValue Observability observability,
|
||||
@DefaultValue Security security,
|
||||
@DefaultValue Verification verification,
|
||||
@DefaultValue Quota quota,
|
||||
@DefaultValue Cleanup cleanup) {
|
||||
|
||||
/** Configuration prefix; the canonical environment form is {@code APP_FILESERVER_PLATFORM_*}. */
|
||||
public static final String PREFIX = "app.fileserver-platform";
|
||||
|
||||
public FileserverPlatformSettings {
|
||||
requireText(instanceId, "instance-id");
|
||||
requireText(defaultNamespace, "default-namespace");
|
||||
}
|
||||
|
||||
/**
|
||||
* Physical storage settings.
|
||||
*
|
||||
* <p>The provider type, the same-file-store requirement, the symlink refusal, and the force on
|
||||
* publish are not settings. There is exactly one provider, and the other three are the invariants
|
||||
* the whole design rests on — a deployment that could turn them off would be running a different,
|
||||
* unsafe capability under the same name.
|
||||
*/
|
||||
public record Storage(
|
||||
@DefaultValue("/var/lib/backend/files") Path root,
|
||||
@DefaultValue("atomic-move-preferred") String publishMode,
|
||||
@DefaultValue("128KB") DataSize bufferSize,
|
||||
@DefaultValue List<Path> forbiddenRootAncestors) {
|
||||
|
||||
/** Bounds inherited from the storage adapter's own transfer-buffer contract. */
|
||||
private static final long MINIMUM_BUFFER_BYTES = 4L * 1024;
|
||||
|
||||
private static final long MAXIMUM_BUFFER_BYTES = 8L * 1024 * 1024;
|
||||
|
||||
public Storage {
|
||||
requireAbsolute(root);
|
||||
requireText(publishMode, "storage.publish-mode");
|
||||
long bytes = requireSize(bufferSize, "storage.buffer-size");
|
||||
if (bytes < MINIMUM_BUFFER_BYTES || bytes > MAXIMUM_BUFFER_BYTES) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX + ".storage.buffer-size must be between 4KB and 8MB");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Upload policy. */
|
||||
public record Upload(
|
||||
@DefaultValue("100MB") DataSize maxFileSize,
|
||||
@DefaultValue("110MB") DataSize maxRequestSize,
|
||||
@DefaultValue("8MB") DataSize initialReservation,
|
||||
@DefaultValue("16") int maxParts,
|
||||
@DefaultValue("1h") Duration ttl,
|
||||
@DefaultValue("24h") Duration reservationTtl,
|
||||
@DefaultValue("30s") Duration leaseDuration,
|
||||
@DefaultValue("false") boolean requireContentLength) {
|
||||
|
||||
public Upload {
|
||||
long maxFile = requireSize(maxFileSize, "upload.max-file-size");
|
||||
long maxRequest = requireSize(maxRequestSize, "upload.max-request-size");
|
||||
long reservation = requireSize(initialReservation, "upload.initial-reservation");
|
||||
if (maxRequest < maxFile) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX
|
||||
+ ".upload.max-request-size must be at least upload.max-file-size: a request "
|
||||
+ "envelope smaller than the file it carries rejects every maximum-sized upload");
|
||||
}
|
||||
if (reservation > maxFile) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX + ".upload.initial-reservation must not exceed upload.max-file-size");
|
||||
}
|
||||
requirePositive(maxParts, "upload.max-parts");
|
||||
requirePositive(ttl, "upload.ttl");
|
||||
requirePositive(reservationTtl, "upload.reservation-ttl");
|
||||
requirePositive(leaseDuration, "upload.lease-duration");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Download policy.
|
||||
*
|
||||
* @param zeroCopyEnabled whether a large plaintext response may be handed to the kernel instead
|
||||
* of streamed through the JVM; it changes no header and no status, only where the bytes are
|
||||
* copied
|
||||
* @param zeroCopyMinimumBytes below this size the syscall setup costs more than it saves
|
||||
*/
|
||||
public record Download(
|
||||
@DefaultValue("private, no-store") String cacheControl,
|
||||
@DefaultValue("false") boolean inlineAllowed,
|
||||
@DefaultValue("1") int maxRanges,
|
||||
@DefaultValue("100MB") DataSize maxRangeBytes,
|
||||
@DefaultValue("true") boolean zeroCopyEnabled,
|
||||
@DefaultValue("16MB") DataSize zeroCopyMinimumBytes) {
|
||||
|
||||
public Download {
|
||||
requireText(cacheControl, "download.cache-control");
|
||||
requirePositive(maxRanges, "download.max-ranges");
|
||||
requireSize(maxRangeBytes, "download.max-range-bytes");
|
||||
requireSize(zeroCopyMinimumBytes, "download.zero-copy-minimum-bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/** Bounds on the blocking transfer pool. */
|
||||
public record Transfer(
|
||||
@DefaultValue("8") int coreSize,
|
||||
@DefaultValue("32") int maxSize,
|
||||
@DefaultValue("64") int queueCapacity,
|
||||
@DefaultValue("300") int awaitSeconds) {
|
||||
|
||||
public Transfer {
|
||||
requirePositive(coreSize, "transfer.core-size");
|
||||
requirePositive(maxSize, "transfer.max-size");
|
||||
requirePositive(queueCapacity, "transfer.queue-capacity");
|
||||
requirePositive(awaitSeconds, "transfer.await-seconds");
|
||||
if (coreSize > maxSize) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX + ".transfer.core-size must not exceed transfer.max-size");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Management plane; separate switch from the public capability.
|
||||
*
|
||||
* @param orphanMinimumAge how long an unreferenced object must exist before a scan may name it;
|
||||
* publishing content and committing its record are two steps, and anything younger than this
|
||||
* is assumed to be mid-commit rather than abandoned
|
||||
*/
|
||||
public record Admin(
|
||||
@DefaultValue("false") boolean enabled, @DefaultValue("1h") Duration orphanMinimumAge) {
|
||||
|
||||
public Admin {
|
||||
requirePositive(orphanMinimumAge, "admin.orphan-minimum-age");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Authorization.
|
||||
*
|
||||
* <p>{@code access-policy} has no permissive default. Leaving it unset fails startup rather than
|
||||
* granting anything, because a file capability that authorizes by default is worse than one that
|
||||
* refuses to start.
|
||||
*
|
||||
* <p>There is no anonymous-read switch. The servlet chain authenticates every Fileserver route
|
||||
* before any application policy is consulted, so an anonymous-read setting could only ever have
|
||||
* described a permission the transport already refused.
|
||||
*
|
||||
* @param accessPolicy {@code required} to supply your own {@code FileAccessPolicy} bean, {@code
|
||||
* role-based} for the built-in role tiers, or {@code unenforced} for local development only —
|
||||
* the last is refused under a production profile
|
||||
*/
|
||||
public record Security(
|
||||
@DefaultValue("required") String accessPolicy,
|
||||
@DefaultValue("ROLE_FILE_READ") List<String> readRoles,
|
||||
@DefaultValue("ROLE_FILE_WRITE") List<String> writeRoles,
|
||||
@DefaultValue("ROLE_FILE_ADMIN") List<String> adminRoles) {
|
||||
|
||||
public Security {
|
||||
requireText(accessPolicy, "security.access-policy");
|
||||
requireRoles(readRoles, "security.read-roles");
|
||||
requireRoles(writeRoles, "security.write-roles");
|
||||
requireRoles(adminRoles, "security.admin-roles");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Content verification.
|
||||
*
|
||||
* @param requireMediaTypeVerdict when true a file whose type could not be determined is refused
|
||||
* rather than published as an opaque stream
|
||||
* @param inlineSafeProfile when true scriptable content is accepted instead of quarantined; only
|
||||
* safe when downloads are never served inline from a trusted origin
|
||||
*/
|
||||
public record Verification(
|
||||
@DefaultValue("5s") Duration timeout,
|
||||
@DefaultValue("false") boolean requireMediaTypeVerdict,
|
||||
@DefaultValue("false") boolean inlineSafeProfile) {
|
||||
|
||||
public Verification {
|
||||
requirePositive(timeout, "verification.timeout");
|
||||
}
|
||||
}
|
||||
|
||||
/** Transfer admission control and storage high-water marks. */
|
||||
public record Quota(
|
||||
@DefaultValue("16") int instanceUploadPermits,
|
||||
@DefaultValue("4") int scopeUploadPermits,
|
||||
@DefaultValue("64") int directDownloadPermits,
|
||||
@DefaultValue("0.70") double softHighWater,
|
||||
@DefaultValue("0.85") double hardHighWater) {
|
||||
|
||||
public Quota {
|
||||
requirePositive(instanceUploadPermits, "quota.instance-upload-permits");
|
||||
requirePositive(scopeUploadPermits, "quota.scope-upload-permits");
|
||||
requirePositive(directDownloadPermits, "quota.direct-download-permits");
|
||||
requireFraction(softHighWater, "quota.soft-high-water");
|
||||
requireFraction(hardHighWater, "quota.hard-high-water");
|
||||
if (softHighWater >= hardHighWater) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX + ".quota.soft-high-water must be below quota.hard-high-water");
|
||||
}
|
||||
if (scopeUploadPermits > instanceUploadPermits) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX + ".quota.scope-upload-permits must not exceed quota.instance-upload-permits");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Background reclamation.
|
||||
*
|
||||
* <p>Off by default: the worker deletes physical objects, and a template that started deleting on
|
||||
* first boot would be deciding something the deployment has not yet decided.
|
||||
*/
|
||||
public record Cleanup(
|
||||
@DefaultValue("false") boolean enabled,
|
||||
@DefaultValue("60s") Duration interval,
|
||||
@DefaultValue("100") int maxItems,
|
||||
@DefaultValue("1GB") DataSize maxBytes,
|
||||
@DefaultValue("5m") Duration retryBackoff) {
|
||||
|
||||
public Cleanup {
|
||||
requirePositive(interval, "cleanup.interval");
|
||||
requirePositive(maxItems, "cleanup.max-items");
|
||||
requireSize(maxBytes, "cleanup.max-bytes");
|
||||
requirePositive(retryBackoff, "cleanup.retry-backoff");
|
||||
}
|
||||
}
|
||||
|
||||
/** tus 1.0 Stable protocol. */
|
||||
public record Tus(@DefaultValue("false") boolean enabled) {}
|
||||
|
||||
/** Experimental HTTP resumable-upload draft; no stability guarantee. */
|
||||
public record Draft12(@DefaultValue("false") boolean enabled) {}
|
||||
|
||||
/**
|
||||
* Front-proxy delegation.
|
||||
*
|
||||
* <p>There is no "mapping validated" switch. Whether the internal mapping holds is a fact the
|
||||
* startup attestation establishes by testing it, not a boolean a deployment can assert about
|
||||
* itself.
|
||||
*/
|
||||
public record Nginx(
|
||||
@DefaultValue("false") boolean enabled,
|
||||
@DefaultValue("/__files/") String internalPrefix,
|
||||
@DefaultValue(".bin") String objectSuffix,
|
||||
@DefaultValue("16MB") DataSize minimumSize) {
|
||||
|
||||
public Nginx {
|
||||
requireText(internalPrefix, "nginx.internal-prefix");
|
||||
requireText(objectSuffix, "nginx.object-suffix");
|
||||
requireSize(minimumSize, "nginx.minimum-size");
|
||||
}
|
||||
}
|
||||
|
||||
/** Telemetry settings; the fingerprint key is a secret and has no default. */
|
||||
public record Observability(
|
||||
@DefaultValue("true") boolean metricsEnabled, String fingerprintKey) {}
|
||||
|
||||
private static void requireText(String value, String name) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must be non-blank");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireRoles(List<String> roles, String name) {
|
||||
if (roles == null || roles.isEmpty()) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must list at least one role");
|
||||
}
|
||||
for (String role : roles) {
|
||||
requireText(role, name);
|
||||
}
|
||||
}
|
||||
|
||||
private static void requirePositive(int value, String name) {
|
||||
if (value < 1) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requirePositive(Duration value, String name) {
|
||||
if (value == null || value.isNegative() || value.isZero()) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must be a positive duration");
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireFraction(double value, String name) {
|
||||
if (!(value > 0) || value > 1) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must be within (0, 1]");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects a size that cannot survive the {@code int} narrowing the storage layer performs.
|
||||
*
|
||||
* <p>A buffer or limit above {@link Integer#MAX_VALUE} would silently wrap into a negative
|
||||
* allocation rather than fail, so the ceiling is checked where the value is still a long.
|
||||
*/
|
||||
private static long requireSize(DataSize value, String name) {
|
||||
if (value == null || value.toBytes() < 1) {
|
||||
throw StartupFailures.envValidation(PREFIX + "." + name + " must be a positive size");
|
||||
}
|
||||
return value.toBytes();
|
||||
}
|
||||
|
||||
private static void requireAbsolute(Path root) {
|
||||
if (root == null || !root.isAbsolute()) {
|
||||
throw StartupFailures.envValidation(
|
||||
PREFIX
|
||||
+ ".storage.root must be an absolute path: a relative root resolves against the "
|
||||
+ "process working directory, which differs between a container and a test");
|
||||
}
|
||||
}
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.StrictSettingsBinder;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Binds {@link FileserverPlatformSettings} strictly, and only when asked.
|
||||
*
|
||||
* <p>The mechanics — master-gated timing, refusing unknown keys under the prefix — live in {@link
|
||||
* StrictSettingsBinder}, which this and the HTTP client platform's binder used to hold a copy of
|
||||
* each (BOOT-011). What is left here is the one thing that is actually specific: which settings
|
||||
* type is bound. Every property source is in scope for the unbound-element check, because this
|
||||
* prefix is populated from YAML placeholders rather than bound directly from the system
|
||||
* environment.
|
||||
*/
|
||||
final class FileserverPlatformSettingsBinder {
|
||||
|
||||
private FileserverPlatformSettingsBinder() {}
|
||||
|
||||
static FileserverPlatformSettings bind(Environment environment) {
|
||||
return StrictSettingsBinder.bind(
|
||||
environment, FileserverPlatformSettings.PREFIX, FileserverPlatformSettings.class);
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.draft12.Draft12Properties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusChecksumVerifier;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusProperties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.tus.TusRequestParser;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverProtocolConfiguration {
|
||||
|
||||
/**
|
||||
* tus support objects, contributed only when both this switch and the master switch are on.
|
||||
*
|
||||
* <p>The nesting is the fix: previously the protocol's own flag was the only condition, so
|
||||
* enabling tus in a deployment with the Fileserver off produced a controller with no service
|
||||
* behind it.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX + ".tus",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
TusProperties fileserverTusProperties(FileserverPlatformSettings properties) {
|
||||
return new TusProperties(
|
||||
TusProperties.RESUMABLE_VERSION,
|
||||
List.of("creation", "expiration", "checksum", "termination"),
|
||||
properties.upload().maxFileSize().toBytes(),
|
||||
properties.upload().ttl());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX + ".tus",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
TusRequestParser fileserverTusRequestParser(TusProperties tusProperties) {
|
||||
return new TusRequestParser(tusProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX + ".tus",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
TusChecksumVerifier fileserverTusChecksumVerifier() {
|
||||
return new TusChecksumVerifier();
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings for the experimental draft, which previously had no production binding at all.
|
||||
*
|
||||
* <p>The controller existed and could be switched on, but nothing built the properties it needs,
|
||||
* so the switch produced a startup failure rather than a protocol.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnProperty(
|
||||
prefix = FileserverPlatformSettings.PREFIX + ".httpbis-draft12",
|
||||
name = "enabled",
|
||||
havingValue = "true")
|
||||
Draft12Properties fileserverDraft12Properties(FileserverPlatformSettings properties) {
|
||||
return new Draft12Properties(
|
||||
true, properties.upload().maxFileSize().toBytes(), properties.upload().ttl(), false);
|
||||
}
|
||||
}
|
||||
-95
@@ -1,95 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredAdminAuditAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.audit.StructuredFileserverAuditAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.RoleBasedFileAccessPolicy;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.UnenforcedFileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.admin.AdminAuditPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverAuditPort;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Chooses how file operations are authorized.
|
||||
*
|
||||
* <p>There is no permissive default. When a deployment supplies its own {@link FileAccessPolicy}
|
||||
* bean this class contributes nothing; otherwise the mode must be named explicitly, and the unnamed
|
||||
* case fails startup. The alternative — quietly permitting everything until someone configures a
|
||||
* policy — produces a capability that is wide open exactly while nobody is looking at it.
|
||||
*
|
||||
* <p>The unenforced stand-in is additionally refused under a production profile, so a value that
|
||||
* was convenient in a developer's configuration cannot survive a promotion.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class FileserverSecurityConfiguration {
|
||||
|
||||
private static final String MODE_REQUIRED = "required";
|
||||
private static final String MODE_ROLE_BASED = "role-based";
|
||||
private static final String MODE_UNENFORCED = "unenforced";
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileAccessPolicy fileserverAccessPolicy(
|
||||
FileserverPlatformSettings settings, Environment environment) {
|
||||
FileserverPlatformSettings.Security security = settings.security();
|
||||
String mode = security.accessPolicy().trim().toLowerCase(Locale.ROOT);
|
||||
return switch (mode) {
|
||||
// Anonymous read is not offered. The servlet chain authenticates every Fileserver route
|
||||
// before this policy is consulted, so the setting could only ever have described a
|
||||
// permission the transport had already refused — a configuration that looks like it grants
|
||||
// access and does not.
|
||||
case MODE_ROLE_BASED ->
|
||||
new RoleBasedFileAccessPolicy(
|
||||
toRoles(security.readRoles()),
|
||||
toRoles(security.writeRoles()),
|
||||
toRoles(security.adminRoles()),
|
||||
false);
|
||||
case MODE_UNENFORCED -> unenforcedOrFail(environment);
|
||||
case MODE_REQUIRED ->
|
||||
throw StartupFailures.envValidation(
|
||||
"fileserver is enabled without an authorization policy: supply a FileAccessPolicy "
|
||||
+ "bean, or set app.fileserver-platform.security.access-policy to role-based");
|
||||
default ->
|
||||
throw StartupFailures.envValidation(
|
||||
"app.fileserver-platform.security.access-policy must be one of required, role-based, "
|
||||
+ "unenforced");
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
AdminAuditPort fileserverAdminAudit() {
|
||||
return new StructuredAdminAuditAdapter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverAuditPort fileserverAccessAudit() {
|
||||
return new StructuredFileserverAuditAdapter();
|
||||
}
|
||||
|
||||
private static FileAccessPolicy unenforcedOrFail(Environment environment) {
|
||||
if (RuntimeProfileSnapshot.from(environment).isProduction()) {
|
||||
throw StartupFailures.profileMismatch(
|
||||
"app.fileserver-platform.security.access-policy=unenforced authorizes every file "
|
||||
+ "operation and must not be active under the '"
|
||||
+ RuntimeEnvironment.PROD.profileName()
|
||||
+ "' profile");
|
||||
}
|
||||
return new UnenforcedFileAccessPolicy();
|
||||
}
|
||||
|
||||
private static Set<String> toRoles(List<String> configured) {
|
||||
return Set.copyOf(new LinkedHashSet<>(configured));
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/** Application-service composition aggregator split by runtime concern. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import({
|
||||
FileserverUploadServiceConfiguration.class,
|
||||
FileserverDownloadLifecycleConfiguration.class,
|
||||
FileserverMaintenanceServiceConfiguration.class
|
||||
})
|
||||
class FileserverServiceConfiguration {}
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.application.fileserver.api.content.PublishMode;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Everything the startup gate needs to decide whether the Fileserver may accept traffic.
|
||||
*
|
||||
* <p>The composition root assembles this from the bound properties, the probe result, and which
|
||||
* beans it actually created. Keeping it a value makes the gate testable without a Spring context.
|
||||
*/
|
||||
public record FileserverStartupCheck(
|
||||
PublishMode publishMode,
|
||||
LocalStorageProbeResult probeResult,
|
||||
Path storageRoot,
|
||||
List<Path> forbiddenRootAncestors,
|
||||
boolean multiInstance,
|
||||
boolean metadataStorePresent,
|
||||
boolean productionProfile,
|
||||
boolean allowAllAccessPolicy,
|
||||
boolean scannerRequired,
|
||||
boolean scannerPresent,
|
||||
boolean nginxDelegationEnabled,
|
||||
boolean nginxInternalMappingValidated) {
|
||||
|
||||
public FileserverStartupCheck {
|
||||
Objects.requireNonNull(publishMode, "publishMode");
|
||||
Objects.requireNonNull(probeResult, "probeResult");
|
||||
Objects.requireNonNull(storageRoot, "storageRoot");
|
||||
Objects.requireNonNull(forbiddenRootAncestors, "forbiddenRootAncestors");
|
||||
forbiddenRootAncestors = List.copyOf(forbiddenRootAncestors);
|
||||
}
|
||||
}
|
||||
-90
@@ -1,90 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.NginxInternalUriMapper;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProperties;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.UnenforcedFileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationService;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Runs the fail-closed startup gate against the graph that was actually assembled.
|
||||
*
|
||||
* <p>The validator existed but nothing in the production graph called it, so every claim it makes —
|
||||
* a shared metadata store behind a multi-instance deployment, a verifier behind a scanner
|
||||
* requirement, no allow-all policy in production, a proven Nginx mapping — was a documented
|
||||
* intention rather than an enforced one. Wiring it as a bean whose construction depends on the
|
||||
* things it inspects is what turns those back into startup conditions.
|
||||
*
|
||||
* <p>The Nginx mapping is attested rather than asserted: the gate asks the mapper to produce an
|
||||
* internal URI and checks the answer, instead of reading a boolean in which a deployment claims its
|
||||
* own configuration is correct.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class FileserverStartupConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverStartupValidator fileserverStartupValidator() {
|
||||
return new FileserverStartupValidator();
|
||||
}
|
||||
|
||||
/**
|
||||
* The gate itself, expressed as a bean so its dependencies are its preconditions.
|
||||
*
|
||||
* <p>Spring cannot create it until the storage probe, the authorization policy, the metadata
|
||||
* store, and the verifier exist, which is exactly the set of facts the check needs.
|
||||
*/
|
||||
@Bean
|
||||
FileserverStartupCheck fileserverStartupCheck(
|
||||
FileserverStartupValidator validator,
|
||||
FileserverPlatformSettings settings,
|
||||
LocalStorageProperties storageProperties,
|
||||
LocalStorageProbeResult probeResult,
|
||||
FileAccessPolicy accessPolicy,
|
||||
FileMetadataStore metadataStore,
|
||||
FileVerificationService verificationService,
|
||||
NginxInternalUriMapper nginxUriMapper,
|
||||
Environment environment) {
|
||||
FileserverStartupCheck check =
|
||||
new FileserverStartupCheck(
|
||||
storageProperties.publishMode(),
|
||||
probeResult,
|
||||
storageProperties.root(),
|
||||
settings.storage().forbiddenRootAncestors(),
|
||||
!"local-node".equals(settings.instanceId()),
|
||||
metadataStore != null,
|
||||
isProductionProfile(environment),
|
||||
accessPolicy instanceof UnenforcedFileAccessPolicy,
|
||||
settings.verification().requireMediaTypeVerdict(),
|
||||
verificationService != null,
|
||||
settings.nginx().enabled(),
|
||||
nginxMappingHolds(settings, nginxUriMapper));
|
||||
validator.validate(check);
|
||||
return check;
|
||||
}
|
||||
|
||||
/**
|
||||
* Proves the internal mapping by exercising it rather than by trusting a flag.
|
||||
*
|
||||
* <p>A delegation whose internal prefix does not round-trip answers a 200 with an empty body,
|
||||
* which is the worst possible failure: the client believes it has the file.
|
||||
*/
|
||||
private static boolean nginxMappingHolds(
|
||||
FileserverPlatformSettings settings, NginxInternalUriMapper uriMapper) {
|
||||
if (!settings.nginx().enabled()) {
|
||||
return true;
|
||||
}
|
||||
return uriMapper.attestMapping();
|
||||
}
|
||||
|
||||
private static boolean isProductionProfile(Environment environment) {
|
||||
return RuntimeProfileSnapshot.from(environment).isProduction();
|
||||
}
|
||||
}
|
||||
-107
@@ -1,107 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.application.fileserver.api.content.PublishMode;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupPhase;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* Fail-closed startup gate for the Fileserver platform.
|
||||
*
|
||||
* <p>Every condition here is one the design calls a startup failure. Refusing to start is
|
||||
* deliberate: a running instance with an unproven atomic move, a shared web root, or an allow-all
|
||||
* authorization policy would look healthy while silently violating the invariants the whole design
|
||||
* rests on.
|
||||
*/
|
||||
public final class FileserverStartupValidator {
|
||||
|
||||
/** Shared lead-in for both entry points; the collected violations follow it. */
|
||||
private static final String SUMMARY = "fileserver startup validation failed";
|
||||
|
||||
/**
|
||||
* Validates the publish mode against what the storage probe actually proved.
|
||||
*
|
||||
* <p>{@code ATOMIC_MOVE_REQUIRED} is the one mode that must not degrade. The preferred mode is
|
||||
* allowed to fall back to a metadata pointer publish, so it only requires the mandatory checks.
|
||||
*/
|
||||
public void validate(PublishMode publishMode, LocalStorageProbeResult probeResult) {
|
||||
StartupValidationContext violations =
|
||||
StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION);
|
||||
collectStorageViolations(publishMode, probeResult, violations);
|
||||
violations.failIfViolated(SUMMARY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the whole Fileserver startup surface.
|
||||
*
|
||||
* <p>Collecting every violation before failing means an operator sees the complete list once
|
||||
* rather than discovering them one restart at a time.
|
||||
*/
|
||||
public void validate(FileserverStartupCheck check) {
|
||||
StartupValidationContext violations =
|
||||
StartupValidationContext.forPhase(StartupPhase.ENV_VALIDATION);
|
||||
collectStorageViolations(check.publishMode(), check.probeResult(), violations);
|
||||
collectRootViolations(check, violations);
|
||||
|
||||
if (check.multiInstance() && !check.metadataStorePresent()) {
|
||||
violations.reject("multi-instance mode requires a shared metadata store");
|
||||
}
|
||||
if (check.productionProfile() && check.allowAllAccessPolicy()) {
|
||||
violations.reject(
|
||||
"a no-op allow-all FileAccessPolicy must not be active in a production profile");
|
||||
}
|
||||
if (check.scannerRequired() && !check.scannerPresent()) {
|
||||
violations.reject("scanner-required is set but no file verifier bean is registered");
|
||||
}
|
||||
if (check.nginxDelegationEnabled() && !check.nginxInternalMappingValidated()) {
|
||||
violations.reject("nginx delegation is enabled without a validated internal URI mapping");
|
||||
}
|
||||
violations.failIfViolated(SUMMARY);
|
||||
}
|
||||
|
||||
private void collectStorageViolations(
|
||||
PublishMode publishMode,
|
||||
LocalStorageProbeResult probeResult,
|
||||
StartupValidationContext violations) {
|
||||
if (!probeResult.writableRoot()) {
|
||||
violations.reject("storage root is not writable");
|
||||
}
|
||||
if (!probeResult.atomicCreate()) {
|
||||
violations.reject("storage root does not provide atomic create");
|
||||
}
|
||||
if (!probeResult.sameFileStore()) {
|
||||
violations.reject("staging, content, and quarantine are not on the same file store");
|
||||
}
|
||||
if (!probeResult.symlinkNoFollow()) {
|
||||
violations.reject("storage root does not refuse to follow symbolic links");
|
||||
}
|
||||
if (!probeResult.descriptorRelativeAccess()) {
|
||||
violations.reject(
|
||||
"storage root does not support descriptor-relative access, so every open would "
|
||||
+ "re-resolve a pathname and leave the parent-replacement race open");
|
||||
}
|
||||
if (publishMode == PublishMode.ATOMIC_MOVE_REQUIRED && !probeResult.atomicMove()) {
|
||||
violations.reject(
|
||||
"publish mode requires an atomic move that the storage probe could not prove");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejects a storage root that shares a tree with code or configuration.
|
||||
*
|
||||
* <p>Storing uploads under a web root or a config root is what turns an upload into remote code
|
||||
* execution, so this is checked before anything is written.
|
||||
*/
|
||||
private void collectRootViolations(
|
||||
FileserverStartupCheck check, StartupValidationContext violations) {
|
||||
Path root = check.storageRoot().toAbsolutePath().normalize();
|
||||
for (Path forbidden : check.forbiddenRootAncestors()) {
|
||||
Path normalized = forbidden.toAbsolutePath().normalize();
|
||||
if (root.startsWith(normalized) || normalized.startsWith(root)) {
|
||||
violations.reject("storage root overlaps a web root or configuration root");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/** Storage composition aggregator; concrete concerns remain separately reviewable. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import({
|
||||
FileserverLocalStorageCoreConfiguration.class,
|
||||
FileserverStorageGatewayConfiguration.class,
|
||||
FileserverStorageOperationsConfiguration.class,
|
||||
FileserverVerificationConfiguration.class
|
||||
})
|
||||
class FileserverStorageConfiguration {}
|
||||
-66
@@ -1,66 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCleanupContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalCopyContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalDownloadContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadContentGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalUploadStorageGateway;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalZeroCopyDownloadGateway;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionStore;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupContentGateway;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyDownloadGateway;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.CopyContentGateway;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadStorageGateway;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverStorageGatewayConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadStorageGateway fileserverUploadStorageGateway(LocalBlockingContentStore store) {
|
||||
return new LocalUploadStorageGateway(store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadContentGateway fileserverUploadContentGateway(
|
||||
LocalBlockingContentStore store,
|
||||
FileMetadataStore metadataStore,
|
||||
UploadSessionStore sessionStore,
|
||||
FileserverPlatformSettings settings) {
|
||||
return new LocalUploadContentGateway(
|
||||
store, metadataStore, sessionStore, settings.upload().maxFileSize().toBytes());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
DownloadContentGateway fileserverDownloadContentGateway(LocalBlockingContentStore store) {
|
||||
return new LocalDownloadContentGateway(store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
CopyContentGateway fileserverCopyContentGateway(
|
||||
LocalBlockingContentStore store, FileserverPlatformSettings settings) {
|
||||
return new LocalCopyContentGateway(store, settings.upload().maxFileSize().toBytes());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
CleanupContentGateway fileserverCleanupContentGateway(LocalBlockingContentStore store) {
|
||||
return new LocalCleanupContentGateway(store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
ZeroCopyDownloadGateway fileserverZeroCopyDownloadGateway(LocalBlockingContentStore store) {
|
||||
return new LocalZeroCopyDownloadGateway(store);
|
||||
}
|
||||
}
|
||||
-56
@@ -1,56 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalOrphanScanAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalReconciliationContentProbe;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageHealthAdapter;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProperties;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageUsageProbe;
|
||||
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedger;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthPort;
|
||||
import dev.caskeleton.application.fileserver.quota.StorageUsageProbe;
|
||||
import dev.caskeleton.application.fileserver.recovery.ReconciliationContentProbe;
|
||||
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocator;
|
||||
import java.time.Clock;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverStorageOperationsConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
StorageHealthPort fileserverStorageHealth(
|
||||
LocalStorageProperties properties,
|
||||
LocalStorageProbeResult probeResult,
|
||||
LocalBlockingContentStore store) {
|
||||
return new LocalStorageHealthAdapter(properties, probeResult, store);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
OrphanScanPort fileserverOrphanScan(
|
||||
ContentReferenceLedger ledger,
|
||||
LocalStorageProperties properties,
|
||||
FileserverPlatformSettings settings,
|
||||
Clock clock) {
|
||||
return new LocalOrphanScanAdapter(
|
||||
ledger, properties, settings.admin().orphanMinimumAge(), clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
StorageUsageProbe fileserverStorageUsageProbe(LocalStorageProperties properties) {
|
||||
return new LocalStorageUsageProbe(properties.root());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
ReconciliationContentProbe fileserverReconciliationProbe(
|
||||
LocalBlockingContentStore store, StagingUploadLocator stagingLocator) {
|
||||
return new LocalReconciliationContentProbe(store, stagingLocator);
|
||||
}
|
||||
}
|
||||
-147
@@ -1,147 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.identifier.RandomUploadIdentifierFactory;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaService;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionStore;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueue;
|
||||
import dev.caskeleton.application.fileserver.concurrency.DefaultWriterLeaseCoordinator;
|
||||
import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.quota.DefaultTransferAdmissionController;
|
||||
import dev.caskeleton.application.fileserver.quota.StorageUsageProbe;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionController;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionProperties;
|
||||
import dev.caskeleton.application.fileserver.recovery.RecoveryQueue;
|
||||
import dev.caskeleton.application.fileserver.upload.DefaultFinalizeUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.DefaultSingleShotUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.DefaultUploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationService;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.QuotaCommitGateway;
|
||||
import dev.caskeleton.application.fileserver.upload.SingleShotUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadIdentifierFactory;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadPolicy;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadStorageGateway;
|
||||
import dev.caskeleton.application.transaction.PolicyTransactionPort;
|
||||
import dev.caskeleton.application.transaction.TransactionPort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverUploadServiceConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadIdentifierFactory fileserverIdentifierFactory() {
|
||||
return new RandomUploadIdentifierFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
TransferAdmissionProperties fileserverAdmissionProperties(FileserverPlatformSettings settings) {
|
||||
FileserverPlatformSettings.Quota quota = settings.quota();
|
||||
return new TransferAdmissionProperties(
|
||||
quota.instanceUploadPermits(),
|
||||
quota.scopeUploadPermits(),
|
||||
quota.directDownloadPermits(),
|
||||
quota.softHighWater(),
|
||||
quota.hardHighWater());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
TransferAdmissionController fileserverAdmissionController(
|
||||
TransferAdmissionProperties properties,
|
||||
StorageUsageProbe usageProbe,
|
||||
FileserverPlatformSettings settings) {
|
||||
return new DefaultTransferAdmissionController(
|
||||
properties, usageProbe, settings.upload().maxFileSize().toBytes());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
UploadApplicationService fileserverUploadService(
|
||||
FileMetadataStore metadataStore,
|
||||
UploadSessionStore sessionStore,
|
||||
WriterLeaseCoordinator leaseCoordinator,
|
||||
UploadStorageGateway storageGateway,
|
||||
FileQuotaService quotaService,
|
||||
TransferAdmissionController admissionController,
|
||||
FileAccessPolicy accessPolicy,
|
||||
OriginalFilenamePolicy filenamePolicy,
|
||||
CleanupQueue cleanupQueue,
|
||||
UploadIdentifierFactory identifierFactory,
|
||||
UploadPolicy uploadPolicy,
|
||||
ObjectProvider<FileserverMetricsPort> metrics,
|
||||
PolicyTransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultUploadApplicationService(
|
||||
metadataStore,
|
||||
sessionStore,
|
||||
leaseCoordinator,
|
||||
storageGateway,
|
||||
quotaService,
|
||||
admissionController,
|
||||
accessPolicy,
|
||||
filenamePolicy,
|
||||
cleanupQueue,
|
||||
identifierFactory,
|
||||
uploadPolicy,
|
||||
FileserverMetricsSupport.metricsOrNoop(metrics),
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FinalizeUploadService fileserverFinalizeService(
|
||||
FileMetadataStore metadataStore,
|
||||
UploadSessionStore sessionStore,
|
||||
UploadContentGateway contentGateway,
|
||||
FileVerificationService verificationService,
|
||||
QuotaCommitGateway quotaGateway,
|
||||
CleanupQueue cleanupQueue,
|
||||
RecoveryQueue recoveryQueue,
|
||||
LocalBlockingContentStore store,
|
||||
PolicyTransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultFinalizeUploadService(
|
||||
metadataStore,
|
||||
sessionStore,
|
||||
contentGateway,
|
||||
verificationService,
|
||||
quotaGateway,
|
||||
cleanupQueue,
|
||||
recoveryQueue,
|
||||
store.effectivePublishMode(),
|
||||
transactions,
|
||||
clock);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
SingleShotUploadService fileserverSingleShotUploadService(
|
||||
UploadApplicationService uploadService, FinalizeUploadService finalizeService) {
|
||||
return new DefaultSingleShotUploadService(uploadService, finalizeService);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
WriterLeaseCoordinator fileserverWriterLeaseCoordinator(
|
||||
UploadSessionStore sessionStore,
|
||||
UploadPolicy uploadPolicy,
|
||||
TransactionPort transactions,
|
||||
Clock clock) {
|
||||
return new DefaultWriterLeaseCoordinator(
|
||||
sessionStore, uploadPolicy.leaseDuration(), transactions, clock);
|
||||
}
|
||||
}
|
||||
-73
@@ -1,73 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalBlockingContentStore;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.FilenamePolicyVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.LengthVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.LocalVerificationContentReader;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.MediaTypeVerifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.ScriptableContentPolicy;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.Sha256Verifier;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.VerificationContentReader;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.verification.VerificationCoordinator;
|
||||
import dev.caskeleton.application.fileserver.api.DefaultFileStateMachine;
|
||||
import dev.caskeleton.application.fileserver.api.FileStateMachine;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileVerifier;
|
||||
import dev.caskeleton.application.fileserver.api.security.OriginalFilenamePolicy;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationService;
|
||||
import java.util.List;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverVerificationConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
OriginalFilenamePolicy fileserverFilenamePolicy() {
|
||||
return OriginalFilenamePolicy.standard();
|
||||
}
|
||||
|
||||
/**
|
||||
* The transition table, shared by everything that changes a file's state.
|
||||
*
|
||||
* <p>One instance rather than one per store. The metadata store rejects an illegal transition
|
||||
* before it reaches SQL, and a second copy of the table is a second place for the legal edges to
|
||||
* drift.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileStateMachine fileserverStateMachine() {
|
||||
return new DefaultFileStateMachine();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
VerificationContentReader fileserverVerificationContentReader(LocalBlockingContentStore store) {
|
||||
return new LocalVerificationContentReader(store);
|
||||
}
|
||||
|
||||
/**
|
||||
* The verification chain, in the order the design fixes.
|
||||
*
|
||||
* <p>Order does not change the verdict — precedence over the collected results does that — but it
|
||||
* does decide how much work a doomed upload causes. The cheap structural checks run before the
|
||||
* ones that read content.
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileVerificationService fileserverVerificationService(
|
||||
VerificationContentReader contentReader,
|
||||
OriginalFilenamePolicy filenamePolicy,
|
||||
FileserverPlatformSettings settings) {
|
||||
List<FileVerifier> verifiers =
|
||||
List.of(
|
||||
new LengthVerifier(settings.upload().maxFileSize().toBytes()),
|
||||
new Sha256Verifier(),
|
||||
new FilenamePolicyVerifier(filenamePolicy),
|
||||
new MediaTypeVerifier(contentReader, settings.verification().requireMediaTypeVerdict()),
|
||||
new ScriptableContentPolicy(
|
||||
contentReader, settings.verification().inlineSafeProfile()));
|
||||
return new VerificationCoordinator(verifiers, settings.verification().timeout());
|
||||
}
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.mapper.MultipartUploadRequestMapper;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.mapper.RawUploadRequestMapper;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.problem.FileserverProblemFactory;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.security.FileserverRequestContextFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class FileserverWebAssemblyConfiguration {
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverRequestContextFactory fileserverRequestContextFactory(
|
||||
FileserverPlatformSettings properties) {
|
||||
return new FileserverRequestContextFactory(properties.instanceId());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
FileserverProblemFactory fileserverProblemFactory() {
|
||||
return new FileserverProblemFactory();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
RawUploadRequestMapper fileserverRawUploadRequestMapper(FileserverPlatformSettings properties) {
|
||||
return new RawUploadRequestMapper(properties.upload().requireContentLength());
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
MultipartUploadRequestMapper fileserverMultipartUploadRequestMapper() {
|
||||
return new MultipartUploadRequestMapper();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.jpa;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
+1
-2
@@ -66,8 +66,7 @@ public class RedisActivationValidator implements SmartInitializingSingleton {
|
||||
private void validateIdempotencyKeyVersion() {
|
||||
if (!"redis"
|
||||
.equalsIgnoreCase(
|
||||
environment.getProperty(
|
||||
"ca-skeleton.capabilities.idempotency.provider", "disabled"))) {
|
||||
environment.getProperty("ca-skeleton.capabilities.idempotency.provider", "disabled"))) {
|
||||
return;
|
||||
}
|
||||
int keyVersion =
|
||||
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.cache.RedisCacheRegionAdapter;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.application.cache.CacheRegionPort;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The Redis-backed semantic cache region.
|
||||
*
|
||||
* <p>One capability, one configuration class (BOOT-007). It contributes nothing unless the cache
|
||||
* binding names Redis, and it is only reachable at all while the Redis master switch is on, because
|
||||
* {@link RedisCapabilityConfig} imports it and carries that switch.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class RedisCacheConfig {
|
||||
|
||||
/**
|
||||
* The semantic cache region for the default binding.
|
||||
*
|
||||
* @param owner the Redis runtime owner
|
||||
* @param sdk the Redis SDK settings, which own the namespace
|
||||
* @param capabilities the capability settings
|
||||
* @param secretSource resolves the key-digest material
|
||||
* @param clock the clock expiries are measured against
|
||||
* @return the cache region port
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
name = "ca-skeleton.capabilities.cache.bindings.default",
|
||||
havingValue = "redis")
|
||||
CacheRegionPort<String, byte[]> redisDefaultCacheRegion(
|
||||
RedisRuntimeOwner owner,
|
||||
RedisSdkSettings sdk,
|
||||
RedisCapabilitySettings capabilities,
|
||||
SecretSourcePort secretSource,
|
||||
Clock clock) {
|
||||
RedisCapabilitySettings.Cache cache = capabilities.getCache();
|
||||
cache.validate();
|
||||
RedisKeys.KeyDigest digest =
|
||||
RedisKeys.KeyDigest.of(secretSource, cache.getKeyHmacSecretReference(), "cache", sdk);
|
||||
return new RedisCacheRegionAdapter<>(
|
||||
owner,
|
||||
new RedisCacheRegionAdapter.CacheKeys(
|
||||
RedisKeys.namespaceOf(sdk), cache.getSemanticRegion(), cache.getKeyVersion()),
|
||||
digest::of,
|
||||
value -> value,
|
||||
stored -> stored,
|
||||
clock,
|
||||
cache.getPositiveSoftTtl(),
|
||||
cache.getPositiveHardTtl(),
|
||||
cache.getNegativeTtl(),
|
||||
cache.getCommandTimeout());
|
||||
}
|
||||
}
|
||||
-82
@@ -1,82 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
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.Import;
|
||||
|
||||
/**
|
||||
* Composes the Redis semantic ports the deployment's role selectors asked for.
|
||||
*
|
||||
* <p>Before this existed, {@code APP_REDIS_ENABLED=true} produced a client, a connection owner and
|
||||
* a health contributor — and nothing else. Every semantic port stayed unimplemented, so a
|
||||
* deployment that selected {@code redis} for its rate limiter got a context that started, reported
|
||||
* healthy, and had no rate limiter. "Redis is reachable" is not the same claim as "the capabilities
|
||||
* that need Redis are available", and only the second one is worth making.
|
||||
*
|
||||
* <p>Each port is conditional on its own selector, so selecting Redis for leases does not build an
|
||||
* idempotency store nobody asked for. All of them are conditional on {@link RedisRuntimeOwner},
|
||||
* which exists only while the global switch is on — a role selector never activates Redis by
|
||||
* itself, and {@code RedisActivationValidator} refuses the contradiction of a role that selects
|
||||
* Redis while the switch is off.
|
||||
*
|
||||
* <p>This class is the composition point only: it holds the master switch, binds the settings once,
|
||||
* bridges the secret backend into the SDK, and imports one configuration per capability. It used to
|
||||
* hold all four capabilities plus rate-limit policy compilation and the key digest — 376 lines, in
|
||||
* a leaf whose Notification platform had already been split into nine focused configurations. The
|
||||
* decomposition pattern existed; this was simply where it had not been applied (BOOT-007).
|
||||
*
|
||||
* <p>The namespace comes from {@code app.redis.namespace} for every capability. That is the change
|
||||
* that makes the ACL pattern meaningful: one prefix, {@code {environment}:{service}:{domain}}, that
|
||||
* the deployment's {@code ~} pattern can actually fence.
|
||||
*/
|
||||
@AutoConfiguration(after = RedisSdkAutoConfiguration.class)
|
||||
@EnableConfigurationProperties(RedisCapabilitySettings.class)
|
||||
// The global switch, not a role selector. A role selector says which capability composes; it
|
||||
// never says Redis exists, and RedisActivationValidator refuses the contradiction of one
|
||||
// without the other.
|
||||
@ConditionalOnProperty(prefix = "app.redis", name = "enabled", havingValue = "true")
|
||||
// Imported rather than scanned: the master switch above gates this class, and an @Import only
|
||||
// registers what a registered configuration asked for. Component scanning would have made each
|
||||
// capability configuration independently discoverable and the switch advisory.
|
||||
@Import({
|
||||
RedisCacheConfig.class,
|
||||
RedisRateLimitConfig.class,
|
||||
RedisLeaseConfig.class,
|
||||
RedisIdempotencyConfig.class
|
||||
})
|
||||
public class RedisCapabilityConfig {
|
||||
|
||||
/**
|
||||
* Bridges the deployment's configured secret backend into the Redis SDK.
|
||||
*
|
||||
* <p>Without it the SDK falls back to reading the process environment directly, which quietly
|
||||
* bypasses whichever backend {@code ca-skeleton.secret-source.strategy} selected — so a
|
||||
* deployment using a secret manager would resolve its Redis credential from an environment
|
||||
* variable that is not supposed to hold it.
|
||||
*
|
||||
* @param secretSource the configured backend
|
||||
* @return the SDK's view of it
|
||||
*/
|
||||
@Bean
|
||||
RedisSdkAutoConfiguration.RedisSecretSource redisSdkSecretSource(SecretSourcePort secretSource) {
|
||||
return secretSource::resolve;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(RedisSemanticScriptAclProbe.class)
|
||||
RedisSemanticScriptAclProbe redisSemanticScriptAclProbe(
|
||||
RedisRuntimeOwner owner, RedisCapabilitySettings capabilities, RedisSdkSettings sdk) {
|
||||
byte[] probeKey =
|
||||
(RedisKeys.namespaceOf(sdk).prefix() + ":probe:{semantic-script}:acl")
|
||||
.getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
return new RedisSemanticScriptAclProbe(
|
||||
owner, capabilities, probeKey, sdk.getTimeout().getScript());
|
||||
}
|
||||
}
|
||||
-465
@@ -1,465 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.NestedConfigurationProperty;
|
||||
|
||||
/**
|
||||
* The per-capability knobs the Redis composition reads.
|
||||
*
|
||||
* <p>One class rather than four, bound at {@code ca-skeleton.capabilities}, because the
|
||||
* capabilities share the decisions that matter: which provider is selected, how long a command may
|
||||
* take, and where the material that digests a caller's identifier comes from. Splitting them
|
||||
* produced four near-identical records and four places to forget the same setting.
|
||||
*
|
||||
* <p>What is deliberately <em>not</em> here is a namespace. Each capability used to carry its own
|
||||
* {@code namespace-application} and {@code namespace-environment}, which is how the deployment
|
||||
* ended up with four key prefixes, none of which matched the ACL pattern that was supposed to fence
|
||||
* it in. The namespace now comes from {@code app.redis.namespace}, once, and every capability
|
||||
* renders below it.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = "ca-skeleton.capabilities")
|
||||
public class RedisCapabilitySettings {
|
||||
|
||||
private final Cache cache = new Cache();
|
||||
private final RateLimit rateLimit = new RateLimit();
|
||||
private final Lease lease = new Lease();
|
||||
private final Idempotency idempotency = new Idempotency();
|
||||
|
||||
public Cache getCache() {
|
||||
return cache;
|
||||
}
|
||||
|
||||
@NestedConfigurationProperty
|
||||
public RateLimit getRateLimit() {
|
||||
return rateLimit;
|
||||
}
|
||||
|
||||
public Lease getLease() {
|
||||
return lease;
|
||||
}
|
||||
|
||||
public Idempotency getIdempotency() {
|
||||
return idempotency;
|
||||
}
|
||||
|
||||
/** Semantic cache region composition. */
|
||||
public static class Cache {
|
||||
|
||||
private Map<String, String> bindings = new LinkedHashMap<>();
|
||||
private String semanticRegion = "default";
|
||||
private int keyVersion = 1;
|
||||
private String keyHmacSecretReference;
|
||||
private Duration commandTimeout = Duration.ofMillis(200);
|
||||
private Duration positiveSoftTtl = Duration.ofSeconds(30);
|
||||
private Duration positiveHardTtl = Duration.ofMinutes(5);
|
||||
private Duration negativeTtl = Duration.ofSeconds(10);
|
||||
private Duration minimumHardTtl = Duration.ofSeconds(1);
|
||||
|
||||
/**
|
||||
* Reports whether the default binding selected Redis.
|
||||
*
|
||||
* @return {@code true} when {@code bindings.default} is {@code redis}
|
||||
*/
|
||||
public boolean redisSelected() {
|
||||
return "redis".equalsIgnoreCase(bindings.get("default"));
|
||||
}
|
||||
|
||||
void validate() {
|
||||
if (positiveSoftTtl.compareTo(positiveHardTtl) > 0) {
|
||||
throw StartupFailures.envValidation(
|
||||
"the cache soft TTL must not exceed the hard TTL: an entry cannot stop being fresh"
|
||||
+ " after it has stopped being usable");
|
||||
}
|
||||
if (positiveHardTtl.compareTo(minimumHardTtl) < 0) {
|
||||
// The floor exists so an operator cannot configure a cache whose entries expire faster
|
||||
// than the round trip that wrote them, which costs a Redis write per read and returns a
|
||||
// miss every time.
|
||||
throw StartupFailures.envValidation(
|
||||
"the cache hard TTL of "
|
||||
+ positiveHardTtl
|
||||
+ " is below the configured minimum of "
|
||||
+ minimumHardTtl);
|
||||
}
|
||||
if (commandTimeout.isZero() || commandTimeout.isNegative()) {
|
||||
throw StartupFailures.envValidation("the cache command timeout must be positive");
|
||||
}
|
||||
if (keyVersion < 1) {
|
||||
throw StartupFailures.envValidation("the cache key version must be positive");
|
||||
}
|
||||
}
|
||||
|
||||
public Map<String, String> getBindings() {
|
||||
return bindings;
|
||||
}
|
||||
|
||||
public void setBindings(Map<String, String> bindings) {
|
||||
this.bindings = bindings;
|
||||
}
|
||||
|
||||
public String getSemanticRegion() {
|
||||
return semanticRegion;
|
||||
}
|
||||
|
||||
public void setSemanticRegion(String semanticRegion) {
|
||||
this.semanticRegion = semanticRegion;
|
||||
}
|
||||
|
||||
public int getKeyVersion() {
|
||||
return keyVersion;
|
||||
}
|
||||
|
||||
public void setKeyVersion(int keyVersion) {
|
||||
this.keyVersion = keyVersion;
|
||||
}
|
||||
|
||||
public String getKeyHmacSecretReference() {
|
||||
return keyHmacSecretReference;
|
||||
}
|
||||
|
||||
public void setKeyHmacSecretReference(String keyHmacSecretReference) {
|
||||
this.keyHmacSecretReference = keyHmacSecretReference;
|
||||
}
|
||||
|
||||
public Duration getCommandTimeout() {
|
||||
return commandTimeout;
|
||||
}
|
||||
|
||||
public void setCommandTimeout(Duration commandTimeout) {
|
||||
this.commandTimeout = commandTimeout;
|
||||
}
|
||||
|
||||
public Duration getPositiveSoftTtl() {
|
||||
return positiveSoftTtl;
|
||||
}
|
||||
|
||||
public void setPositiveSoftTtl(Duration positiveSoftTtl) {
|
||||
this.positiveSoftTtl = positiveSoftTtl;
|
||||
}
|
||||
|
||||
public Duration getPositiveHardTtl() {
|
||||
return positiveHardTtl;
|
||||
}
|
||||
|
||||
public void setPositiveHardTtl(Duration positiveHardTtl) {
|
||||
this.positiveHardTtl = positiveHardTtl;
|
||||
}
|
||||
|
||||
public Duration getNegativeTtl() {
|
||||
return negativeTtl;
|
||||
}
|
||||
|
||||
public void setNegativeTtl(Duration negativeTtl) {
|
||||
this.negativeTtl = negativeTtl;
|
||||
}
|
||||
|
||||
public Duration getMinimumHardTtl() {
|
||||
return minimumHardTtl;
|
||||
}
|
||||
|
||||
public void setMinimumHardTtl(Duration minimumHardTtl) {
|
||||
this.minimumHardTtl = minimumHardTtl;
|
||||
}
|
||||
}
|
||||
|
||||
/** Edge rate-limit provider composition. */
|
||||
public static class RateLimit {
|
||||
|
||||
private String provider = "disabled";
|
||||
private String failurePolicy = "fail-closed";
|
||||
private String defaultPolicyId = "api-default";
|
||||
private Duration failureRetryAfter = Duration.ofMillis(100);
|
||||
private Duration commandTimeout = Duration.ofMillis(200);
|
||||
private int keyVersion = 1;
|
||||
private Map<String, Policy> policies = new LinkedHashMap<>();
|
||||
|
||||
public boolean redisSelected() {
|
||||
return "redis".equalsIgnoreCase(provider);
|
||||
}
|
||||
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public String getFailurePolicy() {
|
||||
return failurePolicy;
|
||||
}
|
||||
|
||||
public void setFailurePolicy(String failurePolicy) {
|
||||
this.failurePolicy = failurePolicy;
|
||||
}
|
||||
|
||||
public String getDefaultPolicyId() {
|
||||
return defaultPolicyId;
|
||||
}
|
||||
|
||||
public void setDefaultPolicyId(String defaultPolicyId) {
|
||||
this.defaultPolicyId = defaultPolicyId;
|
||||
}
|
||||
|
||||
public Duration getFailureRetryAfter() {
|
||||
return failureRetryAfter;
|
||||
}
|
||||
|
||||
public void setFailureRetryAfter(Duration failureRetryAfter) {
|
||||
this.failureRetryAfter = failureRetryAfter;
|
||||
}
|
||||
|
||||
public Duration getCommandTimeout() {
|
||||
return commandTimeout;
|
||||
}
|
||||
|
||||
public void setCommandTimeout(Duration commandTimeout) {
|
||||
this.commandTimeout = commandTimeout;
|
||||
}
|
||||
|
||||
public int getKeyVersion() {
|
||||
return keyVersion;
|
||||
}
|
||||
|
||||
public void setKeyVersion(int keyVersion) {
|
||||
this.keyVersion = keyVersion;
|
||||
}
|
||||
|
||||
public Map<String, Policy> getPolicies() {
|
||||
return policies;
|
||||
}
|
||||
|
||||
public void setPolicies(Map<String, Policy> policies) {
|
||||
this.policies = policies;
|
||||
}
|
||||
|
||||
/** One configured limit. */
|
||||
public static class Policy {
|
||||
|
||||
private String revision = "v1";
|
||||
private String algorithm = "sliding-counter";
|
||||
private long limit = 100;
|
||||
private Duration window = Duration.ofSeconds(1);
|
||||
private long capacity = 100;
|
||||
private long refillTokens = 100;
|
||||
private Duration refillPeriod = Duration.ofSeconds(1);
|
||||
private long maximumCost = 10;
|
||||
private Duration cleanupGrace = Duration.ofSeconds(5);
|
||||
|
||||
public String getRevision() {
|
||||
return revision;
|
||||
}
|
||||
|
||||
public void setRevision(String revision) {
|
||||
this.revision = revision;
|
||||
}
|
||||
|
||||
public String getAlgorithm() {
|
||||
return algorithm;
|
||||
}
|
||||
|
||||
public void setAlgorithm(String algorithm) {
|
||||
this.algorithm = algorithm;
|
||||
}
|
||||
|
||||
public long getLimit() {
|
||||
return limit;
|
||||
}
|
||||
|
||||
public void setLimit(long limit) {
|
||||
this.limit = limit;
|
||||
}
|
||||
|
||||
public Duration getWindow() {
|
||||
return window;
|
||||
}
|
||||
|
||||
public void setWindow(Duration window) {
|
||||
this.window = window;
|
||||
}
|
||||
|
||||
public long getCapacity() {
|
||||
return capacity;
|
||||
}
|
||||
|
||||
public void setCapacity(long capacity) {
|
||||
this.capacity = capacity;
|
||||
}
|
||||
|
||||
public long getRefillTokens() {
|
||||
return refillTokens;
|
||||
}
|
||||
|
||||
public void setRefillTokens(long refillTokens) {
|
||||
this.refillTokens = refillTokens;
|
||||
}
|
||||
|
||||
public Duration getRefillPeriod() {
|
||||
return refillPeriod;
|
||||
}
|
||||
|
||||
public void setRefillPeriod(Duration refillPeriod) {
|
||||
this.refillPeriod = refillPeriod;
|
||||
}
|
||||
|
||||
public long getMaximumCost() {
|
||||
return maximumCost;
|
||||
}
|
||||
|
||||
public void setMaximumCost(long maximumCost) {
|
||||
this.maximumCost = maximumCost;
|
||||
}
|
||||
|
||||
public Duration getCleanupGrace() {
|
||||
return cleanupGrace;
|
||||
}
|
||||
|
||||
public void setCleanupGrace(Duration cleanupGrace) {
|
||||
this.cleanupGrace = cleanupGrace;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Distributed lease provider composition. */
|
||||
public static class Lease {
|
||||
|
||||
private String provider = "disabled";
|
||||
private int keyVersion = 1;
|
||||
private Duration commandTimeout = Duration.ofMillis(200);
|
||||
private Duration contentionRetryAfter = Duration.ofMillis(50);
|
||||
private Duration driftBudget = Duration.ofMillis(10);
|
||||
|
||||
public boolean redisSelected() {
|
||||
return "redis".equalsIgnoreCase(provider);
|
||||
}
|
||||
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public int getKeyVersion() {
|
||||
return keyVersion;
|
||||
}
|
||||
|
||||
public void setKeyVersion(int keyVersion) {
|
||||
this.keyVersion = keyVersion;
|
||||
}
|
||||
|
||||
public Duration getCommandTimeout() {
|
||||
return commandTimeout;
|
||||
}
|
||||
|
||||
public void setCommandTimeout(Duration commandTimeout) {
|
||||
this.commandTimeout = commandTimeout;
|
||||
}
|
||||
|
||||
public Duration getContentionRetryAfter() {
|
||||
return contentionRetryAfter;
|
||||
}
|
||||
|
||||
public void setContentionRetryAfter(Duration contentionRetryAfter) {
|
||||
this.contentionRetryAfter = contentionRetryAfter;
|
||||
}
|
||||
|
||||
public Duration getDriftBudget() {
|
||||
return driftBudget;
|
||||
}
|
||||
|
||||
public void setDriftBudget(Duration driftBudget) {
|
||||
this.driftBudget = driftBudget;
|
||||
}
|
||||
}
|
||||
|
||||
/** Owner-safe request replay (V2) provider composition. */
|
||||
public static class Idempotency {
|
||||
|
||||
private String provider = "disabled";
|
||||
private int keyVersion = 1;
|
||||
private Duration commandTimeout = Duration.ofMillis(200);
|
||||
private Duration processingLease = Duration.ofSeconds(30);
|
||||
private Duration replayTtl = Duration.ofHours(24);
|
||||
private Duration failureRetention = Duration.ofHours(24);
|
||||
private String responseCodecId = "json-v2";
|
||||
|
||||
// The owner-safe claim carries this as a number, not a name: the store writes it into the
|
||||
// record and compares it there, and `IdempotencyClaimRequest` rejects anything below 1. It
|
||||
// used to be the string "request-replay-v2", which nothing read, because the only executor
|
||||
// that could have read it was written against a contract nothing implements.
|
||||
private int policyRevision = 2;
|
||||
|
||||
public boolean redisSelected() {
|
||||
return "redis".equalsIgnoreCase(provider);
|
||||
}
|
||||
|
||||
public String getProvider() {
|
||||
return provider;
|
||||
}
|
||||
|
||||
public void setProvider(String provider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
public int getKeyVersion() {
|
||||
return keyVersion;
|
||||
}
|
||||
|
||||
public void setKeyVersion(int keyVersion) {
|
||||
this.keyVersion = keyVersion;
|
||||
}
|
||||
|
||||
public Duration getCommandTimeout() {
|
||||
return commandTimeout;
|
||||
}
|
||||
|
||||
public void setCommandTimeout(Duration commandTimeout) {
|
||||
this.commandTimeout = commandTimeout;
|
||||
}
|
||||
|
||||
public Duration getProcessingLease() {
|
||||
return processingLease;
|
||||
}
|
||||
|
||||
public void setProcessingLease(Duration processingLease) {
|
||||
this.processingLease = processingLease;
|
||||
}
|
||||
|
||||
public Duration getReplayTtl() {
|
||||
return replayTtl;
|
||||
}
|
||||
|
||||
public void setReplayTtl(Duration replayTtl) {
|
||||
this.replayTtl = replayTtl;
|
||||
}
|
||||
|
||||
public Duration getFailureRetention() {
|
||||
return failureRetention;
|
||||
}
|
||||
|
||||
public void setFailureRetention(Duration failureRetention) {
|
||||
this.failureRetention = failureRetention;
|
||||
}
|
||||
|
||||
public String getResponseCodecId() {
|
||||
return responseCodecId;
|
||||
}
|
||||
|
||||
public void setResponseCodecId(String responseCodecId) {
|
||||
this.responseCodecId = responseCodecId;
|
||||
}
|
||||
|
||||
public int getPolicyRevision() {
|
||||
return policyRevision;
|
||||
}
|
||||
|
||||
public void setPolicyRevision(int policyRevision) {
|
||||
this.policyRevision = policyRevision;
|
||||
}
|
||||
}
|
||||
}
|
||||
-79
@@ -1,79 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.idempotency.IdempotencyScripts;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.idempotency.RedisIdempotencyStoreAdapter;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2;
|
||||
import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2;
|
||||
import java.time.Clock;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The Redis-backed owner-safe idempotency store and the executor that drives it.
|
||||
*
|
||||
* <p>Both beans stay together because the selection guard in {@code
|
||||
* IdempotencyProviderSelectionConfig} refuses a store with no executor: they are one selection, not
|
||||
* two (BOOT-007).
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class RedisIdempotencyConfig {
|
||||
|
||||
/**
|
||||
* The owner-safe request-replay store.
|
||||
*
|
||||
* @param owner the Redis runtime owner
|
||||
* @param sdk the Redis SDK settings, which own the namespace
|
||||
* @param capabilities the capability settings
|
||||
* @param clock the clock lease deadlines are measured against
|
||||
* @return the V2 store port
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
name = "ca-skeleton.capabilities.idempotency.provider",
|
||||
havingValue = "redis")
|
||||
IdempotencyStorePortV2 redisIdempotencyStore(
|
||||
RedisRuntimeOwner owner,
|
||||
RedisSdkSettings sdk,
|
||||
RedisCapabilitySettings capabilities,
|
||||
Clock clock) {
|
||||
RedisCapabilitySettings.Idempotency idempotency = capabilities.getIdempotency();
|
||||
return new RedisIdempotencyStoreAdapter(
|
||||
owner,
|
||||
new RedisIdempotencyStoreAdapter.IdempotencyKeys(
|
||||
RedisKeys.namespaceOf(sdk), idempotency.getKeyVersion()),
|
||||
new IdempotencyScripts(),
|
||||
clock,
|
||||
idempotency.getCommandTimeout());
|
||||
}
|
||||
|
||||
/**
|
||||
* The request-replay lifecycle driven over the selected owner-safe store.
|
||||
*
|
||||
* <p>Provider-neutral by type — it depends on {@link IdempotencyStorePortV2}, not on Redis — and
|
||||
* composed here because this is where the settings behind it are bound. A selection that produced
|
||||
* the store and no executor produced a store nothing could drive, which is what {@code
|
||||
* IdempotencyProviderSelectionConfig} refuses.
|
||||
*
|
||||
* @param store the selected owner-safe store
|
||||
* @param capabilities the capability settings
|
||||
* @return the owner-safe request-replay executor
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
name = "ca-skeleton.capabilities.idempotency.provider",
|
||||
havingValue = "redis")
|
||||
IdempotencyExecutorV2 idempotencyExecutorV2(
|
||||
IdempotencyStorePortV2 store, RedisCapabilitySettings capabilities) {
|
||||
RedisCapabilitySettings.Idempotency idempotency = capabilities.getIdempotency();
|
||||
return new IdempotencyExecutorV2(
|
||||
store,
|
||||
idempotency.getProcessingLease(),
|
||||
idempotency.getReplayTtl(),
|
||||
idempotency.getFailureRetention(),
|
||||
idempotency.getResponseCodecId(),
|
||||
idempotency.getPolicyRevision());
|
||||
}
|
||||
}
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.key.RedisNamespace;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* Namespace construction and the keyed digest every Redis capability derives its key material from.
|
||||
*
|
||||
* <p>Both were private members of the single Redis configuration class. Splitting that class by
|
||||
* capability (BOOT-007) made them shared, and shared members of a class that no longer exists have
|
||||
* to live somewhere: here, where the two things a Redis key is made of — the deployment's namespace
|
||||
* and the digest that hides identifiers inside it — sit together and are named for what they are.
|
||||
*/
|
||||
final class RedisKeys {
|
||||
|
||||
private RedisKeys() {}
|
||||
|
||||
/** The deployment's key namespace: {@code {environment}:{service}:{domain}}. */
|
||||
static RedisNamespace namespaceOf(RedisSdkSettings settings) {
|
||||
return new RedisNamespace(
|
||||
settings.getNamespace().getEnvironment(),
|
||||
settings.getNamespace().getService(),
|
||||
settings.getNamespace().getDomain());
|
||||
}
|
||||
|
||||
/**
|
||||
* Digests a semantic key before it reaches Redis.
|
||||
*
|
||||
* <p>Keyed, not plain. An unkeyed digest of a low-entropy identifier — a customer number, a short
|
||||
* order id — is reversible by anyone who can read the keyspace and can guess the format, which is
|
||||
* everyone who can run {@code SCAN}. The key comes from the deployment's secret backend, so the
|
||||
* keyspace is only correlatable by something that already holds the secret.
|
||||
*/
|
||||
record KeyDigest(javax.crypto.Mac prototype) {
|
||||
|
||||
static KeyDigest of(
|
||||
SecretSourcePort secretSource, String reference, String capability, RedisSdkSettings sdk) {
|
||||
String name = secretName(reference, capability);
|
||||
String material =
|
||||
secretSource
|
||||
.resolve(name)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
StartupFailures.envValidation(
|
||||
"the Redis "
|
||||
+ capability
|
||||
+ " key-digest secret '"
|
||||
+ name
|
||||
+ "' resolved to nothing. Without it the keyspace would carry"
|
||||
+ " identifiers in a form anybody who can read it could reverse."));
|
||||
try {
|
||||
javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256");
|
||||
mac.init(
|
||||
new javax.crypto.spec.SecretKeySpec(
|
||||
// Namespace-bound: the same identifier in staging and production must not digest
|
||||
// to the same key, or a keyspace dump from the softer environment would map
|
||||
// one-for-one onto the harder one.
|
||||
(material
|
||||
+ '|'
|
||||
+ sdk.getNamespace().getEnvironment()
|
||||
+ ':'
|
||||
+ sdk.getNamespace().getService()
|
||||
+ ':'
|
||||
+ sdk.getNamespace().getDomain())
|
||||
.getBytes(StandardCharsets.UTF_8),
|
||||
"HmacSHA256"));
|
||||
return new KeyDigest(mac);
|
||||
} catch (java.security.GeneralSecurityException failure) {
|
||||
throw new IllegalStateException("HmacSHA256 must be available", failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static String secretName(String reference, String capability) {
|
||||
if (reference == null || reference.isBlank()) {
|
||||
throw StartupFailures.envValidation(
|
||||
"the Redis " + capability + " capability needs a key-digest secret reference");
|
||||
}
|
||||
int separator = reference.lastIndexOf('/');
|
||||
if (!reference.startsWith("secret://") || separator < 0) {
|
||||
throw StartupFailures.envValidation(
|
||||
"the Redis "
|
||||
+ capability
|
||||
+ " key-digest reference '"
|
||||
+ reference
|
||||
+ "' must be secret://<source>/<name>");
|
||||
}
|
||||
return reference.substring(separator + 1);
|
||||
}
|
||||
|
||||
String of(String key) {
|
||||
try {
|
||||
javax.crypto.Mac mac = (javax.crypto.Mac) prototype.clone();
|
||||
return "hv1:"
|
||||
+ java.util.HexFormat.of().formatHex(mac.doFinal(key.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (CloneNotSupportedException failure) {
|
||||
throw new IllegalStateException("a Mac must be cloneable", failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-45
@@ -1,45 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.lease.LeaseScripts;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.lease.RedisDistributedLeaseAdapter;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.application.lease.DistributedLeasePort;
|
||||
import java.time.Clock;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/** The Redis-backed distributed lease. Efficiency only — it never supplies fencing. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class RedisLeaseConfig {
|
||||
|
||||
/**
|
||||
* The distributed lease port. Efficiency only — it never supplies fencing.
|
||||
*
|
||||
* @param owner the Redis runtime owner
|
||||
* @param sdk the Redis SDK settings, which own the namespace
|
||||
* @param capabilities the capability settings
|
||||
* @param clock the wall clock used for reporting instants
|
||||
* @return the lease port
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(name = "ca-skeleton.capabilities.lease.provider", havingValue = "redis")
|
||||
DistributedLeasePort redisDistributedLeasePort(
|
||||
RedisRuntimeOwner owner,
|
||||
RedisSdkSettings sdk,
|
||||
RedisCapabilitySettings capabilities,
|
||||
Clock clock) {
|
||||
RedisCapabilitySettings.Lease lease = capabilities.getLease();
|
||||
return new RedisDistributedLeaseAdapter(
|
||||
owner,
|
||||
new RedisDistributedLeaseAdapter.LeaseKeys(
|
||||
RedisKeys.namespaceOf(sdk), lease.getKeyVersion()),
|
||||
new LeaseScripts(),
|
||||
clock,
|
||||
System::nanoTime,
|
||||
lease.getCommandTimeout(),
|
||||
lease.getContentionRetryAfter(),
|
||||
lease.getDriftBudget());
|
||||
}
|
||||
}
|
||||
-134
@@ -1,134 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitKeys;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RateLimitScripts;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.ratelimit.RedisEdgeRateLimitAdapter;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort;
|
||||
import dev.caskeleton.shared.ratelimit.RateLimitAlgorithm;
|
||||
import dev.caskeleton.shared.ratelimit.RateLimitFailurePolicy;
|
||||
import dev.caskeleton.shared.ratelimit.RateLimitPolicy;
|
||||
import dev.caskeleton.shared.ratelimit.RateParameters;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* The Redis-backed edge rate limiter, and the policy compilation it needs.
|
||||
*
|
||||
* <p>The two private helpers below are the largest part of what used to make the single Redis
|
||||
* configuration class 376 lines: policy compilation belongs to the rate limiter and to nothing
|
||||
* else, so it moves with it (BOOT-007).
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
class RedisRateLimitConfig {
|
||||
|
||||
/**
|
||||
* The provider-neutral edge rate limiter, backed by Redis.
|
||||
*
|
||||
* @param owner the Redis runtime owner
|
||||
* @param sdk the Redis SDK settings, which own the namespace
|
||||
* @param capabilities the capability settings
|
||||
* @param clock the local clock used for caller deadlines and response reset instants
|
||||
* @return the rate limit port
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnProperty(
|
||||
name = "ca-skeleton.capabilities.rate-limit.provider",
|
||||
havingValue = "redis")
|
||||
EdgeRateLimitPort redisEdgeRateLimitPort(
|
||||
RedisRuntimeOwner owner,
|
||||
RedisSdkSettings sdk,
|
||||
RedisCapabilitySettings capabilities,
|
||||
Clock clock) {
|
||||
RedisCapabilitySettings.RateLimit rateLimit = capabilities.getRateLimit();
|
||||
return new RedisEdgeRateLimitAdapter(
|
||||
owner,
|
||||
new RateLimitKeys(RedisKeys.namespaceOf(sdk), rateLimit.getKeyVersion()),
|
||||
policiesOf(rateLimit),
|
||||
new RateLimitScripts(),
|
||||
clock,
|
||||
rateLimit.getCommandTimeout(),
|
||||
rateLimit.getFailureRetryAfter());
|
||||
}
|
||||
|
||||
private static Map<String, RateLimitPolicy> policiesOf(
|
||||
RedisCapabilitySettings.RateLimit rateLimit) {
|
||||
if (rateLimit.getPolicies().isEmpty()) {
|
||||
// An enabled limiter with no policy would answer every request "unknown policy", which the
|
||||
// port reports as a deployment error on every call rather than once at startup.
|
||||
throw StartupFailures.envValidation(
|
||||
"the Redis rate limiter is selected but no policy is configured under"
|
||||
+ " ca-skeleton.capabilities.rate-limit.policies");
|
||||
}
|
||||
Map<String, RateLimitPolicy> policies = new LinkedHashMap<>();
|
||||
rateLimit
|
||||
.getPolicies()
|
||||
.forEach((id, policy) -> policies.put(id, policyOf(id, policy, rateLimit)));
|
||||
if (!policies.containsKey(rateLimit.getDefaultPolicyId())) {
|
||||
throw StartupFailures.envValidation(
|
||||
"the default rate-limit policy '"
|
||||
+ rateLimit.getDefaultPolicyId()
|
||||
+ "' is not among the configured policies "
|
||||
+ policies.keySet());
|
||||
}
|
||||
return policies;
|
||||
}
|
||||
|
||||
private static RateLimitPolicy policyOf(
|
||||
String id,
|
||||
RedisCapabilitySettings.RateLimit.Policy policy,
|
||||
RedisCapabilitySettings.RateLimit rateLimit) {
|
||||
RateLimitAlgorithm algorithm =
|
||||
switch (policy.getAlgorithm().toLowerCase(Locale.ROOT)) {
|
||||
case "fixed-window" -> RateLimitAlgorithm.FIXED_WINDOW;
|
||||
case "sliding-counter" -> RateLimitAlgorithm.SLIDING_COUNTER;
|
||||
case "token-bucket" -> RateLimitAlgorithm.TOKEN_BUCKET;
|
||||
default ->
|
||||
throw StartupFailures.envValidation(
|
||||
"unsupported rate-limit algorithm '" + policy.getAlgorithm() + "' for " + id);
|
||||
};
|
||||
RateParameters parameters =
|
||||
switch (algorithm) {
|
||||
case FIXED_WINDOW ->
|
||||
new RateParameters.FixedWindow(policy.getLimit(), policy.getWindow());
|
||||
case SLIDING_COUNTER ->
|
||||
new RateParameters.SlidingCounter(policy.getLimit(), policy.getWindow());
|
||||
case TOKEN_BUCKET ->
|
||||
new RateParameters.TokenBucket(
|
||||
policy.getCapacity(), policy.getRefillTokens(), policy.getRefillPeriod());
|
||||
// No `default`. RateLimitAlgorithm has exactly these three constants, so the branch
|
||||
// that
|
||||
// used to be here was unreachable — and it suppressed the compiler's exhaustiveness
|
||||
// check
|
||||
// on this switch expression, which is the one thing that would notice a fourth
|
||||
// algorithm
|
||||
// being added without parameters for it (BOOT-010).
|
||||
};
|
||||
if (!"fail-closed".equalsIgnoreCase(rateLimit.getFailurePolicy())) {
|
||||
// The port only implements fail-closed, so a deployment that configured anything else has a
|
||||
// limit it believes is permissive and is not.
|
||||
throw StartupFailures.envValidation(
|
||||
"only fail-closed is supported for the Redis rate limiter, but"
|
||||
+ " ca-skeleton.capabilities.rate-limit.failure-policy is '"
|
||||
+ rateLimit.getFailurePolicy()
|
||||
+ "'");
|
||||
}
|
||||
return new RateLimitPolicy(
|
||||
id,
|
||||
policy.getRevision(),
|
||||
algorithm,
|
||||
parameters,
|
||||
policy.getMaximumCost(),
|
||||
policy.getCleanupGrace(),
|
||||
Duration.ZERO,
|
||||
RateLimitFailurePolicy.FAIL_CLOSED);
|
||||
}
|
||||
}
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisLease;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
|
||||
/**
|
||||
* Fails startup when a selected semantic capability needs the SCRIPT lane but its effective Redis
|
||||
* account cannot actually execute registered programs.
|
||||
*/
|
||||
final class RedisSemanticScriptAclProbe implements SmartInitializingSingleton {
|
||||
|
||||
private static final byte[] PROBE_SCRIPT = "return {1}".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
private final RedisRuntimeOwner owner;
|
||||
private final RedisCapabilitySettings capabilities;
|
||||
private final byte[] probeKey;
|
||||
private final Duration timeout;
|
||||
|
||||
RedisSemanticScriptAclProbe(
|
||||
RedisRuntimeOwner owner,
|
||||
RedisCapabilitySettings capabilities,
|
||||
byte[] probeKey,
|
||||
Duration timeout) {
|
||||
this.owner = Objects.requireNonNull(owner, "owner must be non-null");
|
||||
this.capabilities = Objects.requireNonNull(capabilities, "capabilities must be non-null");
|
||||
this.probeKey = Objects.requireNonNull(probeKey, "probe key must be non-null").clone();
|
||||
this.timeout = Objects.requireNonNull(timeout, "timeout must be non-null");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterSingletonsInstantiated() {
|
||||
if (!scriptCapabilitySelected()) {
|
||||
return;
|
||||
}
|
||||
try (RedisLease lease = owner.borrow(RedisConnectionKind.SCRIPT)) {
|
||||
String digest =
|
||||
lease
|
||||
.gateway()
|
||||
.loadScript(PROBE_SCRIPT)
|
||||
.toCompletableFuture()
|
||||
.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
|
||||
List<Object> reply =
|
||||
lease
|
||||
.gateway()
|
||||
.evaluateRegisteredForList(digest, probeKey, List.of())
|
||||
.toCompletableFuture()
|
||||
.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
|
||||
if (reply.size() != 1
|
||||
|| !(reply.get(0) instanceof Number number)
|
||||
|| number.longValue() != 1L) {
|
||||
throw StartupFailures.envValidation(
|
||||
"Redis semantic SCRIPT capability is selected but the SCRIPT ACL probe returned an "
|
||||
+ "unexpected reply");
|
||||
}
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw StartupFailures.envValidation("Redis SCRIPT ACL probe was interrupted", interrupted);
|
||||
} catch (Exception failure) {
|
||||
throw StartupFailures.envValidation(
|
||||
"Redis semantic SCRIPT capability is selected but SCRIPT LOAD/EVALSHA is unavailable; "
|
||||
+ "configure the ADVANCED Redis credential role or grant the effective account the "
|
||||
+ "required script permissions",
|
||||
failure);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean scriptCapabilitySelected() {
|
||||
return capabilities.getRateLimit().redisSelected()
|
||||
|| capabilities.getLease().redisSelected()
|
||||
|| capabilities.getIdempotency().redisSelected();
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.tracing;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
|
||||
import dev.caskeleton.shared.tracing.SpanErrorRecorder;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.tracing;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupOrder;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
package dev.caskeleton.bootstrap.logging;
|
||||
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import java.util.List;
|
||||
import org.slf4j.ILoggerFactory;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.util.Locale;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupFailures;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
-48
@@ -1,48 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
/**
|
||||
* Immutable snapshot of Spring's active profiles at one composition-root decision point.
|
||||
*
|
||||
* <p>This is the only app-bootstrap production type that reads {@link
|
||||
* Environment#getActiveProfiles()}. Runtime vocabulary and interpretation remain owned by the
|
||||
* framework-free {@link RuntimeEnvironment}; this type only bridges Spring's environment API to
|
||||
* that contract.
|
||||
*/
|
||||
public record RuntimeProfileSnapshot(List<String> activeProfiles) {
|
||||
|
||||
public RuntimeProfileSnapshot {
|
||||
activeProfiles = List.copyOf(Objects.requireNonNull(activeProfiles, "activeProfiles"));
|
||||
}
|
||||
|
||||
/** Captures the current Spring active-profile order without interpreting it. */
|
||||
public static RuntimeProfileSnapshot from(Environment environment) {
|
||||
Objects.requireNonNull(environment, "environment");
|
||||
return new RuntimeProfileSnapshot(List.of(environment.getActiveProfiles()));
|
||||
}
|
||||
|
||||
/** Runtime environments named by this profile set, preserving profile order. */
|
||||
public List<RuntimeEnvironment> environments() {
|
||||
return RuntimeEnvironment.activeIn(activeProfiles);
|
||||
}
|
||||
|
||||
/** The single runtime environment when exactly one is named. */
|
||||
public Optional<RuntimeEnvironment> resolve() {
|
||||
return RuntimeEnvironment.resolve(activeProfiles);
|
||||
}
|
||||
|
||||
/** Whether this snapshot names the production runtime environment. */
|
||||
public boolean isProduction() {
|
||||
return RuntimeEnvironment.isProductionActive(activeProfiles);
|
||||
}
|
||||
|
||||
/** Whether this snapshot includes the test-only profile. */
|
||||
public boolean isTestContext() {
|
||||
return RuntimeEnvironment.isTestContext(activeProfiles);
|
||||
}
|
||||
}
|
||||
+1
@@ -1,5 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupPhase;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupValidationContext;
|
||||
|
||||
+1
-4
@@ -21,8 +21,7 @@ public class StartupSafetyValidator implements SmartInitializingSingleton {
|
||||
private final RuntimeSafetySettings settings;
|
||||
private final ListableBeanFactory beanFactory;
|
||||
|
||||
public StartupSafetyValidator(
|
||||
RuntimeSafetySettings settings, ListableBeanFactory beanFactory) {
|
||||
public StartupSafetyValidator(RuntimeSafetySettings settings, ListableBeanFactory beanFactory) {
|
||||
this.settings = settings;
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
@@ -60,6 +59,4 @@ public class StartupSafetyValidator implements SmartInitializingSingleton {
|
||||
invalid.failIfViolated(
|
||||
"APP_MULTI_INSTANCE_ENABLED=true requires the cross-instance DistributedLockPort");
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
package dev.caskeleton.bootstrap.runtime.startup;
|
||||
|
||||
import dev.caskeleton.bootstrap.runtime.RuntimeProfileSnapshot;
|
||||
import dev.caskeleton.adapter.outbound.support.runtime.RuntimeProfileSnapshot;
|
||||
import org.springframework.beans.factory.SmartInitializingSingleton;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
|
||||
-1
@@ -1 +0,0 @@
|
||||
dev.caskeleton.bootstrap.autoconfigure.fileserver.FileserverAdminManagementContextConfiguration
|
||||
-2
@@ -1,10 +1,8 @@
|
||||
dev.caskeleton.bootstrap.autoconfigure.common.BootstrapClockAutoConfiguration
|
||||
dev.caskeleton.bootstrap.autoconfigure.fileserver.FileserverPlatformAutoConfiguration
|
||||
dev.caskeleton.bootstrap.autoconfigure.jpa.PersistenceJpaRootAutoConfiguration
|
||||
dev.caskeleton.bootstrap.autoconfigure.messaging.DisabledMessagingSentinelAutoConfiguration
|
||||
dev.caskeleton.bootstrap.activation.AdapterActivationAutoConfiguration
|
||||
dev.caskeleton.bootstrap.autoconfigure.notification.NotificationApplicationCompositionAutoConfiguration
|
||||
dev.caskeleton.bootstrap.autoconfigure.redis.RedisCapabilityConfig
|
||||
dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig
|
||||
dev.caskeleton.bootstrap.autoconfigure.lock.DistributedLockConfig
|
||||
dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig
|
||||
|
||||
@@ -10,3 +10,6 @@
|
||||
app:
|
||||
httpclient:
|
||||
enabled: ${APP_HTTPCLIENT_ENABLED:false}
|
||||
# Platform-level, not per-client: how long a retired runtime generation keeps draining after a
|
||||
# certificate rotation before its pool is closed under whatever is still in flight.
|
||||
rotation-drain-timeout: ${APP_HTTPCLIENT_ROTATION_DRAIN_TIMEOUT:30s}
|
||||
|
||||
+33
-57
@@ -1,24 +1,20 @@
|
||||
package dev.caskeleton.bootstrap.activation;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.capability.RedisCapabilitySettings;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.autoconfigure.HttpClientPlatformSettings;
|
||||
import dev.caskeleton.adapter.outbound.httpclient.service.HttpServiceRegistry;
|
||||
import dev.caskeleton.adapter.outbound.messaging.kafka.KafkaSender;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyExecutor;
|
||||
import dev.caskeleton.application.idempotency.v2.IdempotencyExecutorV2;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.lock.MeteredDistributedLockPort;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxMetrics;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxRelayScheduler;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.redis.RedisCapabilitySettings;
|
||||
import io.micrometer.tracing.Tracer;
|
||||
import java.lang.reflect.Proxy;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
|
||||
import org.springframework.beans.factory.support.RootBeanDefinition;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.scheduling.config.TaskManagementConfigUtils;
|
||||
|
||||
/**
|
||||
@@ -121,63 +117,43 @@ class BootstrapCapabilityReachabilitySystemTest {
|
||||
|
||||
@Test
|
||||
void outboxRootIsReachableFromTheShippedCompositionWhenEnabled() {
|
||||
var builder =
|
||||
ShippedCompositionHarness.shippedComposition("local")
|
||||
.initializers(BootstrapCapabilityReachabilitySystemTest::registerNoOpKafkaSeams);
|
||||
|
||||
// No broker, and none needed: `relay-enabled=false` is one of the two coherent outbox
|
||||
// configurations, and it is the one a broker-neutral artifact can run. This test used to select
|
||||
// Kafka and hand-register no-op Kafka seams, which only worked while the shipped composition
|
||||
// still carried the Kafka provider configuration. It does not — the broker starter is a build
|
||||
// decision the deployment makes — so selecting one here was asserting a composition this
|
||||
// artifact cannot produce.
|
||||
try (ConfigurableApplicationContext context =
|
||||
builder.run(
|
||||
ShippedCompositionHarness.allOffWithH2(
|
||||
"reachability_outbox",
|
||||
"--ca-skeleton.outbox.enabled=true",
|
||||
"--ca-skeleton.outbox.relay-enabled=false",
|
||||
"--app.messaging.enabled=true",
|
||||
"--app.messaging.broker=kafka",
|
||||
"--app.messaging.kafka.brokers[0]=unused.invalid:9092",
|
||||
"--spring.kafka.bootstrap-servers=unused.invalid:9092"))) {
|
||||
ShippedCompositionHarness.shippedComposition("local")
|
||||
.run(
|
||||
ShippedCompositionHarness.allOffWithH2(
|
||||
"reachability_outbox",
|
||||
"--ca-skeleton.outbox.enabled=true",
|
||||
"--ca-skeleton.outbox.relay-enabled=false"))) {
|
||||
assertThat(context.containsBean("outboxLeaderElection")).isTrue();
|
||||
assertThat(context.getBeansOfType(OutboxMetrics.class)).hasSize(1);
|
||||
assertThat(context.getBeansOfType(OutboxRelayScheduler.class)).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
private static void registerNoOpKafkaSeams(ConfigurableApplicationContext context) {
|
||||
Class<?> producer = loadKafkaProducerType();
|
||||
RootBeanDefinition definition = new RootBeanDefinition();
|
||||
definition.setTargetType(
|
||||
ResolvableType.forClassWithGenerics(producer, byte[].class, byte[].class));
|
||||
definition.setInstanceSupplier(BootstrapCapabilityReachabilitySystemTest::noOpKafkaProducer);
|
||||
((BeanDefinitionRegistry) context.getBeanFactory())
|
||||
.registerBeanDefinition("kafkaSeamProducer", definition);
|
||||
context
|
||||
.getBeanFactory()
|
||||
.registerSingleton("reachabilityKafkaSender", (KafkaSender) message -> {});
|
||||
}
|
||||
|
||||
private static Class<?> loadKafkaProducerType() {
|
||||
try {
|
||||
return Class.forName("org.apache.kafka.clients.producer.Producer");
|
||||
} catch (ClassNotFoundException missingKafkaClient) {
|
||||
throw new LinkageError("shipped Kafka client is not loadable", missingKafkaClient);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object noOpKafkaProducer() {
|
||||
Class<?> producer = loadKafkaProducerType();
|
||||
return Proxy.newProxyInstance(
|
||||
producer.getClassLoader(),
|
||||
new Class<?>[] {producer},
|
||||
(proxy, method, arguments) -> {
|
||||
if (method.getName().equals("toString")) {
|
||||
return "reachability-noop-kafka-producer";
|
||||
}
|
||||
if (method.getName().equals("hashCode")) {
|
||||
return System.identityHashCode(proxy);
|
||||
}
|
||||
if (method.getName().equals("equals")) {
|
||||
return proxy == arguments[0];
|
||||
}
|
||||
return null;
|
||||
});
|
||||
@Test
|
||||
void shippedCompositionRefusesABrokerItDidNotCompose() {
|
||||
// The build composition question, asked of the artifact rather than of a build file. The core
|
||||
// messaging starter is broker-neutral and neither broker starter ships, so selecting one is a
|
||||
// deployment asking for a transport it did not compose. Before the selector checked for the
|
||||
// provider configuration it checked only for the client library — which a deployment can hold
|
||||
// transitively — and the refusal arrived as Spring reporting a missing .class file.
|
||||
assertThatThrownBy(
|
||||
() ->
|
||||
ShippedCompositionHarness.shippedComposition("local")
|
||||
.run(
|
||||
ShippedCompositionHarness.allOffWithH2(
|
||||
"refuses_uncomposed_broker",
|
||||
"--app.messaging.enabled=true",
|
||||
"--app.messaging.broker=kafka")))
|
||||
.rootCause()
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("messaging-spring-boot-starter-kafka")
|
||||
.hasMessageContaining("broker-neutral");
|
||||
}
|
||||
}
|
||||
|
||||
+12
-3
@@ -43,9 +43,18 @@ class DependencyErrorStartupContractTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the outbox without a broker is refused, naming the messaging switch")
|
||||
void outboxWithoutMessagingNamesTheMessagingSwitch() {
|
||||
assertRefusedNaming(List.of("--ca-skeleton.outbox.enabled=true"), "app.messaging.enabled");
|
||||
@DisplayName("the relay without a broker is refused, naming the messaging switch")
|
||||
void relayingOutboxWithoutMessagingNamesTheMessagingSwitch() {
|
||||
// The relay, not the capability. An outbox with the relay off writes rows and publishes
|
||||
// nothing, which is how an operator parks events until a transport exists; demanding messaging
|
||||
// for the capability refused that configuration and, in a broker-neutral artifact, left the
|
||||
// outbox with no reachable configuration at all.
|
||||
assertRefusedNaming(
|
||||
List.of(
|
||||
"--ca-skeleton.outbox.enabled=true",
|
||||
"--ca-skeleton.outbox.relay-enabled=true",
|
||||
"--ca-skeleton.persistence-jpa.enabled=true"),
|
||||
"app.messaging.enabled");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -13,7 +13,8 @@ import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
|
||||
/**
|
||||
* With all registered master switches off, the application must hold nothing that belongs to any of them.
|
||||
* With all registered master switches off, the application must hold nothing that belongs to any of
|
||||
* them.
|
||||
*
|
||||
* <p>This boots the real composition root rather than an {@code ApplicationContextRunner}, because
|
||||
* the two things most likely to defeat a master switch are exactly the two a runner does not have:
|
||||
|
||||
+4
-2
@@ -5,8 +5,8 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import dev.caskeleton.adapter.outbound.messaging.core.DisabledMessagePublisher;
|
||||
import dev.caskeleton.adapter.outbound.messaging.core.OutboundMessage;
|
||||
import dev.caskeleton.adapter.outbound.notification.core.RoutingNotifier;
|
||||
import dev.caskeleton.application.notification.NotificationChannel;
|
||||
import dev.caskeleton.application.notification.Notification;
|
||||
import dev.caskeleton.application.notification.NotificationChannel;
|
||||
import dev.caskeleton.shared.error.AdapterDisabledException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -39,7 +39,9 @@ class DisabledAdapterSentinelTest {
|
||||
void unwiredNotificationEmailFailsFast() {
|
||||
// router-fail-fast: no providers, no routes → AdapterDisabledException on first call
|
||||
assertThatThrownBy(
|
||||
() -> new RoutingNotifier(List.of(), Map.of()).notify(NotificationChannel.EMAIL, STUB_NOTIFICATION))
|
||||
() ->
|
||||
new RoutingNotifier(List.of(), Map.of())
|
||||
.notify(NotificationChannel.EMAIL, STUB_NOTIFICATION))
|
||||
.isInstanceOf(AdapterDisabledException.class)
|
||||
.extracting("adapterName")
|
||||
.isEqualTo("notification");
|
||||
|
||||
+3
-2
@@ -27,8 +27,8 @@ import dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackClient;
|
||||
import dev.caskeleton.adapter.outbound.notification.slack.webhook.SlackNotificationAdapterConfig;
|
||||
import dev.caskeleton.adapter.outbound.support.OutboundSupportConfig;
|
||||
import dev.caskeleton.application.filepublication.FilePublicationPort;
|
||||
import dev.caskeleton.application.notification.NotificationChannel;
|
||||
import dev.caskeleton.application.notification.Notification;
|
||||
import dev.caskeleton.application.notification.NotificationChannel;
|
||||
import dev.caskeleton.application.notification.NotificationPort;
|
||||
import dev.caskeleton.application.outbox.OutboxMessagePublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxRelayFailureReportPort;
|
||||
@@ -103,7 +103,8 @@ class OptionalAdapterBeanGatingTest {
|
||||
// notification D4: zero providers boot fine, unbound route fails fast in RoutingNotifier
|
||||
NotificationPort notificationPort = context.getBean(NotificationPort.class);
|
||||
assertThat(notificationPort).isInstanceOf(RoutingNotifier.class);
|
||||
assertThatThrownBy(() -> notificationPort.notify(NotificationChannel.EMAIL, STUB_NOTIFICATION))
|
||||
assertThatThrownBy(
|
||||
() -> notificationPort.notify(NotificationChannel.EMAIL, STUB_NOTIFICATION))
|
||||
.isInstanceOf(AdapterDisabledException.class)
|
||||
.extracting("adapterName")
|
||||
.isEqualTo("notification");
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class AdapterActivationReportShapeTest {
|
||||
}
|
||||
environment.setProperty("ca-skeleton.outbox.enabled", "true");
|
||||
environment.setProperty("ca-skeleton.capabilities.idempotency.provider", "jdbc");
|
||||
environment.setProperty("ca-skeleton.lock.multi-instance-enabled", "true");
|
||||
environment.setProperty("ca-skeleton.runtime.multi-instance-enabled", "true");
|
||||
environment.setProperty("app.fileserver-platform.enabled", "true");
|
||||
environment.setProperty("spring.datasource.url", "jdbc:postgresql://secret-host:5432/db");
|
||||
environment.setProperty("spring.datasource.password", "hunter2");
|
||||
|
||||
+26
-4
@@ -26,9 +26,12 @@ class CapabilityDependencyValidatorTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the outbox needs both a database and a broker, and names each")
|
||||
void outboxNeedsPersistenceAndMessaging() {
|
||||
MockEnvironment environment = allOff().withProperty("ca-skeleton.outbox.enabled", "true");
|
||||
@DisplayName("the outbox needs a database, and a relaying outbox also needs a broker")
|
||||
void outboxNeedsPersistenceAndARelayingOutboxNeedsMessaging() {
|
||||
MockEnvironment environment =
|
||||
allOff()
|
||||
.withProperty("ca-skeleton.outbox.enabled", "true")
|
||||
.withProperty("ca-skeleton.outbox.relay-enabled", "true");
|
||||
|
||||
List<String> violations = CapabilityDependencyValidator.violations(environment);
|
||||
|
||||
@@ -38,6 +41,22 @@ class CapabilityDependencyValidatorTest {
|
||||
.anySatisfy(v -> assertThat(v).contains("app.messaging.enabled"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an outbox with the relay off stores rows and demands no transport")
|
||||
void outboxWithoutARelayDoesNotDemandMessaging() {
|
||||
// The two coherent configurations OutboxRelayBrokerRequirementValidator names are "a relay with
|
||||
// a broker" and "no relay". Requiring messaging for the capability rather than for the relay
|
||||
// refused the second one, and in a broker-neutral artifact — which is what the default build
|
||||
// composition produces — it left the outbox with no reachable configuration at all.
|
||||
MockEnvironment environment =
|
||||
allOff()
|
||||
.withProperty("ca-skeleton.outbox.enabled", "true")
|
||||
.withProperty("ca-skeleton.outbox.relay-enabled", "false")
|
||||
.withProperty("ca-skeleton.persistence-jpa.enabled", "true");
|
||||
|
||||
assertThat(CapabilityDependencyValidator.violations(environment)).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the relay is not a capability switch")
|
||||
void relayWithoutTheCapabilityIsRejected() {
|
||||
@@ -203,7 +222,10 @@ class CapabilityDependencyValidatorTest {
|
||||
@DisplayName(
|
||||
"requireSatisfied raises one typed adapter-enablement failure containing every dependency")
|
||||
void requireSatisfiedAggregatesThroughTheTypedStartupContext() {
|
||||
MockEnvironment environment = allOff().withProperty("ca-skeleton.outbox.enabled", "true");
|
||||
MockEnvironment environment =
|
||||
allOff()
|
||||
.withProperty("ca-skeleton.outbox.enabled", "true")
|
||||
.withProperty("ca-skeleton.outbox.relay-enabled", "true");
|
||||
|
||||
assertThatThrownBy(() -> CapabilityDependencyValidator.requireSatisfied(environment))
|
||||
.isInstanceOfSatisfying(
|
||||
|
||||
-144
@@ -1,144 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import dev.caskeleton.application.fileserver.admin.ContentReferenceLedger;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileMetadataStore;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.FileQuotaService;
|
||||
import dev.caskeleton.application.fileserver.api.metadata.UploadSessionStore;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupQueue;
|
||||
import dev.caskeleton.application.fileserver.cleanup.QuotaReclaimGateway;
|
||||
import dev.caskeleton.application.fileserver.recovery.RecoveryQueue;
|
||||
import dev.caskeleton.application.fileserver.recovery.StagingUploadLocator;
|
||||
import dev.caskeleton.application.fileserver.upload.QuotaCommitGateway;
|
||||
import dev.caskeleton.application.transaction.PolicyTransactionPort;
|
||||
import dev.caskeleton.application.transaction.TransactionRequest;
|
||||
import dev.caskeleton.application.transaction.TransactionResult;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.Optional;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
/**
|
||||
* The persistence side of the fileserver assembly, as stand-ins.
|
||||
*
|
||||
* <p>The point of an assembly test is that every constructor argument the composition root needs
|
||||
* can be satisfied, in order, without a null. Real stores would drag a database into a test whose
|
||||
* subject is the wiring; the stores prove their own behaviour in their own modules.
|
||||
*
|
||||
* <p>The storage root is a real directory because the capability probe genuinely creates, renames,
|
||||
* and deletes files in it at startup — that check is exactly what an assembly test must not stub
|
||||
* out.
|
||||
*/
|
||||
public abstract class FileserverAssemblyFixture {
|
||||
|
||||
private static final Path STORAGE_ROOT = createStorageRoot();
|
||||
|
||||
/** Absolute path of the probe-able storage root shared by the assembly tests. */
|
||||
public static String storageRoot() {
|
||||
return STORAGE_ROOT.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* A boundary that runs its action inline.
|
||||
*
|
||||
* <p>The application services now open their own transactions, so the composition root cannot be
|
||||
* assembled without one. Nothing here reaches a database, so the boundary has nothing to protect
|
||||
* — what this proves is that the wiring supplies one at all.
|
||||
*/
|
||||
@Bean
|
||||
PolicyTransactionPort transactions() {
|
||||
return new PolicyTransactionPort() {
|
||||
@Override
|
||||
public <T> T inWrite(java.util.function.Supplier<T> action) {
|
||||
return action.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T inRootWrite(java.util.function.Supplier<T> action) {
|
||||
return action.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T inRead(java.util.function.Supplier<T> action) {
|
||||
return action.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> T inNew(java.util.function.Supplier<T> action) {
|
||||
return action.get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> TransactionResult<T> inTransaction(
|
||||
TransactionRequest request, java.util.function.Supplier<T> action) {
|
||||
return new TransactionResult.Committed<>(action.get(), request.operationId());
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Clock fixedClock() {
|
||||
return Clock.fixed(Instant.parse("2026-08-08T09:00:00Z"), ZoneOffset.UTC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FileMetadataStore metadataStore() {
|
||||
return mock(FileMetadataStore.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public UploadSessionStore uploadSessionStore() {
|
||||
return mock(UploadSessionStore.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FileQuotaService fileQuotaService() {
|
||||
return mock(FileQuotaService.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CleanupQueue cleanupQueue() {
|
||||
return mock(CleanupQueue.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RecoveryQueue recoveryQueue() {
|
||||
return mock(RecoveryQueue.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public QuotaCommitGateway quotaCommitGateway() {
|
||||
return mock(QuotaCommitGateway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public QuotaReclaimGateway quotaReclaimGateway() {
|
||||
return mock(QuotaReclaimGateway.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ContentReferenceLedger contentReferenceLedger() {
|
||||
return key -> false;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public StagingUploadLocator stagingUploadLocator() {
|
||||
return fileId -> Optional.empty();
|
||||
}
|
||||
|
||||
private static Path createStorageRoot() {
|
||||
try {
|
||||
Path root = Files.createTempDirectory("fileserver-assembly");
|
||||
root.toFile().deleteOnExit();
|
||||
return root.toAbsolutePath();
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("assembly fixture needs a real storage root", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
-270
@@ -1,270 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.bind.BindHandler;
|
||||
import org.springframework.boot.context.properties.bind.Bindable;
|
||||
import org.springframework.boot.context.properties.bind.Binder;
|
||||
import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
|
||||
/**
|
||||
* Keeps the support claims and the endpoint list honest.
|
||||
*
|
||||
* <p>Documentation drifts silently: a level stays "Stable" long after its job was renamed, and an
|
||||
* endpoint ships without ever reaching the contract file. Both are only caught by a test, because
|
||||
* neither produces a compile error or a failing behaviour test. This one reads the documents and
|
||||
* the sources and fails when they disagree.
|
||||
*/
|
||||
class FileserverDocumentationCoverageTest {
|
||||
|
||||
private static final Pattern CI_JOB = Pattern.compile("`(fileserver-[a-z0-9-]+)`");
|
||||
private static final Pattern WORKFLOW_JOB = Pattern.compile("^ {2}([a-z0-9-]+):\\s*$");
|
||||
private static final Pattern MAPPING_PATH =
|
||||
Pattern.compile("\"(/v1/[^\"]*|/internal/fileserver[^\"]*)\"");
|
||||
|
||||
@Test
|
||||
void everySupportClaimNamesAJobThatExists() throws IOException {
|
||||
List<String> claimed =
|
||||
referencedCiJobs(repositoryRoot().resolve("docs/fileserver/support-matrix.md"));
|
||||
List<String> defined = definedWorkflowJobs();
|
||||
|
||||
assertThat(claimed)
|
||||
.as("a support level whose evidence job does not exist is an unbacked claim")
|
||||
.isNotEmpty()
|
||||
.allSatisfy(job -> assertThat(defined).contains(job));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyPublicEndpointAppearsInTheHttpContract() throws IOException {
|
||||
String contract =
|
||||
normalizePathVariables(
|
||||
Files.readString(repositoryRoot().resolve("docs/fileserver/http-contract.md")));
|
||||
List<String> declared = declaredMappingPaths();
|
||||
|
||||
assertThat(declared).isNotEmpty();
|
||||
assertThat(declared)
|
||||
.as("an endpoint that ships undocumented is an undiscoverable contract")
|
||||
.allSatisfy(path -> assertThat(contract).contains(path));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyRunbookNamesAConcreteSignalAndCommand() throws IOException {
|
||||
String operations = Files.readString(repositoryRoot().resolve("docs/fileserver/operations.md"));
|
||||
|
||||
List<String> requiredRunbooks =
|
||||
List.of(
|
||||
"Storage full",
|
||||
"Orphan growth",
|
||||
"Verification backlog",
|
||||
"NFS ambiguity",
|
||||
"PVC remount",
|
||||
"Nginx delegation failure",
|
||||
"Cleanup backlog");
|
||||
|
||||
assertThat(requiredRunbooks).allSatisfy(runbook -> assertThat(operations).contains(runbook));
|
||||
assertThat(operations)
|
||||
.as("a runbook without a metric name has no trigger")
|
||||
.contains("fileserver.quota")
|
||||
.contains("fileserver.cleanup")
|
||||
.contains("fileserver.verification.queue")
|
||||
.contains("fileserver.download.delegation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSupportMatrixStatesWhatIsNotClaimed() throws IOException {
|
||||
String matrix = Files.readString(repositoryRoot().resolve("docs/fileserver/support-matrix.md"));
|
||||
|
||||
assertThat(matrix)
|
||||
.as("an omitted capability reads as an unstated claim; absence must be explicit")
|
||||
.contains("Explicitly not claimed")
|
||||
.contains("ReadWriteMany");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExperimentalProtocolIsLabelledAsSuchWhereverItAppears() throws IOException {
|
||||
String matrix = Files.readString(repositoryRoot().resolve("docs/fileserver/support-matrix.md"));
|
||||
String contract =
|
||||
Files.readString(repositoryRoot().resolve("docs/fileserver/http-contract.md"));
|
||||
|
||||
assertThat(matrix).contains("draft-12").contains("Experimental");
|
||||
assertThat(contract).contains("draft12").contains("Experimental");
|
||||
}
|
||||
|
||||
/**
|
||||
* Every documented setting must be a setting that exists.
|
||||
*
|
||||
* <p>Checking that a document merely mentions a word cannot catch the drift that matters: a key
|
||||
* renamed in the settings record leaves the old name in the documentation, and a reader
|
||||
* configures something no binder will accept. Binding each documented key strictly settles it —
|
||||
* the same handler the auto-configuration uses refuses an element it cannot place.
|
||||
*/
|
||||
@Test
|
||||
void everyDocumentedSettingKeyStillBinds() throws IOException {
|
||||
List<String> documented =
|
||||
documentedSettingKeys(repositoryRoot().resolve("docs/fileserver/configuration.md"));
|
||||
|
||||
assertThat(documented).as("the configuration reference must list keys").isNotEmpty();
|
||||
|
||||
Map<String, Object> properties = new LinkedHashMap<>();
|
||||
for (String key : documented) {
|
||||
properties.put(FileserverPlatformSettings.PREFIX + "." + key, placeholderFor(key));
|
||||
}
|
||||
StandardEnvironment environment = new StandardEnvironment();
|
||||
environment.getPropertySources().addFirst(new MapPropertySource("documented", properties));
|
||||
|
||||
assertThatCode(
|
||||
() ->
|
||||
Binder.get(environment)
|
||||
.bind(
|
||||
FileserverPlatformSettings.PREFIX,
|
||||
Bindable.of(FileserverPlatformSettings.class),
|
||||
new NoUnboundElementsBindHandler(BindHandler.DEFAULT))
|
||||
.orElseThrow(() -> new AssertionError("documented settings did not bind")))
|
||||
.as("a documented key that binds to nothing is a reader following instructions to nowhere")
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Table keys from the configuration reference, minus the ones already qualified by a section.
|
||||
*
|
||||
* <p>The document writes a bare key inside a per-section table (for example {@code root} under
|
||||
* "Storage") and a qualified one elsewhere ({@code upload.ttl}); only the qualified form can be
|
||||
* bound without reconstructing the section context, so the bare ones are read with their heading.
|
||||
*/
|
||||
private static List<String> documentedSettingKeys(Path configuration) throws IOException {
|
||||
List<String> keys = new ArrayList<>();
|
||||
String section = "";
|
||||
for (String line : Files.readAllLines(configuration)) {
|
||||
Matcher heading = SECTION_KEY.matcher(line);
|
||||
if (heading.find()) {
|
||||
section = heading.group(1);
|
||||
continue;
|
||||
}
|
||||
Matcher matcher = TABLE_KEY.matcher(line);
|
||||
if (matcher.find()) {
|
||||
String key = matcher.group(1);
|
||||
keys.add(key.contains(".") || section.isEmpty() ? key : section + "." + key);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* A value the binder will accept for any key, so the test measures existence and not format.
|
||||
*
|
||||
* <p>Format is already the settings record's own business, and its constructors are exercised by
|
||||
* the auto-configuration tests.
|
||||
*/
|
||||
private static Object placeholderFor(String key) {
|
||||
return DEFAULTS.getOrDefault(key, "1");
|
||||
}
|
||||
|
||||
private static final Pattern TABLE_KEY = Pattern.compile("^\\| `([a-z0-9.-]+)` \\|");
|
||||
private static final Pattern SECTION_KEY = Pattern.compile("^## .*— `([a-z-]+)`");
|
||||
|
||||
/** Keys whose type will not accept a bare "1". */
|
||||
private static final Map<String, Object> DEFAULTS =
|
||||
Map.ofEntries(
|
||||
Map.entry("storage.root", "/var/lib/backend/files"),
|
||||
Map.entry("storage.publish-mode", "atomic-move-preferred"),
|
||||
Map.entry("storage.buffer-size", "128KB"),
|
||||
Map.entry("storage.forbidden-root-ancestors", "/app"),
|
||||
Map.entry("upload.max-file-size", "100MB"),
|
||||
Map.entry("upload.max-request-size", "100MB"),
|
||||
Map.entry("upload.initial-reservation", "1MB"),
|
||||
Map.entry("upload.ttl", "1h"),
|
||||
Map.entry("upload.reservation-ttl", "1h"),
|
||||
Map.entry("upload.lease-duration", "30s"),
|
||||
Map.entry("upload.require-content-length", "false"),
|
||||
Map.entry("security.access-policy", "role-based"),
|
||||
Map.entry("security.read-roles", "ROLE_FILE_READ"),
|
||||
Map.entry("security.write-roles", "ROLE_FILE_WRITE"),
|
||||
Map.entry("security.admin-roles", "ROLE_FILE_ADMIN"),
|
||||
// The water marks are cross-validated against each other, so a shared placeholder
|
||||
// would fail the record's own invariant rather than the documentation check.
|
||||
Map.entry("quota.soft-high-water", "0.70"),
|
||||
Map.entry("quota.hard-high-water", "0.85"));
|
||||
|
||||
private static List<String> referencedCiJobs(Path supportMatrix) throws IOException {
|
||||
List<String> jobs = new ArrayList<>();
|
||||
Matcher matcher = CI_JOB.matcher(Files.readString(supportMatrix));
|
||||
while (matcher.find()) {
|
||||
jobs.add(matcher.group(1));
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
/** Job identifiers across every fileserver workflow, read from the two-space indent level. */
|
||||
private static List<String> definedWorkflowJobs() throws IOException {
|
||||
List<String> jobs = new ArrayList<>();
|
||||
Path workflows = repositoryRoot().resolve(".github/workflows");
|
||||
try (Stream<Path> files = Files.list(workflows)) {
|
||||
for (Path file :
|
||||
files.filter(path -> path.getFileName().toString().startsWith("fileserver-")).toList()) {
|
||||
for (String line : Files.readAllLines(file)) {
|
||||
Matcher matcher = WORKFLOW_JOB.matcher(line);
|
||||
if (matcher.matches()) {
|
||||
jobs.add(matcher.group(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
/** Literal request-mapping paths declared by the fileserver transport sources. */
|
||||
private static List<String> declaredMappingPaths() throws IOException {
|
||||
List<String> paths = new ArrayList<>();
|
||||
Path fileserverWeb =
|
||||
repositoryRoot()
|
||||
.resolve(
|
||||
"src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/fileserver");
|
||||
try (Stream<Path> sources = Files.walk(fileserverWeb)) {
|
||||
for (Path source : sources.filter(path -> path.toString().endsWith(".java")).toList()) {
|
||||
String body = Files.readString(source);
|
||||
Matcher matcher = MAPPING_PATH.matcher(body);
|
||||
while (matcher.find()) {
|
||||
paths.add(normalizePathVariables(matcher.group(1)));
|
||||
}
|
||||
}
|
||||
}
|
||||
return paths.stream().distinct().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduces every path variable to one placeholder.
|
||||
*
|
||||
* <p>Both sides are normalized the same way, so renaming a handler's path variable — which
|
||||
* changes nothing a client observes — cannot fail this test.
|
||||
*/
|
||||
private static String normalizePathVariables(String text) {
|
||||
return text.replaceAll("\\{[a-zA-Z][a-zA-Z0-9]*}", "{id}");
|
||||
}
|
||||
|
||||
/** Repository root, resolved from the Gradle working directory rather than assumed. */
|
||||
private static Path repositoryRoot() {
|
||||
Path working = Path.of("").toAbsolutePath();
|
||||
Path candidate = working;
|
||||
while (candidate != null && !Files.isDirectory(candidate.resolve(".github/workflows"))) {
|
||||
candidate = candidate.getParent();
|
||||
}
|
||||
if (candidate == null) {
|
||||
throw new IllegalStateException("repository root not found above " + working);
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
-264
@@ -1,264 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.BlockingTransferExecutor;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.FileserverWebProperties;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.config.MvcTransferExecutorConfiguration;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.http.HttpDownloadPolicy;
|
||||
import dev.caskeleton.adapter.inbound.web.fileserver.nginx.NginxDelegationProperties;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverMetricsPort;
|
||||
import dev.caskeleton.application.fileserver.observability.SafeFileFingerprint;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadPolicy;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.core.task.TaskDecorator;
|
||||
|
||||
class FileserverPlatformAutoConfigurationTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(FileserverPlatformAutoConfiguration.class))
|
||||
.withUserConfiguration(SupportingBeansConfiguration.class);
|
||||
|
||||
@Test
|
||||
void disabledCapabilityIgnoresDetailAndSubFeatureSettings() {
|
||||
runner
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.upload.ttl=not-a-duration",
|
||||
"app.fileserver-platform.storage.buffer-size=not-a-size",
|
||||
"app.fileserver-platform.storage.root=relative/path",
|
||||
"app.fileserver-platform.admin.enabled=true",
|
||||
"app.fileserver-platform.tus.enabled=true",
|
||||
"app.fileserver-platform.httpbis-draft12.enabled=true",
|
||||
"app.fileserver-platform.cleanup.enabled=true")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).doesNotHaveBean(FileserverWebProperties.class);
|
||||
assertThat(context).doesNotHaveBean(BlockingTransferExecutor.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverMetricsPort.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverPlatformSettings.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverCleanupWorker.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A misspelled key is a configuration error, not a silently ignored one.
|
||||
*
|
||||
* <p>Dropping {@code uplaod.max-file-size} leaves the node running the default limit while its
|
||||
* configuration file says otherwise — the kind of divergence a file capability should never make
|
||||
* an operator discover from an incident.
|
||||
*/
|
||||
@Test
|
||||
void anUnknownKeyUnderThePrefixIsRefused() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver-platform.uplaod.max-file-size=1MB")
|
||||
.run(context -> assertThat(context).hasFailed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCorePoolLargerThanItsMaximumIsRefused() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.transfer.core-size=64",
|
||||
"app.fileserver-platform.transfer.max-size=8")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasStackTraceContaining("transfer.core-size"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSoftWaterMarkAtOrAboveTheHardOneIsRefused() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.quota.soft-high-water=0.90",
|
||||
"app.fileserver-platform.quota.hard-high-water=0.85")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasStackTraceContaining("soft-high-water"));
|
||||
}
|
||||
|
||||
/** The byte ceiling applies to the default single-range profile, not only to multi-range. */
|
||||
@Test
|
||||
void theRangeByteCeilingAppliesToTheSingleRangeProfile() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver-platform.download.max-range-bytes=4MB")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context.getBean(HttpDownloadPolicy.class).rangePolicy().maxTotalBytes())
|
||||
.isEqualTo(4L * 1024 * 1024));
|
||||
}
|
||||
|
||||
/**
|
||||
* A master switch that is not a boolean must fail loudly and early.
|
||||
*
|
||||
* <p>Spring's property condition treats anything that is not the expected value as "no", so
|
||||
* {@code enabled=yes} silently disables the capability. A deployment that meant to turn the
|
||||
* Fileserver on then serves 404s with a configuration file that says otherwise, and nothing in
|
||||
* the startup log mentions it.
|
||||
*/
|
||||
@Test
|
||||
void aMasterSwitchThatIsNotABooleanDoesNotSilentlyEnableTheCapability() {
|
||||
runner
|
||||
.withPropertyValues("app.fileserver-platform.enabled=yes")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).doesNotHaveBean(FileserverPlatformSettings.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverWebProperties.class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The three file capabilities share nothing but a word in their names.
|
||||
*
|
||||
* <p>They previously shared a configuration prefix, so switching the HTTP platform on also
|
||||
* switched on the R1 publication and its directory initialisation. Each namespace must now move
|
||||
* exactly one capability.
|
||||
*/
|
||||
/**
|
||||
* A delegation whose internal mapping does not round-trip must not start.
|
||||
*
|
||||
* <p>Nginx answers an unresolvable internal redirect with an empty {@code 200}: the client
|
||||
* believes it received the file. Failing at startup is the only point at which that is visible.
|
||||
*/
|
||||
@Test
|
||||
void nginxDelegationWithAnUnusableInternalPrefixFailsStartup() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.nginx.enabled=true",
|
||||
"app.fileserver-platform.nginx.internal-prefix=files/")
|
||||
.run(context -> assertThat(context).hasFailed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void enabledDefaultsAssembleTheExpectedRuntime() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver.enabled=false", "app.file-export.enabled=false")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(FileserverPlatformSettings.class);
|
||||
assertThat(context).hasSingleBean(FileserverWebProperties.class);
|
||||
assertThat(context).hasSingleBean(UploadPolicy.class);
|
||||
assertThat(context).hasSingleBean(HttpDownloadPolicy.class);
|
||||
assertThat(context).hasSingleBean(BlockingTransferExecutor.class);
|
||||
assertThat(context).hasSingleBean(SafeFileFingerprint.class);
|
||||
|
||||
HttpDownloadPolicy download = context.getBean(HttpDownloadPolicy.class);
|
||||
assertThat(download.cacheControl()).isEqualTo("private, no-store");
|
||||
assertThat(download.inlineAllowed()).isFalse();
|
||||
assertThat(download.rangePolicy().allowsMultipleRanges()).isFalse();
|
||||
assertThat(context.getBean(NginxDelegationProperties.class).enabled()).isFalse();
|
||||
assertThat(context.getBean(FileserverWebProperties.class).maxBatchParts())
|
||||
.isEqualTo(16);
|
||||
|
||||
assertThat(
|
||||
context.getBean(
|
||||
dev.caskeleton.adapter.inbound.web.fileserver.config
|
||||
.TransferExecutorProperties.class))
|
||||
.satisfies(
|
||||
properties -> {
|
||||
assertThat(properties.coreSize()).isEqualTo(8);
|
||||
assertThat(properties.maxSize()).isEqualTo(32);
|
||||
assertThat(properties.queueCapacity()).isEqualTo(64);
|
||||
});
|
||||
|
||||
assertThat(context.getEnvironment().getProperty("app.fileserver.enabled"))
|
||||
.isEqualTo("false");
|
||||
assertThat(context.getEnvironment().getProperty("app.file-export.enabled"))
|
||||
.isEqualTo("false");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnkeyedTelemetryFingerprintIsRefusedRatherThanDowngraded() {
|
||||
runner
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.enabled=true",
|
||||
"app.fileserver-platform.security.access-policy=role-based",
|
||||
"app.fileserver-platform.storage.root=" + FileserverAssemblyFixture.storageRoot())
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasStackTraceContaining("fingerprint-key"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void propertiesOverrideTheDefaults() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.download.inline-allowed=true",
|
||||
"app.fileserver-platform.download.max-ranges=4",
|
||||
"app.fileserver-platform.upload.max-file-size=1MB",
|
||||
"app.fileserver-platform.upload.max-request-size=2MB",
|
||||
"app.fileserver-platform.upload.initial-reservation=512KB",
|
||||
"app.fileserver-platform.nginx.enabled=true")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context.getBean(HttpDownloadPolicy.class).inlineAllowed()).isTrue();
|
||||
assertThat(context.getBean(HttpDownloadPolicy.class).rangePolicy().maxRanges())
|
||||
.isEqualTo(4);
|
||||
assertThat(context.getBean(UploadPolicy.class).maximumFileSize())
|
||||
.isEqualTo(1024L * 1024);
|
||||
assertThat(context.getBean(NginxDelegationProperties.class).enabled()).isTrue();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void metricsCanBeTurnedOffWithoutDisablingTheCapability() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver-platform.observability.metrics-enabled=false")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasSingleBean(FileserverWebProperties.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverMetricsPort.class);
|
||||
});
|
||||
}
|
||||
|
||||
private ApplicationContextRunner enabled() {
|
||||
return runner.withPropertyValues(
|
||||
"app.fileserver-platform.enabled=true",
|
||||
"app.fileserver-platform.observability.fingerprint-key=a-sixteen-byte-key!!",
|
||||
"app.fileserver-platform.security.access-policy=role-based",
|
||||
"app.fileserver-platform.storage.root=" + FileserverAssemblyFixture.storageRoot());
|
||||
}
|
||||
|
||||
/**
|
||||
* The collaborators the composition root normally supplies.
|
||||
*
|
||||
* <p>A real registry, so the Micrometer implementation is exercised rather than mocked away, and
|
||||
* a real decorator, because the transfer pool refuses to be built without one. The persistence
|
||||
* ports are stand-ins: this test proves the assembly graph closes, and the stores prove their own
|
||||
* behaviour in their own module.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(MvcTransferExecutorConfiguration.class)
|
||||
static class SupportingBeansConfiguration extends FileserverAssemblyFixture {
|
||||
|
||||
@Bean
|
||||
MeterRegistry meterRegistry() {
|
||||
return new SimpleMeterRegistry();
|
||||
}
|
||||
|
||||
@Bean
|
||||
TaskDecorator taskDecorator() {
|
||||
return runnable -> runnable;
|
||||
}
|
||||
}
|
||||
}
|
||||
-127
@@ -1,127 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.context.properties.bind.BindHandler;
|
||||
import org.springframework.boot.context.properties.bind.Bindable;
|
||||
import org.springframework.boot.context.properties.bind.Binder;
|
||||
import org.springframework.boot.context.properties.bind.handler.NoUnboundElementsBindHandler;
|
||||
import org.springframework.core.env.StandardEnvironment;
|
||||
import org.springframework.core.env.SystemEnvironmentPropertySource;
|
||||
|
||||
/**
|
||||
* Closes the loop between the shipped {@code .env} and the typed settings.
|
||||
*
|
||||
* <p>The Gradle {@code verifyEnvKeys} check compares three text files, which proves a key is
|
||||
* declared everywhere but not that anything reads it. A key can be spelled correctly in {@code
|
||||
* .env}, {@code application.yml} and the registry and still map to no field at all — which is
|
||||
* exactly how a documented setting ends up doing nothing.
|
||||
*
|
||||
* <p>The names go in as real environment variables rather than as hand-translated property names,
|
||||
* so what is under test is the mapping the runtime actually performs — including the cases where an
|
||||
* underscore becomes a hyphen inside one property name rather than a level of nesting. Binding
|
||||
* strictly then settles the rest: the same handler the auto-configuration uses refuses an element
|
||||
* it cannot place, so a key with no field fails here instead of in production.
|
||||
*/
|
||||
class FileserverPlatformEnvRoundTripTest {
|
||||
|
||||
private static final String ENV_PREFIX = "APP_FILESERVER_PLATFORM_";
|
||||
|
||||
@Test
|
||||
void everyDeclaredEnvKeyBindsToAField() {
|
||||
Map<String, Object> environmentVariables = declaredPlatformEnvironment();
|
||||
|
||||
assertThat(environmentVariables)
|
||||
.as("src/.env must declare the platform's operational surface")
|
||||
.isNotEmpty();
|
||||
|
||||
FileserverPlatformSettings bound = bindStrictly(environmentVariables);
|
||||
|
||||
assertThat(bound.enabled()).isFalse();
|
||||
assertThat(bound.storage().root().isAbsolute()).isTrue();
|
||||
assertThat(bound.upload().maxRequestSize().toBytes())
|
||||
.isGreaterThanOrEqualTo(bound.upload().maxFileSize().toBytes());
|
||||
assertThat(bound.security().readRoles()).containsExactly("ROLE_FILE_READ");
|
||||
assertThat(bound.storage().forbiddenRootAncestors()).isNotEmpty();
|
||||
}
|
||||
|
||||
/** The shipped defaults must be the conservative ones, in the file operators actually copy. */
|
||||
@Test
|
||||
void theShippedEnvironmentKeepsEveryOptionalSurfaceOff() {
|
||||
Map<String, Object> environmentVariables = declaredPlatformEnvironment();
|
||||
|
||||
assertThat(environmentVariables)
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_ADMIN_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_CLEANUP_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_TUS_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_HTTPBIS_DRAFT12_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_NGINX_ENABLED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_DOWNLOAD_INLINE_ALLOWED", "false")
|
||||
.containsEntry("APP_FILESERVER_PLATFORM_SECURITY_ACCESS_POLICY", "required");
|
||||
}
|
||||
|
||||
private static FileserverPlatformSettings bindStrictly(Map<String, Object> environmentVariables) {
|
||||
StandardEnvironment environment = new StandardEnvironment();
|
||||
environment
|
||||
.getPropertySources()
|
||||
.addFirst(
|
||||
new SystemEnvironmentPropertySource(
|
||||
StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, environmentVariables));
|
||||
BindHandler strict = new NoUnboundElementsBindHandler(BindHandler.DEFAULT);
|
||||
return Binder.get(environment)
|
||||
.bind(
|
||||
FileserverPlatformSettings.PREFIX,
|
||||
Bindable.of(FileserverPlatformSettings.class),
|
||||
strict)
|
||||
.orElseThrow(
|
||||
() -> new AssertionError("the declared environment did not bind to any settings"));
|
||||
}
|
||||
|
||||
private static Map<String, Object> declaredPlatformEnvironment() {
|
||||
Map<String, Object> variables = new LinkedHashMap<>();
|
||||
for (String line : readEnvFile()) {
|
||||
String trimmed = line.trim();
|
||||
if (!trimmed.startsWith(ENV_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
int separator = trimmed.indexOf('=');
|
||||
String value = trimmed.substring(separator + 1);
|
||||
if (value.isBlank()) {
|
||||
// A blank secret is a deliberate placeholder, not a value the binder should see.
|
||||
continue;
|
||||
}
|
||||
variables.put(trimmed.substring(0, separator), value);
|
||||
}
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the repository's tracked {@code src/.env.example}.
|
||||
*
|
||||
* <p>A copy in the test resources would drift from the shipped contract, which is the drift this
|
||||
* test exists to catch — so it reads the repository file rather than a fixture.
|
||||
*
|
||||
* <p>It reads {@code .env.example}, not {@code .env}. {@code .gitignore} states the rule: the
|
||||
* real {@code .env} is operator input and the examples beside it are the tracked contract. A real
|
||||
* {@code .env} exists only on a developer machine, so pointing this test at it made the test pass
|
||||
* locally and fail on every clean checkout — which is where CI runs.
|
||||
*/
|
||||
private static List<String> readEnvFile() {
|
||||
Path fromModule = Path.of(System.getProperty("user.dir")).resolve(".env.example");
|
||||
Path env = Files.exists(fromModule) ? fromModule : Path.of("..").resolve(".env.example");
|
||||
try {
|
||||
return Files.readAllLines(env);
|
||||
} catch (IOException exception) {
|
||||
throw new UncheckedIOException("src/.env.example could not be read", exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
-199
@@ -1,199 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.RoleBasedFileAccessPolicy;
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.security.UnenforcedFileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.admin.AdminAuditPort;
|
||||
import dev.caskeleton.application.fileserver.admin.FileserverAdminService;
|
||||
import dev.caskeleton.application.fileserver.admin.OrphanScanPort;
|
||||
import dev.caskeleton.application.fileserver.admin.StorageHealthPort;
|
||||
import dev.caskeleton.application.fileserver.api.security.FileAccessPolicy;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupContentGateway;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import dev.caskeleton.application.fileserver.concurrency.WriterLeaseCoordinator;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.download.DownloadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.download.ZeroCopyDownloadGateway;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.CopyContentGateway;
|
||||
import dev.caskeleton.application.fileserver.lifecycle.FileLifecycleService;
|
||||
import dev.caskeleton.application.fileserver.observability.FileserverAuditPort;
|
||||
import dev.caskeleton.application.fileserver.quota.StorageUsageProbe;
|
||||
import dev.caskeleton.application.fileserver.quota.TransferAdmissionController;
|
||||
import dev.caskeleton.application.fileserver.recovery.FileReconciliationService;
|
||||
import dev.caskeleton.application.fileserver.recovery.ReconciliationContentProbe;
|
||||
import dev.caskeleton.application.fileserver.upload.FileVerificationService;
|
||||
import dev.caskeleton.application.fileserver.upload.FinalizeUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.SingleShotUploadService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadApplicationService;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadContentGateway;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadIdentifierFactory;
|
||||
import dev.caskeleton.application.fileserver.upload.UploadStorageGateway;
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.task.TaskDecorator;
|
||||
|
||||
/**
|
||||
* Proves the capability is assembled, not merely present.
|
||||
*
|
||||
* <p>Every other fileserver test builds its subject by hand, so a port with no production
|
||||
* implementation and a composition root that never wires one both stay invisible: the code
|
||||
* compiles, the unit tests pass, and the first thing to notice is a failed startup in an
|
||||
* environment where the flag was finally switched on. This test switches it on.
|
||||
*
|
||||
* <p>It asserts on interfaces rather than implementations wherever the design allows a substitute,
|
||||
* so replacing a storage backend or an authorization policy does not break it — what it pins is
|
||||
* that something satisfies each seam.
|
||||
*/
|
||||
class FileserverRuntimeAssemblyTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(FileserverPlatformAutoConfiguration.class))
|
||||
.withUserConfiguration(AssemblySupport.class);
|
||||
|
||||
@Test
|
||||
void enabledBaselineAssemblesTheCompleteRuntime() {
|
||||
enabled()
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
|
||||
List.of(
|
||||
UploadStorageGateway.class,
|
||||
UploadContentGateway.class,
|
||||
DownloadContentGateway.class,
|
||||
ZeroCopyDownloadGateway.class,
|
||||
CopyContentGateway.class,
|
||||
CleanupContentGateway.class,
|
||||
ReconciliationContentProbe.class,
|
||||
StorageUsageProbe.class,
|
||||
StorageHealthPort.class,
|
||||
OrphanScanPort.class,
|
||||
FileVerificationService.class)
|
||||
.forEach(port -> assertThat(context).hasSingleBean(port));
|
||||
|
||||
List.of(
|
||||
UploadApplicationService.class,
|
||||
FinalizeUploadService.class,
|
||||
SingleShotUploadService.class,
|
||||
DownloadApplicationService.class,
|
||||
FileLifecycleService.class,
|
||||
CleanupService.class,
|
||||
FileReconciliationService.class,
|
||||
WriterLeaseCoordinator.class,
|
||||
TransferAdmissionController.class,
|
||||
UploadIdentifierFactory.class)
|
||||
.forEach(service -> assertThat(context).hasSingleBean(service));
|
||||
|
||||
assertThat(context).hasSingleBean(FileAccessPolicy.class);
|
||||
assertThat(context).hasSingleBean(AdminAuditPort.class);
|
||||
assertThat(context).hasSingleBean(FileserverAuditPort.class);
|
||||
assertThat(context.getBean(FileAccessPolicy.class))
|
||||
.isInstanceOf(RoleBasedFileAccessPolicy.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverAdminService.class);
|
||||
assertThat(context).doesNotHaveBean(FileserverCleanupWorker.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEnabledCapabilityWithoutAnAuthorizationDecisionRefusesToStart() {
|
||||
baseline()
|
||||
.withPropertyValues("app.fileserver-platform.enabled=true")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasMessageContaining("without an authorization policy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUnenforcedPolicyIsAvailableForDevelopment() {
|
||||
baseline()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.enabled=true",
|
||||
"app.fileserver-platform.security.access-policy=unenforced")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context.getBean(FileAccessPolicy.class))
|
||||
.isInstanceOf(UnenforcedFileAccessPolicy.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theUnenforcedPolicyIsRefusedUnderAProductionProfile() {
|
||||
baseline()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.enabled=true",
|
||||
"app.fileserver-platform.security.access-policy=unenforced")
|
||||
.withPropertyValues("spring.profiles.active=prod")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasMessageContaining("must not be active under the 'prod' profile"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theAdminPlaneAppearsOnItsOwnSwitch() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver-platform.admin.enabled=true")
|
||||
.run(context -> assertThat(context).hasSingleBean(FileserverAdminService.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCleanupWorkerAppearsOnItsOwnSwitch() {
|
||||
enabled()
|
||||
.withPropertyValues("app.fileserver-platform.cleanup.enabled=true")
|
||||
.run(context -> assertThat(context).hasSingleBean(FileserverCleanupWorker.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStorageRootThatCannotBeProbedRefusesToStart() {
|
||||
enabled()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.storage.root=" + FileserverAssemblyFixture.storageRoot(),
|
||||
"app.fileserver-platform.storage.forbidden-root-ancestors="
|
||||
+ FileserverAssemblyFixture.storageRoot())
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.hasMessageContaining("forbidden ancestor"));
|
||||
}
|
||||
|
||||
private ApplicationContextRunner enabled() {
|
||||
return baseline()
|
||||
.withPropertyValues(
|
||||
"app.fileserver-platform.enabled=true",
|
||||
"app.fileserver-platform.security.access-policy=role-based");
|
||||
}
|
||||
|
||||
private ApplicationContextRunner baseline() {
|
||||
return runner.withPropertyValues(
|
||||
"app.fileserver-platform.observability.fingerprint-key=a-sixteen-byte-key!!",
|
||||
"app.fileserver-platform.storage.root=" + FileserverAssemblyFixture.storageRoot());
|
||||
}
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class AssemblySupport extends FileserverAssemblyFixture {
|
||||
|
||||
@Bean
|
||||
MeterRegistry meterRegistry() {
|
||||
return new SimpleMeterRegistry();
|
||||
}
|
||||
|
||||
@Bean
|
||||
TaskDecorator taskDecorator() {
|
||||
return runnable -> runnable;
|
||||
}
|
||||
}
|
||||
}
|
||||
-220
@@ -1,220 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.fileserver;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.fileserver.platform.local.LocalStorageProbeResult;
|
||||
import dev.caskeleton.application.fileserver.api.content.PublishMode;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class FileserverStartupValidatorTest {
|
||||
|
||||
private final FileserverStartupValidator validator = new FileserverStartupValidator();
|
||||
|
||||
@Test
|
||||
void requiredAtomicModeRejectsUnsupportedStorage() {
|
||||
LocalStorageProbeResult result = resultWithAtomicMove(false);
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(PublishMode.ATOMIC_MOVE_REQUIRED, result))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("atomic move");
|
||||
}
|
||||
|
||||
@Test
|
||||
void preferredModeAcceptsStorageWithoutAnAtomicMove() {
|
||||
assertThatCode(
|
||||
() ->
|
||||
validator.validate(PublishMode.ATOMIC_MOVE_PREFERRED, resultWithAtomicMove(false)))
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyMandatoryProbeFailureBlocksStartup() {
|
||||
LocalStorageProbeResult broken =
|
||||
new LocalStorageProbeResult(
|
||||
false, false, false, true, true, false, false, true, true, "linux-ext4", List.of());
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(PublishMode.ATOMIC_MOVE_PREFERRED, broken))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("not writable")
|
||||
.hasMessageContaining("atomic create")
|
||||
.hasMessageContaining("same file store")
|
||||
.hasMessageContaining("symbolic links")
|
||||
.hasMessageContaining("descriptor-relative access");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStorageRootUnderTheWebRootBlocksStartup() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck()
|
||||
.withStorageRoot(Path.of("/srv/app/static/files"))
|
||||
.withForbiddenAncestors(List.of(Path.of("/srv/app/static")))
|
||||
.build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("web root");
|
||||
}
|
||||
|
||||
@Test
|
||||
void multiInstanceWithoutASharedMetadataStoreBlocksStartup() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck().withMultiInstance(true).withMetadataStorePresent(false).build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("shared metadata store");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowAllPolicyInProductionBlocksStartup() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck().withProductionProfile(true).withAllowAllAccessPolicy(true).build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("allow-all");
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiringAScannerWithoutAVerifierBlocksStartup() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck().withScannerRequired(true).withScannerPresent(false).build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("verifier");
|
||||
}
|
||||
|
||||
@Test
|
||||
void nginxDelegationWithoutAValidatedMappingBlocksStartup() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck()
|
||||
.withNginxDelegationEnabled(true)
|
||||
.withNginxInternalMappingValidated(false)
|
||||
.build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("internal URI mapping");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFullyProvenConfigurationStarts() {
|
||||
assertThatCode(() -> validator.validate(healthyCheck().build())).doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyViolationIsReportedInOnePass() {
|
||||
FileserverStartupCheck check =
|
||||
healthyCheck()
|
||||
.withProductionProfile(true)
|
||||
.withAllowAllAccessPolicy(true)
|
||||
.withScannerRequired(true)
|
||||
.withScannerPresent(false)
|
||||
.build();
|
||||
|
||||
assertThatThrownBy(() -> validator.validate(check))
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.satisfies(
|
||||
failure -> {
|
||||
assertThat(failure.getMessage()).contains("allow-all");
|
||||
assertThat(failure.getMessage()).contains("verifier");
|
||||
});
|
||||
}
|
||||
|
||||
private static LocalStorageProbeResult resultWithAtomicMove(boolean atomicMove) {
|
||||
return new LocalStorageProbeResult(
|
||||
true, true, true, atomicMove, true, true, true, true, true, "linux-ext4", List.of());
|
||||
}
|
||||
|
||||
private static CheckBuilder healthyCheck() {
|
||||
return new CheckBuilder();
|
||||
}
|
||||
|
||||
/** Small builder so each scenario names only the condition it is exercising. */
|
||||
private static final class CheckBuilder {
|
||||
|
||||
private PublishMode publishMode = PublishMode.ATOMIC_MOVE_PREFERRED;
|
||||
private LocalStorageProbeResult probeResult = resultWithAtomicMove(true);
|
||||
private Path storageRoot = Path.of("/var/lib/backend/files");
|
||||
private List<Path> forbiddenRootAncestors = List.of(Path.of("/srv/app/static"));
|
||||
private boolean multiInstance;
|
||||
private boolean metadataStorePresent = true;
|
||||
private boolean productionProfile;
|
||||
private boolean allowAllAccessPolicy;
|
||||
private boolean scannerRequired;
|
||||
private boolean scannerPresent = true;
|
||||
private boolean nginxDelegationEnabled;
|
||||
private boolean nginxInternalMappingValidated = true;
|
||||
|
||||
CheckBuilder withStorageRoot(Path storageRoot) {
|
||||
this.storageRoot = storageRoot;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withForbiddenAncestors(List<Path> forbiddenRootAncestors) {
|
||||
this.forbiddenRootAncestors = forbiddenRootAncestors;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withMultiInstance(boolean multiInstance) {
|
||||
this.multiInstance = multiInstance;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withMetadataStorePresent(boolean metadataStorePresent) {
|
||||
this.metadataStorePresent = metadataStorePresent;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withProductionProfile(boolean productionProfile) {
|
||||
this.productionProfile = productionProfile;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withAllowAllAccessPolicy(boolean allowAllAccessPolicy) {
|
||||
this.allowAllAccessPolicy = allowAllAccessPolicy;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withScannerRequired(boolean scannerRequired) {
|
||||
this.scannerRequired = scannerRequired;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withScannerPresent(boolean scannerPresent) {
|
||||
this.scannerPresent = scannerPresent;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withNginxDelegationEnabled(boolean nginxDelegationEnabled) {
|
||||
this.nginxDelegationEnabled = nginxDelegationEnabled;
|
||||
return this;
|
||||
}
|
||||
|
||||
CheckBuilder withNginxInternalMappingValidated(boolean validated) {
|
||||
this.nginxInternalMappingValidated = validated;
|
||||
return this;
|
||||
}
|
||||
|
||||
FileserverStartupCheck build() {
|
||||
return new FileserverStartupCheck(
|
||||
publishMode,
|
||||
probeResult,
|
||||
storageRoot,
|
||||
forbiddenRootAncestors,
|
||||
multiInstance,
|
||||
metadataStorePresent,
|
||||
productionProfile,
|
||||
allowAllAccessPolicy,
|
||||
scannerRequired,
|
||||
scannerPresent,
|
||||
nginxDelegationEnabled,
|
||||
nginxInternalMappingValidated);
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-3
@@ -16,8 +16,6 @@ class PersistenceJpaRootAutoConfigurationOrderingTest {
|
||||
assertThat(Arrays.asList(root.after())).isEmpty();
|
||||
assertThat(root.afterName())
|
||||
.noneMatch(
|
||||
name ->
|
||||
name.startsWith(
|
||||
"dev.caskeleton.adapter.outbound.persistence.autoconfigure."));
|
||||
name -> name.startsWith("dev.caskeleton.adapter.outbound.persistence.autoconfigure."));
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -3,7 +3,6 @@ package dev.caskeleton.bootstrap.autoconfigure.outbox;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventEncoderPort;
|
||||
import dev.caskeleton.application.messaging.event.IntegrationEventPublishPort;
|
||||
import dev.caskeleton.application.outbox.OutboxPublishOutcome;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
@@ -52,7 +51,9 @@ class OutboxCanonicalTransportRequirementValidatorTest {
|
||||
event -> CompletableFuture.completedFuture(OutboxPublishOutcome.CONFIRMED);
|
||||
|
||||
assertThatCode(
|
||||
() -> new OutboxCanonicalTransportRequirementValidator(settings, publisher, draft -> null).validate())
|
||||
() ->
|
||||
new OutboxCanonicalTransportRequirementValidator(settings, publisher, draft -> null)
|
||||
.validate())
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -143,8 +143,7 @@ class RedisActivationValidatorTest {
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.isInstanceOf(RequiredAdapterDisabledException.class)
|
||||
.hasStackTraceContaining(
|
||||
"ca-skeleton.capabilities.idempotency.key-version=2")
|
||||
.hasStackTraceContaining("ca-skeleton.capabilities.idempotency.key-version=2")
|
||||
.hasStackTraceContaining("unsupported without dual-read");
|
||||
});
|
||||
}
|
||||
|
||||
-168
@@ -1,168 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.config.RedisSdkAutoConfiguration;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.application.cache.CacheRegionPort;
|
||||
import dev.caskeleton.application.idempotency.v2.IdempotencyStorePortV2;
|
||||
import dev.caskeleton.application.lease.DistributedLeasePort;
|
||||
import dev.caskeleton.application.outbound.SecretSourcePort;
|
||||
import dev.caskeleton.shared.ratelimit.EdgeRateLimitPort;
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Proves that a selected Redis role produces the port it selects.
|
||||
*
|
||||
* <p>The defect this covers was not a wrong value: {@code APP_REDIS_ENABLED=true} built a client, a
|
||||
* connection owner and a health contributor, and every semantic port count was zero. A deployment
|
||||
* that selected {@code redis} for its rate limiter started, reported healthy, and had no rate
|
||||
* limiter — so "Redis is on" meant only "Redis is reachable".
|
||||
*
|
||||
* <p>Nothing connects here. Composition is entirely local: clients are built, lanes are opened
|
||||
* lazily, and what is asserted is which beans exist for which selector. The behaviour of the ports
|
||||
* against a real server is the topology lane's job.
|
||||
*/
|
||||
class RedisCapabilityCompositionTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class))
|
||||
.withBean(
|
||||
"compositionOnlyRedisSemanticScriptAclProbe",
|
||||
RedisSemanticScriptAclProbe.class,
|
||||
() ->
|
||||
new RedisSemanticScriptAclProbe(
|
||||
mock(RedisRuntimeOwner.class),
|
||||
new RedisCapabilitySettings(),
|
||||
new byte[] {0},
|
||||
Duration.ofSeconds(1)))
|
||||
.withUserConfiguration(RedisCapabilityConfig.class, Support.class)
|
||||
.withPropertyValues(
|
||||
"app.redis.enabled=true",
|
||||
"app.redis.nodes=redis-a:6379",
|
||||
"app.redis.namespace.environment=prod",
|
||||
"app.redis.namespace.service=ca-skeleton",
|
||||
"app.redis.namespace.domain=shared",
|
||||
"app.redis.authentication.credential-reference="
|
||||
+ "secret://ca-skeleton-application@environment/APP_REDIS_PASSWORD",
|
||||
"ca-skeleton.capabilities.cache.key-hmac-secret-reference="
|
||||
+ "secret://environment/APP_CACHE_REDIS_KEY_HMAC_SECRET",
|
||||
"ca-skeleton.capabilities.rate-limit.policies.api-default.algorithm=sliding-counter",
|
||||
"ca-skeleton.capabilities.rate-limit.policies.api-default.limit=100",
|
||||
"ca-skeleton.capabilities.rate-limit.policies.api-default.window=1s");
|
||||
|
||||
@Test
|
||||
@DisplayName("Redis on with no role selected composes a runtime and no semantic port")
|
||||
void noRoleComposesNoPort() {
|
||||
runner.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(RedisRuntimeOwner.class);
|
||||
assertThat(context.getBeansOfType(CacheRegionPort.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(EdgeRateLimitPort.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the cache binding composes a cache region and nothing else")
|
||||
void cacheBindingComposesTheCacheRegion() {
|
||||
runner
|
||||
.withPropertyValues("ca-skeleton.capabilities.cache.bindings.default=redis")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(CacheRegionPort.class);
|
||||
assertThat(context.getBeansOfType(EdgeRateLimitPort.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(IdempotencyStorePortV2.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a rate limiter with no configured policy is refused at startup")
|
||||
void aRateLimiterWithoutPoliciesIsRefused() {
|
||||
// Every call would answer "unknown policy", which the port reports as a deployment error per
|
||||
// request rather than once, at the only moment anybody is looking.
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class))
|
||||
.withUserConfiguration(RedisCapabilityConfig.class, Support.class)
|
||||
.withPropertyValues(
|
||||
"app.redis.enabled=true",
|
||||
"app.redis.nodes=redis-a:6379",
|
||||
"app.redis.authentication.credential-reference=secret://u@environment/PW",
|
||||
"ca-skeleton.capabilities.rate-limit.provider=redis")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasFailed();
|
||||
assertThat(context.getStartupFailure())
|
||||
.hasStackTraceContaining("no policy is configured");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("every selected role composes at once, under one namespace")
|
||||
void allRolesComposeTogether() {
|
||||
runner
|
||||
.withPropertyValues(
|
||||
"ca-skeleton.capabilities.cache.bindings.default=redis",
|
||||
"ca-skeleton.capabilities.rate-limit.provider=redis",
|
||||
"ca-skeleton.capabilities.lease.provider=redis",
|
||||
"ca-skeleton.capabilities.idempotency.provider=redis")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(CacheRegionPort.class);
|
||||
assertThat(context).hasSingleBean(EdgeRateLimitPort.class);
|
||||
assertThat(context).hasSingleBean(DistributedLeasePort.class);
|
||||
assertThat(context).hasSingleBean(IdempotencyStorePortV2.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the switch off composes nothing, whatever the roles say")
|
||||
void theSwitchOffComposesNothing() {
|
||||
// The contradiction itself is refused by RedisActivationValidator; what is asserted here is
|
||||
// that this configuration contributes no bean to argue about in the first place.
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(RedisSdkAutoConfiguration.class))
|
||||
.withUserConfiguration(RedisCapabilityConfig.class, Support.class)
|
||||
.withPropertyValues(
|
||||
"app.redis.enabled=false",
|
||||
"ca-skeleton.capabilities.cache.bindings.default=redis",
|
||||
"ca-skeleton.capabilities.lease.provider=redis")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context.getBeansOfType(RedisCapabilityConfig.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(CacheRegionPort.class)).isEmpty();
|
||||
assertThat(context.getBeansOfType(DistributedLeasePort.class)).isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
/** The two collaborators the composition takes from the rest of the application. */
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
static class Support {
|
||||
|
||||
@Bean
|
||||
SecretSourcePort secretSource() {
|
||||
return name -> Optional.of("fixture-secret-" + name);
|
||||
}
|
||||
|
||||
@Bean
|
||||
Clock clock() {
|
||||
return Clock.systemUTC();
|
||||
}
|
||||
}
|
||||
}
|
||||
-137
@@ -1,137 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.autoconfigure.redis;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.api.RedisDeploymentMode;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisConnectionKind;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeClient;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.connection.RedisRuntimeOwner;
|
||||
import dev.caskeleton.adapter.outbound.cache.redis.sdk.lettuce.operations.RedisCommandGateway;
|
||||
import dev.caskeleton.bootstrap.runtime.startup.StartupValidationException;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class RedisSemanticScriptAclProbeTest {
|
||||
|
||||
@Test
|
||||
void noScriptCapabilitySelectedDoesNotTouchRedis() {
|
||||
RedisCapabilitySettings capabilities = new RedisCapabilitySettings();
|
||||
AtomicInteger opened = new AtomicInteger();
|
||||
RedisRuntimeOwner owner = owner(gateway(false), opened);
|
||||
|
||||
RedisSemanticScriptAclProbe probe =
|
||||
new RedisSemanticScriptAclProbe(
|
||||
owner,
|
||||
capabilities,
|
||||
"prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8),
|
||||
Duration.ofSeconds(1));
|
||||
|
||||
assertThatCode(probe::afterSingletonsInstantiated).doesNotThrowAnyException();
|
||||
assertThat(opened).hasValue(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void selectedScriptCapabilityMustLoadAndEvaluateAProgram() {
|
||||
RedisCapabilitySettings capabilities = new RedisCapabilitySettings();
|
||||
capabilities.getRateLimit().setProvider("redis");
|
||||
AtomicInteger opened = new AtomicInteger();
|
||||
RedisRuntimeOwner owner = owner(gateway(false), opened);
|
||||
|
||||
RedisSemanticScriptAclProbe probe =
|
||||
new RedisSemanticScriptAclProbe(
|
||||
owner,
|
||||
capabilities,
|
||||
"prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8),
|
||||
Duration.ofSeconds(1));
|
||||
|
||||
assertThatCode(probe::afterSingletonsInstantiated).doesNotThrowAnyException();
|
||||
assertThat(opened).hasValue(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingScriptAclFailsStartupInsteadOfDeferringToFirstRequest() {
|
||||
RedisCapabilitySettings capabilities = new RedisCapabilitySettings();
|
||||
capabilities.getLease().setProvider("redis");
|
||||
RedisRuntimeOwner owner = owner(gateway(true), new AtomicInteger());
|
||||
|
||||
RedisSemanticScriptAclProbe probe =
|
||||
new RedisSemanticScriptAclProbe(
|
||||
owner,
|
||||
capabilities,
|
||||
"prod:svc:shared:probe".getBytes(StandardCharsets.UTF_8),
|
||||
Duration.ofSeconds(1));
|
||||
|
||||
assertThatThrownBy(probe::afterSingletonsInstantiated)
|
||||
.isInstanceOf(StartupValidationException.class)
|
||||
.hasMessageContaining("SCRIPT LOAD/EVALSHA is unavailable")
|
||||
.hasRootCauseInstanceOf(RuntimeException.class);
|
||||
}
|
||||
|
||||
private static RedisRuntimeOwner owner(RedisCommandGateway gateway, AtomicInteger opened) {
|
||||
RedisRuntimeClient client =
|
||||
new RedisRuntimeClient() {
|
||||
@Override
|
||||
public RedisDeploymentMode mode() {
|
||||
return RedisDeploymentMode.STANDALONE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RedisLaneConnection openLane(
|
||||
RedisConnectionKind kind, Optional<byte[]> routingKey) {
|
||||
opened.incrementAndGet();
|
||||
return new RedisLaneConnection() {
|
||||
@Override
|
||||
public RedisCommandGateway gateway() {
|
||||
return gateway;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean open() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {}
|
||||
};
|
||||
EnumMap<RedisConnectionKind, Integer> limits = new EnumMap<>(RedisConnectionKind.class);
|
||||
for (RedisConnectionKind kind : RedisConnectionKind.values()) {
|
||||
limits.put(kind, 1);
|
||||
}
|
||||
return new RedisRuntimeOwner(client, limits, Duration.ofSeconds(1));
|
||||
}
|
||||
|
||||
private static RedisCommandGateway gateway(boolean denyScripts) {
|
||||
return (RedisCommandGateway)
|
||||
Proxy.newProxyInstance(
|
||||
RedisCommandGateway.class.getClassLoader(),
|
||||
new Class<?>[] {RedisCommandGateway.class},
|
||||
(proxy, method, arguments) ->
|
||||
switch (method.getName()) {
|
||||
case "loadScript" ->
|
||||
denyScripts
|
||||
? CompletableFuture.failedFuture(
|
||||
new RuntimeException("NOPERM script load denied"))
|
||||
: CompletableFuture.completedFuture("probe-digest");
|
||||
case "evaluateRegisteredForList" ->
|
||||
CompletableFuture.completedFuture(List.of(1L));
|
||||
case "toString" -> "RedisSemanticScriptAclProbeTestGateway";
|
||||
default ->
|
||||
throw new UnsupportedOperationException(
|
||||
"unexpected gateway method: " + method.getName());
|
||||
});
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -19,7 +19,12 @@ class BootstrapCapabilityAutoConfigurationReachabilityTest {
|
||||
|
||||
private static final List<String> REQUIRED_ROOTS =
|
||||
List.of(
|
||||
"dev.caskeleton.bootstrap.autoconfigure.redis.RedisCapabilityConfig",
|
||||
// Redis is no longer here. Its semantic wiring — the cache, rate-limit, lease and
|
||||
// idempotency ports and the key policy they share — moved into
|
||||
// `adapter:outbound:cache-redis`, which now ships its own registration and its own
|
||||
// reachability test. What stayed in the composition root is the part that is genuinely
|
||||
// cross-capability: the readiness-group append and the activation validator that reads
|
||||
// the bootstrap-owned secret policy.
|
||||
"dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxConfig",
|
||||
"dev.caskeleton.bootstrap.autoconfigure.lock.DistributedLockConfig",
|
||||
"dev.caskeleton.bootstrap.autoconfigure.idempotency.IdempotencyProviderSelectionConfig",
|
||||
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package dev.caskeleton.bootstrap.contract;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.activation.MasterSwitch;
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
/**
|
||||
* Every master switch has a row in the capability status document.
|
||||
*
|
||||
* <p>The document separates three questions the review found conflated everywhere — is the
|
||||
* capability implemented, does the shipped artifact assemble it, has it been proven against a real
|
||||
* provider. Those are judgements about evidence, so the document is written rather than generated;
|
||||
* what a test can hold is that a capability cannot be added without stating them. A switch with no
|
||||
* row is a capability whose deployment status nobody has answered.
|
||||
*
|
||||
* <p>Deliberately the only automated check on that file. Re-deriving its cells would make a parser
|
||||
* the source of truth for a judgement, which is the shape of verification this repository's own
|
||||
* review says to stop adding.
|
||||
*/
|
||||
class CapabilityStatusDocumentTest {
|
||||
|
||||
private static final String DOCUMENT = "docs/capability-status.md";
|
||||
|
||||
@Test
|
||||
@DisplayName("every master switch is accounted for in the capability status document")
|
||||
void everyMasterSwitchHasARow() {
|
||||
String document = read();
|
||||
|
||||
for (MasterSwitch masterSwitch : MasterSwitch.values()) {
|
||||
assertThat(document)
|
||||
.as(
|
||||
"%s names %s but %s does not say whether it is implemented, wired and qualified",
|
||||
MasterSwitch.class.getSimpleName(), masterSwitch.environmentVariable(), DOCUMENT)
|
||||
.contains(masterSwitch.environmentVariable());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the document states what decides each column")
|
||||
void theDocumentNamesItsOwnSources() {
|
||||
// Without this the table degrades into three columns of "yes" that nobody can check. Each
|
||||
// column has to point at the thing that decides it, not at an opinion.
|
||||
assertThat(read())
|
||||
.contains("config/architecture/modules.json")
|
||||
.contains("AutoConfiguration.imports")
|
||||
.contains("a workflow that executes it");
|
||||
}
|
||||
|
||||
private static String read() {
|
||||
Path document = repositoryRoot().resolve(DOCUMENT);
|
||||
assertThat(Files.isRegularFile(document)).as("%s", document).isTrue();
|
||||
try {
|
||||
return Files.readString(document);
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("cannot read " + document, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path repositoryRoot() {
|
||||
for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) {
|
||||
if (Files.isRegularFile(path.resolve("AGENTS.md"))
|
||||
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("repository root not found");
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -70,8 +70,7 @@ class ConditionalTransportQualificationContractTest {
|
||||
assertThat(scan).isNotNull();
|
||||
assertThat(scan.basePackages())
|
||||
.doesNotContain(
|
||||
"dev.caskeleton.adapter.inbound.grpc",
|
||||
"dev.caskeleton.adapter.inbound.websocket");
|
||||
"dev.caskeleton.adapter.inbound.grpc", "dev.caskeleton.adapter.inbound.websocket");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+23
@@ -274,6 +274,29 @@ class DeveloperExperienceContractTest {
|
||||
"./gradlew :app-bootstrap:test --tests 'dev.caskeleton.bootstrap.architecture.*'");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyOptionalPlatformIntegrationLaneHasAnExecutingWorkflowCaller() throws IOException {
|
||||
// `grpc-operation-ledger-jpa` declares a Testcontainers PostgreSQL lane that certifies the
|
||||
// atomic claim durable mutation idempotency rests on. It was registered in `strictTestLanes`,
|
||||
// fails closed, and ran nowhere: the optional build's `ci` reaches `checkAll`, `qualityCheck`
|
||||
// and the dependency verifier, and none of those runs a lane whose category is INTEGRATION.
|
||||
// A lane nobody runs is not coverage, so both halves are pinned here — the aggregate that
|
||||
// covers the category, and the workflow that executes the aggregate.
|
||||
assertThat(read("src/optional-platforms/build.gradle"))
|
||||
.as("the optional platform build must aggregate its integration-category lanes")
|
||||
.contains("tasks.register('integrationCheck')")
|
||||
.contains(":integrationTestLaneCheck");
|
||||
|
||||
assertThat(read("src/grpc/grpc-operation-ledger-jpa/build.gradle"))
|
||||
.as("the operation ledger lane this contract protects must still be declared")
|
||||
.contains("lane('integrationTest')")
|
||||
.contains("integration()");
|
||||
|
||||
assertThat(read(".github/workflows/integration-main.yml"))
|
||||
.as("a workflow must actually execute the optional platform integration aggregate")
|
||||
.contains("./gradlew -p optional-platforms integrationCheck");
|
||||
}
|
||||
|
||||
@Test
|
||||
void dockerBuildConsumesOnlyTheGradleStagedExecutableJar() throws IOException {
|
||||
String dockerfile = "src/Dockerfile";
|
||||
|
||||
+1
-2
@@ -20,8 +20,7 @@ class MongoShippedCompositionContractTest {
|
||||
|
||||
// The default app-bootstrap explicitly excludes the reactive-streams Mongo driver. Without it,
|
||||
// Boot cannot construct the ReactiveMongoTemplate bean required by ReactiveExecution.
|
||||
assertThat(
|
||||
ClassUtils.isPresent("com.mongodb.reactivestreams.client.MongoClient", classLoader))
|
||||
assertThat(ClassUtils.isPresent("com.mongodb.reactivestreams.client.MongoClient", classLoader))
|
||||
.isFalse();
|
||||
}
|
||||
}
|
||||
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package dev.caskeleton.bootstrap.contract;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/**
|
||||
* {@code OperationalError} and {@code docs/registries/error-codes.yaml} describe the same set.
|
||||
*
|
||||
* <p>This was a Gradle task in the {@code build-tools} included build, with a hand-written YAML
|
||||
* parser inside it. The contract is worth keeping and the placement was not: comparing two
|
||||
* checked-in files needs no dependency resolution, no task graph and no included build, and the
|
||||
* review's Phase 6 asks for exactly this kind of verification to move back to a test. Reading the
|
||||
* registry with a real YAML parser rather than a line-prefix scanner is the other thing the move
|
||||
* buys — the scanner accepted a row whose fields were indented differently.
|
||||
*
|
||||
* <p>Held here rather than in {@code shared-contract}, which owns the enum, because {@code
|
||||
* shared-contract} is Java-stdlib-only by policy and this repository already parses the same
|
||||
* registry here for the runbook coverage contract.
|
||||
*/
|
||||
class OperationalErrorRegistryContractTest {
|
||||
|
||||
private static final String REGISTRY = "docs/registries/error-codes.yaml";
|
||||
|
||||
private static final String SOURCE =
|
||||
"src/shared-contract/src/main/java/dev/caskeleton/shared/error/OperationalError.java";
|
||||
|
||||
/** One constant: NAME(Category.X, status, retryable). */
|
||||
private static final Pattern ENUM_ENTRY =
|
||||
Pattern.compile(
|
||||
"(?m)^\\s*([A-Z][A-Z0-9_]+)\\s*\\(Category\\.([A-Z_]+),\\s*(\\d+),\\s*(true|false)\\)");
|
||||
|
||||
private record Contract(String category, int httpStatus, boolean retryable) {}
|
||||
|
||||
@Test
|
||||
@DisplayName("the enum and the registry name the same operational errors, with the same metadata")
|
||||
void theEnumAndTheRegistryAgree() {
|
||||
Map<String, Contract> declared = declaredInCode();
|
||||
Map<String, Contract> registered = declaredInRegistry();
|
||||
|
||||
assertThat(declared)
|
||||
.as("OperationalError declares no constants; the scan is broken")
|
||||
.isNotEmpty();
|
||||
|
||||
Set<String> codeOnly = new TreeSet<>(declared.keySet());
|
||||
codeOnly.removeAll(registered.keySet());
|
||||
assertThat(codeOnly).as("OperationalError entries missing from %s", REGISTRY).isEmpty();
|
||||
|
||||
Set<String> registryOnly = new TreeSet<>(registered.keySet());
|
||||
registryOnly.removeAll(declared.keySet());
|
||||
assertThat(registryOnly).as("%s rows with no OperationalError constant", REGISTRY).isEmpty();
|
||||
|
||||
declared.forEach(
|
||||
(name, expected) ->
|
||||
assertThat(registered.get(name))
|
||||
.as("%s: category, HTTP status and retryability must match the registry", name)
|
||||
.isEqualTo(expected));
|
||||
}
|
||||
|
||||
private static Map<String, Contract> declaredInCode() {
|
||||
Map<String, Contract> declared = new LinkedHashMap<>();
|
||||
Matcher matcher = ENUM_ENTRY.matcher(read(SOURCE));
|
||||
while (matcher.find()) {
|
||||
declared.put(
|
||||
matcher.group(1),
|
||||
new Contract(
|
||||
matcher.group(2),
|
||||
Integer.parseInt(matcher.group(3)),
|
||||
Boolean.parseBoolean(matcher.group(4))));
|
||||
}
|
||||
return declared;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Contract> declaredInRegistry() {
|
||||
LoaderOptions options = new LoaderOptions();
|
||||
options.setAllowDuplicateKeys(false);
|
||||
Object loaded = new Yaml(new SafeConstructor(options)).load(read(REGISTRY));
|
||||
assertThat(loaded).as("%s must be a YAML mapping", REGISTRY).isInstanceOf(Map.class);
|
||||
|
||||
Map<String, Contract> registered = new LinkedHashMap<>();
|
||||
for (Object section : ((Map<String, Object>) loaded).values()) {
|
||||
if (!(section instanceof List<?> rows)) {
|
||||
continue;
|
||||
}
|
||||
for (Object row : rows) {
|
||||
if (!(row instanceof Map<?, ?> entry) || !(entry.get("code") instanceof String code)) {
|
||||
continue;
|
||||
}
|
||||
Object category = entry.get("category");
|
||||
Object status = entry.get("http_status");
|
||||
Object retryable = entry.get("retryable");
|
||||
if (category == null || status == null || retryable == null) {
|
||||
continue;
|
||||
}
|
||||
Contract previous =
|
||||
registered.put(
|
||||
code,
|
||||
new Contract(
|
||||
String.valueOf(category),
|
||||
((Number) status).intValue(),
|
||||
Boolean.parseBoolean(String.valueOf(retryable))));
|
||||
assertThat(previous).as("%s declares %s more than once", REGISTRY, code).isNull();
|
||||
}
|
||||
}
|
||||
return registered;
|
||||
}
|
||||
|
||||
private static String read(String relativePath) {
|
||||
Path path = repositoryRoot().resolve(relativePath);
|
||||
assertThat(Files.isRegularFile(path)).as("%s", path).isTrue();
|
||||
try {
|
||||
return Files.readString(path);
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("cannot read " + path, failure);
|
||||
}
|
||||
}
|
||||
|
||||
private static Path repositoryRoot() {
|
||||
for (Path path = Path.of("").toAbsolutePath(); path != null; path = path.getParent()) {
|
||||
if (Files.isRegularFile(path.resolve("AGENTS.md"))
|
||||
&& Files.isRegularFile(path.resolve("src/settings.gradle"))) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
throw new IllegalStateException("repository root not found");
|
||||
}
|
||||
}
|
||||
-2
@@ -11,7 +11,6 @@ import dev.caskeleton.bootstrap.logging.LogMaskingPatterns;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
@@ -128,5 +127,4 @@ class PiiTokenBodyForbiddenContractTest {
|
||||
private static long countUnmasked(String text) {
|
||||
return UNMASKED_SECRET.matcher(text).results().count();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+15
-5
@@ -42,11 +42,21 @@ class RedisOptionalityContractTest {
|
||||
.isNotNull();
|
||||
assertThat(scan.basePackages())
|
||||
.as(
|
||||
"the scan that would make an annotated Redis settings class unconditional; the "
|
||||
+ "composition root now names the packages it scans rather than scanning "
|
||||
+ "dev.caskeleton.adapter wholesale, so this asserts the Redis package is still "
|
||||
+ "covered — the hazard this test guards is unchanged, only its address is")
|
||||
.contains("dev.caskeleton.adapter.outbound.cache.redis");
|
||||
"the scan that would make an annotated Redis SDK settings class unconditional; this "
|
||||
+ "asserts the hazard still exists, so the assertion below is about something")
|
||||
.contains("dev.caskeleton.adapter.outbound.cache.redis.sdk");
|
||||
assertThat(scan.basePackages())
|
||||
.as(
|
||||
"the capability package must stay outside the scan. RedisCapabilitySettings is "
|
||||
+ "annotated @ConfigurationProperties and is bound by the gated "
|
||||
+ "RedisCapabilityConfig; when the capability moved into the leaf under the wider "
|
||||
+ "`...cache.redis` prefix the scan bound it with every switch off, which is the "
|
||||
+ "one thing the off-state contract forbids")
|
||||
.doesNotContain("dev.caskeleton.adapter.outbound.cache.redis")
|
||||
.noneMatch(
|
||||
basePackage ->
|
||||
"dev.caskeleton.adapter.outbound.cache.redis.capability"
|
||||
.startsWith(basePackage + "."));
|
||||
assertThat(CaSkeletonApplication.class.getAnnotation(SpringBootConfiguration.class))
|
||||
.as(
|
||||
"the composition root is spelled out as @SpringBootConfiguration + "
|
||||
|
||||
+3
-4
@@ -34,7 +34,8 @@ class MessagingMembershipQualificationTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("the default composition ships the broker-neutral core, not either broker capability")
|
||||
@DisplayName(
|
||||
"the default composition ships the broker-neutral core, not either broker capability")
|
||||
void defaultCompositionShipsOnlyTheBrokerNeutralCore() {
|
||||
String bootstrap = read(repositoryRoot().resolve("src/app-bootstrap/build.gradle"));
|
||||
|
||||
@@ -50,9 +51,7 @@ class MessagingMembershipQualificationTest {
|
||||
@DisplayName("the core starter has no production edge to either broker leaf")
|
||||
void coreStarterIsBrokerNeutral() {
|
||||
String starter =
|
||||
read(
|
||||
repositoryRoot()
|
||||
.resolve("src/messaging/messaging-spring-boot-starter/build.gradle"));
|
||||
read(repositoryRoot().resolve("src/messaging/messaging-spring-boot-starter/build.gradle"));
|
||||
|
||||
assertThat(starter)
|
||||
.doesNotContain(
|
||||
|
||||
-43
@@ -9,13 +9,10 @@ import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupBatchResult;
|
||||
import dev.caskeleton.application.fileserver.cleanup.CleanupService;
|
||||
import dev.caskeleton.application.lock.DistributedLock;
|
||||
import dev.caskeleton.application.lock.DistributedLockPort;
|
||||
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsCommand;
|
||||
import dev.caskeleton.application.outbox.PublishPendingOutboxEventsUseCase;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.fileserver.FileserverCleanupWorker;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.lock.MeteredDistributedLockPort;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxMetrics;
|
||||
import dev.caskeleton.bootstrap.autoconfigure.outbox.OutboxRelayScheduler;
|
||||
@@ -32,46 +29,6 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory;
|
||||
|
||||
class BootstrapStructuredRuntimeLoggingTest {
|
||||
|
||||
@Test
|
||||
void fileserverCleanupSuccessCarriesBoundedOutcomeFields() {
|
||||
CleanupService cleanup = (maxItems, maxBytes) -> new CleanupBatchResult(1, 2, 3, 4, 5L);
|
||||
|
||||
try (CapturedLogger captured = capture(FileserverCleanupWorker.class)) {
|
||||
new FileserverCleanupWorker(cleanup, 10, 1_024L).runBatch();
|
||||
|
||||
ILoggingEvent event = captured.singleEvent();
|
||||
assertThat(event.getLevel()).isEqualTo(Level.INFO);
|
||||
assertThat(event.getFormattedMessage()).contains("deleted=1").contains("reclaimedBytes=5");
|
||||
assertThat(renderedArguments(event))
|
||||
.contains("capability=fileserver")
|
||||
.contains("operation=cleanup")
|
||||
.contains("cleanup.deleted=1")
|
||||
.contains("cleanup.failed=4")
|
||||
.contains("cleanup.reclaimed_bytes=5");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void fileserverCleanupFailureCarriesRetryDisposition() {
|
||||
CleanupService cleanup =
|
||||
(maxItems, maxBytes) -> {
|
||||
throw new IllegalStateException("storage unavailable");
|
||||
};
|
||||
|
||||
try (CapturedLogger captured = capture(FileserverCleanupWorker.class)) {
|
||||
new FileserverCleanupWorker(cleanup, 10, 1_024L).runBatch();
|
||||
|
||||
ILoggingEvent event = captured.singleEvent();
|
||||
assertThat(event.getLevel()).isEqualTo(Level.WARN);
|
||||
assertThat(renderedArguments(event))
|
||||
.contains("capability=fileserver")
|
||||
.contains("operation=cleanup")
|
||||
.contains("warning.kind=scheduled-task-failed")
|
||||
.contains("retry.disposition=next-run");
|
||||
assertThat(event.getThrowableProxy()).isNotNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void outboxRelayUnexpectedFailureCarriesNextTickDispositionWithoutInventedErrorCode() {
|
||||
PublishPendingOutboxEventsUseCase relay = mock(PublishPendingOutboxEventsUseCase.class);
|
||||
|
||||
-59
@@ -1,59 +0,0 @@
|
||||
package dev.caskeleton.bootstrap.runtime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.runtime.RuntimeEnvironment;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.mock.env.MockEnvironment;
|
||||
|
||||
class RuntimeProfileSnapshotTest {
|
||||
|
||||
@Test
|
||||
void capturesProfileOrderAndSupplementaryProfilesWithoutReinterpretingThem() {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setActiveProfiles("prod", "eu-west");
|
||||
|
||||
RuntimeProfileSnapshot snapshot = RuntimeProfileSnapshot.from(environment);
|
||||
|
||||
assertThat(snapshot.activeProfiles()).containsExactly("prod", "eu-west");
|
||||
assertThat(snapshot.environments()).containsExactly(RuntimeEnvironment.PROD);
|
||||
assertThat(snapshot.resolve()).contains(RuntimeEnvironment.PROD);
|
||||
assertThat(snapshot.isProduction()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void profilelessContextRemainsUnresolvedAndNonProduction() {
|
||||
RuntimeProfileSnapshot snapshot = RuntimeProfileSnapshot.from(new MockEnvironment());
|
||||
|
||||
assertThat(snapshot.activeProfiles()).isEmpty();
|
||||
assertThat(snapshot.environments()).isEmpty();
|
||||
assertThat(snapshot.resolve()).isEmpty();
|
||||
assertThat(snapshot.isProduction()).isFalse();
|
||||
assertThat(snapshot.isTestContext()).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void testProfileIsRecognisedButNeverPromotedToADeployableEnvironment() {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setActiveProfiles("test");
|
||||
|
||||
RuntimeProfileSnapshot snapshot = RuntimeProfileSnapshot.from(environment);
|
||||
|
||||
assertThat(snapshot.isTestContext()).isTrue();
|
||||
assertThat(snapshot.resolve()).isEmpty();
|
||||
assertThat(snapshot.environments()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void snapshotIsDetachedFromLaterEnvironmentMutation() {
|
||||
MockEnvironment environment = new MockEnvironment();
|
||||
environment.setActiveProfiles("dev");
|
||||
RuntimeProfileSnapshot snapshot = RuntimeProfileSnapshot.from(environment);
|
||||
|
||||
environment.setActiveProfiles("prod");
|
||||
|
||||
assertThat(snapshot.activeProfiles()).containsExactly("dev");
|
||||
assertThat(snapshot.resolve()).contains(RuntimeEnvironment.DEV);
|
||||
assertThat(snapshot.isProduction()).isFalse();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -33,8 +33,7 @@ import org.springframework.context.SmartLifecycle;
|
||||
*/
|
||||
class MigrationStartupRunnerTest {
|
||||
|
||||
private final RuntimeSafetySettings settings =
|
||||
new RuntimeSafetySettings(false, true);
|
||||
private final RuntimeSafetySettings settings = new RuntimeSafetySettings(false, true);
|
||||
private final MigrationStartupRunner runner = new MigrationStartupRunner(settings);
|
||||
|
||||
@Test
|
||||
|
||||
Reference in New Issue
Block a user