diff --git a/.gitignore b/.gitignore index 835a593..792b359 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,5 @@ graphify-out/ .quinoa/ src/main/webui/node_modules/ src/main/webui/dist/ + +.gitattributes diff --git a/doc/access-control.md b/doc/access-control.md index e8568c0..f9c2d80 100644 --- a/doc/access-control.md +++ b/doc/access-control.md @@ -57,6 +57,8 @@ Endpoints check permissions, and each role grants a fixed set of them: | `api.simulation.read` | ✓ | ✓ | ✓ | | `api.environment.read` | ✓ | ✓ | ✓ | | `api.environment.write`| ✓ | | | +| `api.asset.read` | ✓ | ✓ | ✓ | +| `api.asset.write` | ✓ | | | | `api.metric.write` | ✓ | | | | `api.apikey.manage` | ✓ | ✓ | ✓ | | `api.apikey.admin` | ✓ | | ✓ | diff --git a/doc/distributed.md b/doc/distributed.md index 0d6392b..54fb03a 100644 --- a/doc/distributed.md +++ b/doc/distributed.md @@ -35,7 +35,7 @@ The mode also sets which functionalities an instance serves: | Feature | Serves | `standalone` | `aggregator` | `worker` | |-------------|--------------------------------------------------------------------------------|--------------|--------------|----------| | `ui` | the web UI and its dashboards, `GET /api/app` | ✓ | ✓ | | -| `api-read` | `/api/impact`, `/api/simulation`, `/api/environments`, `/api/modules` | ✓ | ✓ | | +| `api-read` | `/api/impact`, `/api/simulation`, `/api/environments`, `/api/assets`, `/api/modules` | ✓ | ✓ | | | `api-write` | `POST /api/workers/{worker}/metrics`, `PUT /api/workers/{worker}/environments` | | ✓ | | | `admin` | `/api/users`, `/api/keys`, `/api/secrets` | ✓ | ✓ | | diff --git a/src/main/java/tech/illuin/wombat/endpoint/AssetController.java b/src/main/java/tech/illuin/wombat/endpoint/AssetController.java new file mode 100644 index 0000000..05b0243 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/endpoint/AssetController.java @@ -0,0 +1,211 @@ +package tech.illuin.wombat.endpoint; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.quarkus.resteasy.reactive.server.EndpointDisabled; +import io.quarkus.security.PermissionsAllowed; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; +import org.eclipse.microprofile.openapi.annotations.media.Content; +import org.eclipse.microprofile.openapi.annotations.media.Schema; +import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty; +import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.jboss.resteasy.reactive.ResponseStatus; +import tech.illuin.wombat.endpoint.response.Response; +import tech.illuin.wombat.endpoint.response.Status; +import tech.illuin.wombat.engine.context.SlugHelper; +import tech.illuin.wombat.engine.context.asset.AssetConflictException; +import tech.illuin.wombat.engine.context.asset.AssetService; +import tech.illuin.wombat.engine.context.asset.InvalidAssetException; +import tech.illuin.wombat.engine.context.asset.UnknownAssetException; +import tech.illuin.wombat.engine.context.asset.model.AssetInfo; +import tech.illuin.wombat.engine.context.environment.UnknownEnvironmentException; +import tech.illuin.wombat.feature.Feature; +import tech.illuin.wombat.security.Permission; + +import java.util.List; +import java.util.Optional; + +import static jakarta.ws.rs.core.Response.Status.CONFLICT; + +/** + * The assets of every environment. Those declared by the monitored-environments file or a worker are provisioned, kept + * in sync by the {@link tech.illuin.wombat.engine.context.EnvironmentReconciler} and read-only here; the others are + * managed through this API. Soft-deleted assets are unknown. + */ +@Path("api/assets") +@EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") +@PermissionsAllowed(Permission.Names.API_ASSET_READ) +public class AssetController +{ + private final AssetService service; + + public AssetController(AssetService service) + { + this.service = service; + } + + @GET + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", type = SchemaType.ARRAY, implementation = AssetInfo.class) + }))) + @APIResponse(responseCode = "404", description = "Unknown environment") + public Response> list(@QueryParam("environmentId") String environmentId) + { + try { + return Response.success( + this.service.list(Optional.ofNullable(environmentId)).stream() + .map(AssetInfo::from) + .toList() + ); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + } + + @GET + @Path("/{id}") + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = AssetInfo.class) + }))) + @APIResponse(responseCode = "404", description = "Unknown asset") + public Response get(@PathParam("id") String id) + { + try { + return Response.success(AssetInfo.from(this.service.get(id))); + } + catch (UnknownAssetException e) { + throw new NotFoundException(e.getMessage()); + } + } + + @GET + @Path("/{uuid}/uuid") + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = AssetInfo.class) + }))) + @APIResponse(responseCode = "404", description = "Unknown asset") + public Response getByUuid(@PathParam("uuid") String uuid) + { + try { + return Response.success(AssetInfo.from(this.service.getByUuid(uuid))); + } + catch (UnknownAssetException e) { + throw new NotFoundException(e.getMessage()); + } + } + + @POST + @PermissionsAllowed(Permission.Names.API_ASSET_WRITE) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ResponseStatus(201) + @APIResponse(responseCode = "201", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = AssetInfo.class) + }))) + @APIResponse(responseCode = "400", description = "Invalid payload, unknown asset type or invalid properties") + @APIResponse(responseCode = "404", description = "Unknown environment") + @APIResponse(responseCode = "409", description = "An asset with this id already exists") + public Response create(@NotNull @Valid AssetCreateRequest request) + { + try { + return Response.success(AssetInfo.from(this.service.create( + request.id(), request.environmentId(), request.name(), request.type(), request.description(), request.disabled(), request.properties() + ))); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + catch (AssetConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + catch (InvalidAssetException e) { + throw new BadRequestException(e.getMessage()); + } + } + + @PUT + @Path("/{id}") + @PermissionsAllowed(Permission.Names.API_ASSET_WRITE) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = AssetInfo.class) + }))) + @APIResponse(responseCode = "400", description = "Invalid payload or properties") + @APIResponse(responseCode = "404", description = "Unknown asset") + @APIResponse(responseCode = "409", description = "The asset is provisioned") + public Response update(@PathParam("id") String id, @NotNull @Valid AssetUpdateRequest request) + { + try { + return Response.success(AssetInfo.from(this.service.update(id, request.name(), request.description(), request.disabled(), request.properties()))); + } + catch (UnknownAssetException e) { + throw new NotFoundException(e.getMessage()); + } + catch (AssetConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + catch (InvalidAssetException e) { + throw new BadRequestException(e.getMessage()); + } + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed(Permission.Names.API_ASSET_WRITE) + @APIResponse(responseCode = "204", description = "Soft-deleted") + @APIResponse(responseCode = "404", description = "Unknown asset") + @APIResponse(responseCode = "409", description = "The asset is provisioned") + public void delete(@PathParam("id") String id) + { + try { + this.service.delete(id); + } + catch (UnknownAssetException e) { + throw new NotFoundException(e.getMessage()); + } + catch (AssetConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + } + + /** + * The identity of the asset, and its type-specific {@code properties} (e.g. its {@code profile}) as they would be + * declared in the monitored-environments file, in JSON. + */ + public record AssetCreateRequest( + @NotBlank @Size(max = 64) @Pattern(regexp = SlugHelper.PATTERN, message = SlugHelper.MESSAGE) @JsonProperty("id") @Schema(required = true) String id, + @NotBlank @JsonProperty("environmentId") @Schema(required = true) String environmentId, + @NotBlank @Size(max = 255) @JsonProperty("name") @Schema(required = true) String name, + @NotBlank @JsonProperty("type") @Schema(required = true) String type, + @Size(max = 4096) @JsonProperty("description") String description, + @JsonProperty("disabled") boolean disabled, + @NotNull @JsonProperty("properties") @Schema(required = true) ObjectNode properties + ) {} + + /** + * Replaces the editable fields of an asset; its id, environment and type are immutable. + */ + public record AssetUpdateRequest( + @NotBlank @Size(max = 255) @JsonProperty("name") @Schema(required = true) String name, + @Size(max = 4096) @JsonProperty("description") String description, + @JsonProperty("disabled") boolean disabled, + @NotNull @JsonProperty("properties") @Schema(required = true) ObjectNode properties + ) {} +} diff --git a/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java b/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java index cddb1d9..a127287 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/EnvironmentController.java @@ -1,7 +1,13 @@ package tech.illuin.wombat.endpoint; +import com.fasterxml.jackson.annotation.JsonProperty; import io.quarkus.resteasy.reactive.server.EndpointDisabled; import io.quarkus.security.PermissionsAllowed; +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; import jakarta.ws.rs.*; import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.annotations.enums.SchemaType; @@ -9,36 +15,42 @@ import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import org.jboss.resteasy.reactive.ResponseStatus; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; -import tech.illuin.wombat.engine.context.model.AssetHistoryInfo; -import tech.illuin.wombat.engine.context.model.EnvironmentInfo; -import tech.illuin.wombat.engine.context.persistence.AssetConfigHistoryRepository; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; +import tech.illuin.wombat.engine.context.SlugHelper; +import tech.illuin.wombat.engine.context.asset.model.AssetHistoryInfo; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.EnvironmentConflictException; +import tech.illuin.wombat.engine.context.environment.EnvironmentService; +import tech.illuin.wombat.engine.context.environment.UnknownEnvironmentException; +import tech.illuin.wombat.engine.context.environment.model.EnvironmentInfo; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.security.Permission; import java.util.List; +import static jakarta.ws.rs.core.Response.Status.CONFLICT; + /** - * Read-only view of the persisted environment configuration. The monitored-environments YAML is the - * source of truth and is reconciled into the DB at startup (see {@link tech.illuin.wombat.engine.context.EnvironmentReconciler}), so - * this controller exposes the current state and the per-asset change history but never mutates config. + * The environments, with their assets and the per-asset change history. Those declared by the monitored-environments + * file or a worker are provisioned, kept in sync by the {@link tech.illuin.wombat.engine.context.EnvironmentReconciler} + * and read-only here; the others are managed through this API. Soft-deleted environments are unknown. */ @Path("api/environments") @EndpointDisabled(name = Feature.Keys.API_READ, stringValue = "false") @PermissionsAllowed(Permission.Names.API_ENVIRONMENT_READ) public class EnvironmentController { - private final EnvironmentRepository repository; + private final EnvironmentService service; private final AssetRepository assetRepository; private final AssetConfigHistoryRepository historyRepository; - public EnvironmentController(EnvironmentRepository repository, AssetRepository assetRepository, AssetConfigHistoryRepository historyRepository) + public EnvironmentController(EnvironmentService service, AssetRepository assetRepository, AssetConfigHistoryRepository historyRepository) { - this.repository = repository; + this.service = service; this.assetRepository = assetRepository; this.historyRepository = historyRepository; } @@ -60,12 +72,113 @@ public EnvironmentController(EnvironmentRepository repository, AssetRepository a public Response> list() { return Response.success( - this.repository.listAll().stream() + this.service.list().stream() .map(this::toInfo) .toList() ); } + @GET + @Path("/{id}") + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = EnvironmentInfo.class) + }))) + @APIResponse(responseCode = "404", description = "Unknown environment") + public Response get(@PathParam("id") String id) + { + try { + return Response.success(this.toInfo(this.service.get(id))); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + } + + @GET + @Path("/{uuid}/uuid") + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = EnvironmentInfo.class) + }))) + @APIResponse(responseCode = "404", description = "Unknown environment") + public Response getByUuid(@PathParam("uuid") String uuid) + { + try { + return Response.success(this.toInfo(this.service.getByUuid(uuid))); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + } + + @POST + @PermissionsAllowed(Permission.Names.API_ENVIRONMENT_WRITE) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ResponseStatus(201) + @APIResponse(responseCode = "201", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = EnvironmentInfo.class) + }))) + @APIResponse(responseCode = "400", description = "Invalid payload") + @APIResponse(responseCode = "409", description = "An environment with this id already exists") + public Response create(@NotNull @Valid EnvironmentCreateRequest request) + { + try { + return Response.success(this.toInfo(this.service.create(request.id(), request.name(), request.description(), request.disabled()))); + } + catch (EnvironmentConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + } + + @PUT + @Path("/{id}") + @PermissionsAllowed(Permission.Names.API_ENVIRONMENT_WRITE) + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @APIResponse(responseCode = "200", content = @Content(mediaType = MediaType.APPLICATION_JSON, schema = @Schema(properties = { + @SchemaProperty(name = "status", implementation = Status.class), + @SchemaProperty(name = "payload", implementation = EnvironmentInfo.class) + }))) + @APIResponse(responseCode = "400", description = "Invalid payload") + @APIResponse(responseCode = "404", description = "Unknown environment") + @APIResponse(responseCode = "409", description = "The environment is provisioned") + public Response update(@PathParam("id") String id, @NotNull @Valid EnvironmentUpdateRequest request) + { + try { + return Response.success(this.toInfo(this.service.update(id, request.name(), request.description(), request.disabled()))); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + catch (EnvironmentConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + } + + @DELETE + @Path("/{id}") + @PermissionsAllowed(Permission.Names.API_ENVIRONMENT_WRITE) + @APIResponse(responseCode = "204", description = "Soft-deleted") + @APIResponse(responseCode = "404", description = "Unknown environment") + @APIResponse(responseCode = "409", description = "The environment is provisioned, or still holds assets") + public void delete(@PathParam("id") String id) + { + try { + this.service.delete(id); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } + catch (EnvironmentConflictException e) { + throw new ClientErrorException(e.getMessage(), CONFLICT); + } + } + @GET @Path("/{id}/assets/{assetId}/history") @Produces(MediaType.APPLICATION_JSON) @@ -83,26 +196,37 @@ public Response> list() ) public Response> history(@PathParam("id") String id, @PathParam("assetId") String assetId) { - this.find(id); - return Response.success( - this.historyRepository.findByAsset(assetId).stream() - .map(AssetHistoryInfo::from) - .toList() - ); + try { + this.service.get(id); + return Response.success( + this.historyRepository.findByAsset(assetId).stream() + .map(AssetHistoryInfo::from) + .toList() + ); + } + catch (UnknownEnvironmentException e) { + throw new NotFoundException(e.getMessage()); + } } private EnvironmentInfo toInfo(EnvironmentEntity entity) { - return EnvironmentInfo.from(entity, this.assetRepository.findByEnvironment(entity.id)); + return EnvironmentInfo.from(entity, this.assetRepository.findVisibleByEnvironment(entity.id)); } - private EnvironmentEntity find(String id) - { - try { - return this.repository.findByIdOptional(id).orElseThrow(() -> new UnknownEnvironmentException(id)); - } - catch (UnknownEnvironmentException e) { - throw new NotFoundException(e); - } - } + public record EnvironmentCreateRequest( + @NotBlank @Size(max = 64) @Pattern(regexp = SlugHelper.PATTERN, message = SlugHelper.MESSAGE) @JsonProperty("id") @Schema(required = true) String id, + @NotBlank @Size(max = 255) @JsonProperty("name") @Schema(required = true) String name, + @Size(max = 4096) @JsonProperty("description") String description, + @JsonProperty("disabled") boolean disabled + ) {} + + /** + * Replaces the editable fields of an environment; its id is immutable. + */ + public record EnvironmentUpdateRequest( + @NotBlank @Size(max = 255) @JsonProperty("name") @Schema(required = true) String name, + @Size(max = 4096) @JsonProperty("description") String description, + @JsonProperty("disabled") boolean disabled + ) {} } diff --git a/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java b/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java index bf3e6c5..1f0ca3e 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/ImpactController.java @@ -10,6 +10,7 @@ import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; +import tech.illuin.wombat.engine.context.environment.UnknownEnvironmentException; import tech.illuin.wombat.core.asset.Environment; import tech.illuin.wombat.core.context.WombatContextProvider; import tech.illuin.wombat.core.activity.commons.AssetFilter; diff --git a/src/main/java/tech/illuin/wombat/endpoint/UnknownEnvironmentException.java b/src/main/java/tech/illuin/wombat/endpoint/UnknownEnvironmentException.java deleted file mode 100644 index c6c4e3f..0000000 --- a/src/main/java/tech/illuin/wombat/endpoint/UnknownEnvironmentException.java +++ /dev/null @@ -1,9 +0,0 @@ -package tech.illuin.wombat.endpoint; - -public class UnknownEnvironmentException extends Exception -{ - public UnknownEnvironmentException(String environmentId) - { - super("Unknown environment: " + environmentId); - } -} diff --git a/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java b/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java index 3858c86..6cb1d1e 100644 --- a/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java +++ b/src/main/java/tech/illuin/wombat/endpoint/WorkerController.java @@ -14,18 +14,16 @@ import org.eclipse.microprofile.openapi.annotations.media.Schema; import org.eclipse.microprofile.openapi.annotations.media.SchemaProperty; import org.eclipse.microprofile.openapi.annotations.responses.APIResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.Environment; import tech.illuin.wombat.core.source.Monitorable; import tech.illuin.wombat.endpoint.response.Response; import tech.illuin.wombat.endpoint.response.Status; -import tech.illuin.wombat.engine.context.EnvironmentConflictException; import tech.illuin.wombat.engine.context.EnvironmentReconciler; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; -import tech.illuin.wombat.engine.module.registry.ModuleMetadata; -import tech.illuin.wombat.engine.module.registry.ModuleRegistry; +import tech.illuin.wombat.engine.context.asset.AssetConflictException; +import tech.illuin.wombat.engine.context.asset.AssetValidator; +import tech.illuin.wombat.engine.context.asset.InvalidAssetException; +import tech.illuin.wombat.engine.context.environment.EnvironmentConflictException; import tech.illuin.wombat.engine.monitor.MonitoredEnvironments; import tech.illuin.wombat.feature.Feature; import tech.illuin.wombat.persistence.backend.push.PushBackendConfig; @@ -45,18 +43,16 @@ public class WorkerController { private final EnvironmentReconciler reconciler; - private final ModuleRegistry modules; + private final AssetValidator validator; private final JsonMapper assetMapper; - private static final Logger logger = LoggerFactory.getLogger(WorkerController.class); - public WorkerController( EnvironmentReconciler reconciler, - ModuleRegistry modules, + AssetValidator validator, JsonMapper assetMapper ) { this.reconciler = reconciler; - this.modules = modules; + this.validator = validator; this.assetMapper = assetMapper; } @@ -92,7 +88,7 @@ public Response declare( try { return Response.success(this.reconciler.reconcile(worker, this.qualify(worker, environments))); } - catch (EnvironmentConflictException e) { + catch (EnvironmentConflictException | AssetConflictException e) { throw new ClientErrorException(e.getMessage(), jakarta.ws.rs.core.Response.Status.CONFLICT); } } @@ -120,19 +116,18 @@ private Asset qualify(String worker, Asset asset) } /** - * This instance evaluates the asset, so it needs its module, and a worker only declares what it samples. A module - * disabled here does not reject the asset: its metrics are skipped when pushed, see {@link MetricController}. The - * asset's secrets are not checked: those of its source are resolved on the worker, and this instance may not know - * them. + * This instance evaluates the asset, so it needs its module, and a worker only declares what it samples, see + * {@link AssetValidator}. The asset's secrets are not checked: those of its source are resolved on the worker, and + * this instance may not know them. */ private void validate(Asset asset) { - if (asset instanceof UnrecognizedAsset unrecognized) - throw new BadRequestException("Unknown asset type " + unrecognized.rawType() + " for asset " + asset.identity().id()); - - ModuleMetadata module = this.modules.getModule(asset.type()).orElseThrow(() -> new BadRequestException("No module for asset type " + asset.type().name() + " of asset " + asset.identity().id())); - if (!module.enabled()) - logger.debug("Asset {} is declared with asset type {} whose module is disabled, its metrics will be skipped", asset.identity().id(), asset.type().name()); + try { + this.validator.validate(asset); + } + catch (InvalidAssetException e) { + throw new BadRequestException(e.getMessage()); + } if (!(asset instanceof Monitorable)) throw new BadRequestException("Asset " + asset.identity().id() + " of type " + asset.type().name() + " is not monitorable, declare it in the aggregator's environments file"); diff --git a/src/main/java/tech/illuin/wombat/engine/context/ContextConfig.java b/src/main/java/tech/illuin/wombat/engine/context/ContextConfig.java index 718f8a5..6001afd 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/ContextConfig.java +++ b/src/main/java/tech/illuin/wombat/engine/context/ContextConfig.java @@ -3,10 +3,10 @@ import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Singleton; import jakarta.ws.rs.Produces; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; import tech.illuin.wombat.core.context.WombatContextProvider; import tech.illuin.wombat.core.secret.SecretResolver; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; @ApplicationScoped public class ContextConfig diff --git a/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java b/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java index 6e8b4bd..3d2f451 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java +++ b/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java @@ -1,8 +1,5 @@ package tech.illuin.wombat.engine.context; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.json.JsonMapper; import io.quarkus.runtime.StartupEvent; import jakarta.annotation.Priority; import jakarta.enterprise.context.ApplicationScoped; @@ -10,15 +7,16 @@ import jakarta.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tech.illuin.wombat.engine.context.persistence.AssetConfigAction; -import tech.illuin.wombat.engine.context.persistence.AssetConfigHistory; -import tech.illuin.wombat.engine.context.persistence.AssetConfigHistoryRepository; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.Environment; +import tech.illuin.wombat.engine.context.asset.AssetConflictException; +import tech.illuin.wombat.engine.context.asset.AssetHistoryRecorder; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.EnvironmentConflictException; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; import tech.illuin.wombat.engine.monitor.MonitoredEnvironments; import java.util.ArrayList; @@ -38,8 +36,12 @@ *

* Each asset belongs to the declaration it comes from (its {@link AssetEntity#owner}), and a reconciliation only * creates, updates and soft-deletes the assets of its own owner, so the YAML and the workers can share an environment. - * An environment is disabled once nothing declares it anymore and none of its assets is left. Every asset change - * appends a row to {@link AssetConfigHistory}. + * An environment is soft-deleted once nothing declares it anymore and none of its assets is left. Every asset change + * is historized, see {@link AssetHistoryRecorder}. + *

+ * Environments and assets created through the API ({@code provisioned = false}) are never touched: a declaration + * clashing with one is an {@link EnvironmentConflictException} or an {@link AssetConflictException}, which fails the startup for the YAML and is a 409 for a + * worker. */ @ApplicationScoped public class EnvironmentReconciler @@ -48,22 +50,21 @@ public class EnvironmentReconciler public static final String LOCAL_OWNER = null; private static final Logger logger = LoggerFactory.getLogger(EnvironmentReconciler.class); - private static final ObjectMapper MAPPER = JsonMapper.builder().findAndAddModules().build(); private final EnvironmentRepository repository; private final AssetRepository assetRepository; - private final AssetConfigHistoryRepository historyRepository; + private final AssetHistoryRecorder history; private final MonitoredEnvironments monitoredEnvironments; public EnvironmentReconciler( EnvironmentRepository repository, AssetRepository assetRepository, - AssetConfigHistoryRepository historyRepository, + AssetHistoryRecorder history, MonitoredEnvironments monitoredEnvironments ) { this.repository = repository; this.assetRepository = assetRepository; - this.historyRepository = historyRepository; + this.history = history; this.monitoredEnvironments = monitoredEnvironments; } @@ -83,7 +84,7 @@ public Result reconcile(String owner, Map desired) Set desiredAssetIds = new HashSet<>(); for (Map.Entry entry : desired.entrySet()) { - this.reconcileEnvironment(entry.getKey(), entry.getValue()); + this.reconcileEnvironment(owner, entry.getKey(), entry.getValue()); for (Asset asset : entry.getValue().assets()) { desiredAssetIds.add(asset.identity().id()); @@ -96,12 +97,12 @@ else if (action == AssetConfigAction.UPDATE) } List deleted = this.deleteMissingAssets(owner, desiredAssetIds); - this.disableEmptyEnvironments(owner, desired.keySet(), deleted); + this.deleteEmptyEnvironments(owner, desired.keySet(), deleted); return new Result(created, updated, deleted.size()); } - private void reconcileEnvironment(String id, Environment environment) + private void reconcileEnvironment(String owner, String id, Environment environment) { Optional existing = this.repository.findByIdOptional(id); if (existing.isEmpty()) @@ -109,16 +110,20 @@ private void reconcileEnvironment(String id, Environment environment) EnvironmentEntity entity = new EnvironmentEntity(); entity.id = id; entity.name = environment.id(); + entity.provisioned = true; this.repository.persist(entity); logger.debug("Created environment {}", id); return; } EnvironmentEntity entity = existing.get(); - if (entity.disabledAt != null) + if (entity.deletedAt != null) { - entity.disabledAt = null; - logger.debug("Re-enabled environment {}", id); + entity.deletedAt = null; + entity.provisioned = true; + logger.debug("Restored environment {}", id); } + else if (!entity.provisioned) + throw new EnvironmentConflictException("Environment " + id + " declared by " + describe(owner) + " already exists, created through the API"); if (!entity.name.equals(environment.id())) { entity.name = environment.id(); @@ -135,7 +140,7 @@ private AssetConfigAction reconcileAsset(String owner, String environmentId, Ass AssetEntity entity = AssetEntity.from(environmentId, properties); entity.owner = owner; this.assetRepository.persist(entity); - this.recordHistory(AssetConfigAction.CREATE, entity); + this.history.record(AssetConfigAction.CREATE, entity); logger.debug("Created asset {} in environment {}", properties.identity().id(), environmentId); return AssetConfigAction.CREATE; } @@ -145,20 +150,23 @@ private AssetConfigAction reconcileAsset(String owner, String environmentId, Ass { entity.deletedAt = null; entity.owner = owner; + entity.provisioned = true; entity.environmentId = environmentId; entity.name = properties.identity().name(); entity.type = properties.type().name(); entity.properties = properties; - this.recordHistory(AssetConfigAction.CREATE, entity); + this.history.record(AssetConfigAction.CREATE, entity); logger.debug("Re-created (undeleted) asset {} in environment {}", properties.identity().id(), environmentId); return AssetConfigAction.CREATE; } + if (!entity.provisioned) + throw new AssetConflictException("Asset " + entity.id + " declared by " + describe(owner) + " already exists, created through the API"); boolean takenOver = !Objects.equals(entity.owner, owner); if (takenOver) { if (!Objects.equals(owner, LOCAL_OWNER)) - throw new EnvironmentConflictException("Asset " + entity.id + " is already declared by " + describe(entity.owner)); + throw new AssetConflictException("Asset " + entity.id + " is already declared by " + describe(entity.owner)); logger.warn("Asset {} declared by {} is now declared by {}", entity.id, describe(entity.owner), describe(owner)); entity.owner = owner; } @@ -173,7 +181,7 @@ private AssetConfigAction reconcileAsset(String owner, String environmentId, Ass entity.name = properties.identity().name(); entity.type = properties.type().name(); entity.properties = properties; - this.recordHistory(AssetConfigAction.UPDATE, entity); + this.history.record(AssetConfigAction.UPDATE, entity); logger.debug("Updated asset {} in environment {}", properties.identity().id(), environmentId); return AssetConfigAction.UPDATE; } @@ -183,40 +191,40 @@ private AssetConfigAction reconcileAsset(String owner, String environmentId, Ass private List deleteMissingAssets(String owner, Set desiredAssetIds) { List deleted = new ArrayList<>(); - for (AssetEntity entity : this.assetRepository.findActive()) + for (AssetEntity entity : this.assetRepository.findVisible()) { - if (desiredAssetIds.contains(entity.id) || !Objects.equals(entity.owner, owner)) + if (!entity.provisioned || desiredAssetIds.contains(entity.id) || !Objects.equals(entity.owner, owner)) continue; entity.deletedAt = EnvironmentEntity.now(); - this.recordHistory(AssetConfigAction.DELETE, entity); + this.history.record(AssetConfigAction.DELETE, entity); deleted.add(entity); logger.debug("Soft-deleted asset {} (no longer declared by {})", entity.id, describe(owner)); } return deleted; } - private void disableEmptyEnvironments(String owner, Set desiredEnvironmentIds, Collection deleted) + private void deleteEmptyEnvironments(String owner, Set desiredEnvironmentIds, Collection deleted) { Set declared = new HashSet<>(desiredEnvironmentIds); if (!Objects.equals(owner, LOCAL_OWNER)) declared.addAll(this.monitoredEnvironments.environments().keySet()); Set withAssets = new HashSet<>(); - for (AssetEntity entity : this.assetRepository.findActive()) + for (AssetEntity entity : this.assetRepository.findVisible()) { if (entity.deletedAt == null) withAssets.add(entity.environmentId); } Set candidates = deleted.stream().map(entity -> entity.environmentId).collect(Collectors.toSet()); - for (EnvironmentEntity entity : this.repository.findActive()) + for (EnvironmentEntity entity : this.repository.findVisible()) { - if (declared.contains(entity.id) || withAssets.contains(entity.id)) + if (!entity.provisioned || declared.contains(entity.id) || withAssets.contains(entity.id)) continue; if (!Objects.equals(owner, LOCAL_OWNER) && !candidates.contains(entity.id)) continue; - entity.disabledAt = EnvironmentEntity.now(); - logger.debug("Disabled environment {} (no longer declared, and without assets)", entity.id); + entity.deletedAt = EnvironmentEntity.now(); + logger.debug("Soft-deleted environment {} (no longer declared, and without assets)", entity.id); } } @@ -225,31 +233,9 @@ private static String describe(String owner) return Objects.equals(owner, LOCAL_OWNER) ? "the monitored-environments file" : "worker " + owner; } - private void recordHistory(AssetConfigAction action, AssetEntity entity) - { - this.historyRepository.persist(AssetConfigHistory.of(action, entity, snapshot(entity))); - } - - private static String snapshot(AssetEntity entity) - { - try { - return MAPPER.writeValueAsString(new AssetSnapshot(entity.id, entity.name, entity.type, entity.properties)); - } - catch (JsonProcessingException e) { - throw new IllegalStateException("Failed to serialize asset config snapshot for " + entity.id, e); - } - } - public record Result( int created, int updated, int deleted ) {} - - private record AssetSnapshot( - String id, - String name, - String type, - Asset data - ) {} } diff --git a/src/main/java/tech/illuin/wombat/engine/context/RepositoryContextProvider.java b/src/main/java/tech/illuin/wombat/engine/context/RepositoryContextProvider.java index 892f548..3871ce7 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/RepositoryContextProvider.java +++ b/src/main/java/tech/illuin/wombat/engine/context/RepositoryContextProvider.java @@ -2,17 +2,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.Environment; import tech.illuin.wombat.core.context.ResolvedContext; import tech.illuin.wombat.core.context.WombatContext; import tech.illuin.wombat.core.context.WombatContextProvider; import tech.illuin.wombat.core.secret.SecretResolver; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/tech/illuin/wombat/engine/context/SlugHelper.java b/src/main/java/tech/illuin/wombat/engine/context/SlugHelper.java new file mode 100644 index 0000000..f169ca7 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/SlugHelper.java @@ -0,0 +1,14 @@ +package tech.illuin.wombat.engine.context; + +/** + * The ids of the environments and assets created through the API. Those declared by the monitored-environments file + * or a worker are not held to it: worker assets are qualified as {@code workerId.assetId}, so they can never clash with + * one. + */ +public final class SlugHelper +{ + public static final String PATTERN = "^[a-z0-9_-]+$"; + public static final String MESSAGE = "must only contain lowercase letters, digits, dashes and underscores"; + + private SlugHelper() {} +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/AssetConflictException.java b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetConflictException.java new file mode 100644 index 0000000..fc85863 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetConflictException.java @@ -0,0 +1,12 @@ +package tech.illuin.wombat.engine.context.asset; + +/** + * An asset clashing with an existing one, or a provisioned asset edited through the API. + */ +public class AssetConflictException extends RuntimeException +{ + public AssetConflictException(String message) + { + super(message); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorder.java b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorder.java new file mode 100644 index 0000000..54a58cc --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorder.java @@ -0,0 +1,50 @@ +package tech.illuin.wombat.engine.context.asset; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; +import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistory; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; + +/** + * Appends a snapshot of an asset to its {@link AssetConfigHistory}, for every change: those applied by the + * {@link tech.illuin.wombat.engine.context.EnvironmentReconciler} and those made through the API. + */ +@ApplicationScoped +public class AssetHistoryRecorder +{ + private static final ObjectMapper MAPPER = JsonMapper.builder().findAndAddModules().build(); + + private final AssetConfigHistoryRepository repository; + + public AssetHistoryRecorder(AssetConfigHistoryRepository repository) + { + this.repository = repository; + } + + public void record(AssetConfigAction action, AssetEntity entity) + { + this.repository.persist(AssetConfigHistory.of(action, entity, snapshot(entity))); + } + + private static String snapshot(AssetEntity entity) + { + try { + return MAPPER.writeValueAsString(new AssetSnapshot(entity.id, entity.name, entity.type, entity.properties)); + } + catch (JsonProcessingException e) { + throw new IllegalStateException("Failed to serialize asset config snapshot for " + entity.id, e); + } + } + + private record AssetSnapshot( + String id, + String name, + String type, + Asset data + ) {} +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/AssetService.java b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetService.java new file mode 100644 index 0000000..ec88732 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetService.java @@ -0,0 +1,181 @@ +package tech.illuin.wombat.engine.context.asset; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.transaction.Transactional; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validator; +import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.EnvironmentService; +import tech.illuin.wombat.engine.context.environment.UnknownEnvironmentException; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Manages the assets created through the API. Provisioned ones (declared by the monitored-environments file or a + * worker) are read-only here, see {@link EnvironmentReconciler}; soft-deleted ones are unknown. Every change is + * historized, like those of the reconciler. + */ +@ApplicationScoped +public class AssetService +{ + private final AssetRepository repository; + private final EnvironmentRepository environmentRepository; + private final AssetHistoryRecorder history; + private final AssetValidator assetValidator; + private final Validator validator; + private final JsonMapper assetMapper; + + public AssetService( + AssetRepository repository, + EnvironmentRepository environmentRepository, + AssetHistoryRecorder history, + AssetValidator assetValidator, + Validator validator, + JsonMapper assetMapper + ) { + this.repository = repository; + this.environmentRepository = environmentRepository; + this.history = history; + this.assetValidator = assetValidator; + this.validator = validator; + this.assetMapper = assetMapper; + } + + @Transactional + public List list(Optional environmentId) + { + if (environmentId.isEmpty()) + return this.repository.findVisible(); + this.environment(environmentId.get()); + return this.repository.findVisibleByEnvironment(environmentId.get()); + } + + @Transactional + public AssetEntity get(String id) + { + return this.repository.findVisibleById(id).orElseThrow(() -> new UnknownAssetException(id)); + } + + @Transactional + public AssetEntity getByUuid(String uuid) + { + return this.repository.findVisibleByUuid(uuid).orElseThrow(() -> new UnknownAssetException(uuid)); + } + + /** + * Takes over a soft-deleted asset with the same id, which then keeps its uuid. Any environment can hold it, + * provisioned or not. The {@code properties} are the type-specific ones (e.g. its {@code profile}), in JSON. + */ + @Transactional + public AssetEntity create(String id, String environmentId, String name, String type, String description, boolean disabled, ObjectNode properties) + { + this.environment(environmentId); + Optional existing = this.repository.findByIdOptional(id); + if (existing.isPresent() && existing.get().deletedAt == null) + throw new AssetConflictException("Asset " + id + " already exists"); + + Asset asset = this.toAsset(id, environmentId, name, type, properties); + + AssetEntity entity = existing.orElseGet(AssetEntity::new); + entity.id = id; + entity.environmentId = environmentId; + entity.owner = null; + entity.provisioned = false; + entity.deletedAt = null; + entity.description = description; + entity.disabledAt = disabled ? EnvironmentEntity.now() : null; + apply(entity, asset); + if (existing.isEmpty()) + this.repository.persist(entity); + this.history.record(AssetConfigAction.CREATE, entity); + return entity; + } + + @Transactional + public AssetEntity update(String id, String name, String description, boolean disabled, ObjectNode properties) + { + AssetEntity entity = this.editable(id); + Asset asset = this.toAsset(entity.id, entity.environmentId, name, entity.type, properties); + + boolean changed = !entity.name.equals(name) || !entity.properties.equals(asset); + entity.description = description; + entity.disabledAt = EnvironmentService.disabledAt(entity.disabledAt, disabled); + if (changed) + { + apply(entity, asset); + this.history.record(AssetConfigAction.UPDATE, entity); + } + return entity; + } + + @Transactional + public void delete(String id) + { + AssetEntity entity = this.editable(id); + entity.deletedAt = EnvironmentEntity.now(); + this.history.record(AssetConfigAction.DELETE, entity); + } + + private AssetEntity editable(String id) + { + AssetEntity entity = this.get(id); + if (entity.provisioned) + throw new AssetConflictException("Asset " + id + " is provisioned, and cannot be edited"); + return entity; + } + + private EnvironmentEntity environment(String id) + { + return this.environmentRepository.findVisibleById(id).orElseThrow(() -> new UnknownEnvironmentException(id)); + } + + /** + * Reads the properties as the asset of the given type, its identity taking precedence over the one they may carry, + * then checks it as a declared one would be. + */ + private Asset toAsset(String id, String environmentId, String name, String type, ObjectNode properties) + { + ObjectNode node = properties.deepCopy(); + node.put("id", id); + node.put("environment-id", environmentId); + node.put("name", name); + node.put("type", type); + + try { + Asset asset = this.assetMapper.treeToValue(node, Asset.class); + + this.assetValidator.validate(asset); + + Set> violations = this.validator.validate(asset); + if (!violations.isEmpty()) + { + throw new InvalidAssetException("Invalid properties for asset " + id + ": " + violations.stream() + .map(violation -> violation.getPropertyPath() + " " + violation.getMessage()) + .sorted() + .collect(Collectors.joining(", "))); + } + return asset; + } + catch (JsonProcessingException e) { + throw new InvalidAssetException("Invalid properties for asset " + id + " of type " + type + ": " + e.getOriginalMessage()); + } + } + + private static void apply(AssetEntity entity, Asset properties) + { + entity.name = properties.identity().name(); + entity.type = properties.type().name(); + entity.properties = properties; + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/AssetValidator.java b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetValidator.java new file mode 100644 index 0000000..87b8535 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/AssetValidator.java @@ -0,0 +1,38 @@ +package tech.illuin.wombat.engine.context.asset; + +import jakarta.enterprise.context.ApplicationScoped; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.module.registry.ModuleMetadata; +import tech.illuin.wombat.engine.module.registry.ModuleRegistry; + +/** + * Checks an asset received through the API (pushed by a worker or created by a user) before it is persisted: its type + * must be known, and have a module on this instance. A module disabled here does not reject the asset, its metrics are + * skipped instead. + */ +@ApplicationScoped +public class AssetValidator +{ + private static final Logger logger = LoggerFactory.getLogger(AssetValidator.class); + + private final ModuleRegistry modules; + + public AssetValidator(ModuleRegistry modules) + { + this.modules = modules; + } + + public void validate(Asset asset) throws InvalidAssetException + { + if (asset instanceof UnrecognizedAsset unrecognized) + throw new InvalidAssetException("Unknown asset type " + unrecognized.rawType() + " for asset " + asset.identity().id()); + + ModuleMetadata module = this.modules.getModule(asset.type()) + .orElseThrow(() -> new InvalidAssetException("No module for asset type " + asset.type().name() + " of asset " + asset.identity().id())); + if (!module.enabled()) + logger.debug("Asset {} is declared with asset type {} whose module is disabled, its metrics will be skipped", asset.identity().id(), asset.type().name()); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/InvalidAssetException.java b/src/main/java/tech/illuin/wombat/engine/context/asset/InvalidAssetException.java new file mode 100644 index 0000000..be2f6c3 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/InvalidAssetException.java @@ -0,0 +1,9 @@ +package tech.illuin.wombat.engine.context.asset; + +public class InvalidAssetException extends RuntimeException +{ + public InvalidAssetException(String message) + { + super(message); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/UnknownAssetException.java b/src/main/java/tech/illuin/wombat/engine/context/asset/UnknownAssetException.java new file mode 100644 index 0000000..08fa232 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/UnknownAssetException.java @@ -0,0 +1,12 @@ +package tech.illuin.wombat.engine.context.asset; + +/** + * An asset that does not exist, or was soft-deleted. + */ +public class UnknownAssetException extends RuntimeException +{ + public UnknownAssetException(String assetId) + { + super("Unknown asset: " + assetId); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfo.java b/src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfo.java similarity index 81% rename from src/main/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfo.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfo.java index e21c63e..6a58106 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfo.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfo.java @@ -1,12 +1,12 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import com.fasterxml.jackson.annotation.JsonAlias; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; -import tech.illuin.wombat.engine.context.persistence.AssetConfigAction; -import tech.illuin.wombat.engine.context.persistence.AssetConfigHistory; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistory; import java.time.Instant; diff --git a/src/main/java/tech/illuin/wombat/engine/context/model/AssetInfo.java b/src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetInfo.java similarity index 74% rename from src/main/java/tech/illuin/wombat/engine/context/model/AssetInfo.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetInfo.java index 897f2e4..982617f 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/model/AssetInfo.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/model/AssetInfo.java @@ -1,9 +1,9 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonUnwrapped; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; import java.time.Instant; @@ -13,8 +13,11 @@ public record AssetInfo( String type, String uuid, String owner, + String description, + boolean provisioned, Instant createdAt, Instant updatedAt, + Instant disabledAt, Instant deletedAt ) { public AssetInfo(Asset properties, String uuid, Instant createdAt, Instant updatedAt, Instant deletedAt) @@ -24,8 +27,11 @@ public AssetInfo(Asset properties, String uuid, Instant createdAt, Instant updat properties.identity().assetType(), uuid, null, + null, + false, createdAt, updatedAt, + null, deletedAt ); } @@ -37,8 +43,11 @@ public static AssetInfo from(AssetEntity entity) entity.type, entity.uuid, entity.owner, + entity.description, + entity.provisioned, entity.createdAt, entity.updatedAt, + entity.disabledAt, entity.deletedAt ); } diff --git a/src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAsset.java b/src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAsset.java similarity index 95% rename from src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAsset.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAsset.java index d215974..4132437 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAsset.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAsset.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonUnwrapped; diff --git a/src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAssetProblemHandler.java b/src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAssetProblemHandler.java similarity index 95% rename from src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAssetProblemHandler.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAssetProblemHandler.java index fcf92c5..c75fc9d 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/model/UnrecognizedAssetProblemHandler.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/model/UnrecognizedAssetProblemHandler.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JavaType; diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigAction.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigAction.java similarity index 53% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigAction.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigAction.java index f4c3903..19085b3 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigAction.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigAction.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; public enum AssetConfigAction { diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistory.java similarity index 92% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistory.java index 25be8d8..5f2ad17 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistory.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import jakarta.persistence.Column; import jakarta.persistence.Entity; @@ -9,6 +9,7 @@ import jakarta.persistence.Id; import jakarta.persistence.PrePersist; import jakarta.persistence.Table; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; import java.time.Instant; diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistoryRepository.java similarity index 91% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistoryRepository.java index 07a5863..8d693c3 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConfigHistoryRepository.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import jakarta.enterprise.context.ApplicationScoped; import tech.illuin.wombat.persistence.backend.api.repository.Repository; diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConverter.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverter.java similarity index 92% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConverter.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverter.java index 392ecba..3f79ec2 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConverter.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverter.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.json.JsonMapper; @@ -6,8 +6,8 @@ import jakarta.inject.Inject; import jakarta.persistence.AttributeConverter; import jakarta.persistence.Converter; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; @Converter @ApplicationScoped diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntity.java similarity index 72% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java rename to src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntity.java index 9cd0be8..78ba9d0 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntity.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import jakarta.persistence.Column; import jakarta.persistence.Convert; @@ -8,6 +8,8 @@ import jakarta.persistence.PreUpdate; import jakarta.persistence.Table; import tech.illuin.wombat.core.asset.Asset; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.persistence.model.BooleanFlagConverter; import java.time.Instant; import java.util.UUID; @@ -32,6 +34,17 @@ public class AssetEntity @Column(nullable = false) public String type; + @Column + public String description; + + /** + * Declared by the monitored-environments file or a worker, and kept in sync by the reconciler: read-only for users. + * {@code false} for the assets created through the API. + */ + @Convert(converter = BooleanFlagConverter.class) + @Column(nullable = false, columnDefinition = "INTEGER") + public boolean provisioned; + @Convert(converter = AssetConverter.class) @Column(name = "properties", nullable = false) public Asset properties; @@ -42,6 +55,11 @@ public class AssetEntity @Column(name = "updated_at", nullable = false, columnDefinition = "INTEGER") public Instant updatedAt; + /** Inactive: skipped by processing, still returned by the API. */ + @Column(name = "disabled_at", columnDefinition = "INTEGER") + public Instant disabledAt; + + /** Soft delete: ignored everywhere. */ @Column(name = "deleted_at", columnDefinition = "INTEGER") public Instant deletedAt; @@ -80,6 +98,7 @@ public static AssetEntity from(String environmentId, Asset asset) entity.name = asset.identity().name(); entity.type = asset.identity().assetType(); entity.properties = asset; + entity.provisioned = true; return entity; } } diff --git a/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepository.java b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepository.java new file mode 100644 index 0000000..444f14e --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepository.java @@ -0,0 +1,69 @@ +package tech.illuin.wombat.engine.context.asset.persistence; + +import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Visible assets are those not soft-deleted, as the API and the reconciler see them; active ones are also not + * disabled, as processing sees them. + */ +@ApplicationScoped +public class AssetRepository extends Repository +{ + public AssetRepository() + { + super(AssetEntity.class); + } + + public List findByEnvironment(String environmentId) + { + return getEntityManager() + .createQuery("FROM AssetEntity WHERE environmentId = :environmentId AND deletedAt IS NULL AND disabledAt IS NULL", AssetEntity.class) + .setParameter("environmentId", environmentId) + .getResultList(); + } + + public List findVisibleByEnvironment(String environmentId) + { + return getEntityManager() + .createQuery("FROM AssetEntity WHERE environmentId = :environmentId AND deletedAt IS NULL", AssetEntity.class) + .setParameter("environmentId", environmentId) + .getResultList(); + } + + public long countVisibleByEnvironment(String environmentId) + { + return getEntityManager() + .createQuery("SELECT COUNT(a) FROM AssetEntity a WHERE a.environmentId = :environmentId AND a.deletedAt IS NULL", Long.class) + .setParameter("environmentId", environmentId) + .getSingleResult(); + } + + public List findVisible() + { + return getEntityManager() + .createQuery("FROM AssetEntity WHERE deletedAt IS NULL", AssetEntity.class) + .getResultList(); + } + + public Optional findVisibleById(String id) + { + return getEntityManager() + .createQuery("FROM AssetEntity WHERE id = :id AND deletedAt IS NULL", AssetEntity.class) + .setParameter("id", id) + .getResultStream() + .findFirst(); + } + + public Optional findVisibleByUuid(String uuid) + { + return getEntityManager() + .createQuery("FROM AssetEntity WHERE uuid = :uuid AND deletedAt IS NULL", AssetEntity.class) + .setParameter("uuid", uuid) + .getResultStream() + .findFirst(); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/EnvironmentConflictException.java b/src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentConflictException.java similarity index 74% rename from src/main/java/tech/illuin/wombat/engine/context/EnvironmentConflictException.java rename to src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentConflictException.java index cd6f199..e08ff6a 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/EnvironmentConflictException.java +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentConflictException.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context; +package tech.illuin.wombat.engine.context.environment; public class EnvironmentConflictException extends RuntimeException { diff --git a/src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentService.java b/src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentService.java new file mode 100644 index 0000000..2a9c635 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/EnvironmentService.java @@ -0,0 +1,106 @@ +package tech.illuin.wombat.engine.context.environment; + +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.transaction.Transactional; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; + +/** + * Manages the environments created through the API. Provisioned ones (declared by the monitored-environments file or a + * worker) are read-only here, see {@link EnvironmentReconciler}; soft-deleted ones are unknown. + */ +@ApplicationScoped +public class EnvironmentService +{ + private final EnvironmentRepository repository; + private final AssetRepository assetRepository; + + public EnvironmentService(EnvironmentRepository repository, AssetRepository assetRepository) + { + this.repository = repository; + this.assetRepository = assetRepository; + } + + @Transactional + public List list() + { + return this.repository.findVisible(); + } + + @Transactional + public EnvironmentEntity get(String id) + { + return this.repository.findVisibleById(id).orElseThrow(() -> new UnknownEnvironmentException(id)); + } + + @Transactional + public EnvironmentEntity getByUuid(String uuid) + { + return this.repository.findVisibleByUuid(uuid).orElseThrow(() -> new UnknownEnvironmentException(uuid)); + } + + /** + * Takes over a soft-deleted environment with the same id, which then keeps its uuid. + */ + @Transactional + public EnvironmentEntity create(String id, String name, String description, boolean disabled) + { + Optional existing = this.repository.findByIdOptional(id); + if (existing.isPresent() && existing.get().deletedAt == null) + throw new EnvironmentConflictException("Environment " + id + " already exists"); + + EnvironmentEntity entity = existing.orElseGet(EnvironmentEntity::new); + entity.id = id; + entity.name = name; + entity.description = description; + entity.provisioned = false; + entity.deletedAt = null; + entity.disabledAt = disabled ? EnvironmentEntity.now() : null; + if (existing.isEmpty()) + this.repository.persist(entity); + return entity; + } + + @Transactional + public EnvironmentEntity update(String id, String name, String description, boolean disabled) + { + EnvironmentEntity entity = this.editable(id); + entity.name = name; + entity.description = description; + entity.disabledAt = disabledAt(entity.disabledAt, disabled); + return entity; + } + + /** + * Soft-deletes an empty environment: its assets have to be deleted first. + */ + @Transactional + public void delete(String id) + { + EnvironmentEntity entity = this.editable(id); + if (this.assetRepository.countVisibleByEnvironment(id) > 0) + throw new EnvironmentConflictException("Environment " + id + " still holds assets"); + entity.deletedAt = EnvironmentEntity.now(); + } + + private EnvironmentEntity editable(String id) + { + EnvironmentEntity entity = this.get(id); + if (entity.provisioned) + throw new EnvironmentConflictException("Environment " + id + " is provisioned, and cannot be edited"); + return entity; + } + + /** Keeps the time it was disabled at while it stays disabled. */ + public static Instant disabledAt(Instant current, boolean disabled) + { + if (!disabled) + return null; + return current != null ? current : EnvironmentEntity.now(); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/environment/UnknownEnvironmentException.java b/src/main/java/tech/illuin/wombat/engine/context/environment/UnknownEnvironmentException.java new file mode 100644 index 0000000..7baf94a --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/UnknownEnvironmentException.java @@ -0,0 +1,12 @@ +package tech.illuin.wombat.engine.context.environment; + +/** + * An environment that does not exist, or was soft-deleted. + */ +public class UnknownEnvironmentException extends RuntimeException +{ + public UnknownEnvironmentException(String environmentId) + { + super("Unknown environment: " + environmentId); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/model/EnvironmentInfo.java b/src/main/java/tech/illuin/wombat/engine/context/environment/model/EnvironmentInfo.java similarity index 55% rename from src/main/java/tech/illuin/wombat/engine/context/model/EnvironmentInfo.java rename to src/main/java/tech/illuin/wombat/engine/context/environment/model/EnvironmentInfo.java index 0888b02..0e89143 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/model/EnvironmentInfo.java +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/model/EnvironmentInfo.java @@ -1,8 +1,9 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.environment.model; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.asset.model.AssetInfo; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; import java.time.Instant; import java.util.List; @@ -10,6 +11,8 @@ public record EnvironmentInfo( String id, String uuid, String name, + String description, + boolean provisioned, Instant createdAt, Instant updatedAt, Instant disabledAt, @@ -18,7 +21,7 @@ public record EnvironmentInfo( public static EnvironmentInfo from(EnvironmentEntity entity, List assets) { return new EnvironmentInfo( - entity.id, entity.uuid, entity.name, + entity.id, entity.uuid, entity.name, entity.description, entity.provisioned, entity.createdAt, entity.updatedAt, entity.disabledAt, assets.stream().map(AssetInfo::from).toList() ); diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java b/src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentEntity.java similarity index 65% rename from src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java rename to src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentEntity.java index aafcade..6d25849 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentEntity.java @@ -1,11 +1,13 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.environment.persistence; import jakarta.persistence.Column; +import jakarta.persistence.Convert; import jakarta.persistence.Entity; import jakarta.persistence.Id; import jakarta.persistence.PrePersist; import jakarta.persistence.PreUpdate; import jakarta.persistence.Table; +import tech.illuin.wombat.persistence.model.BooleanFlagConverter; import java.time.Instant; import java.time.temporal.ChronoUnit; @@ -24,15 +26,31 @@ public class EnvironmentEntity @Column(nullable = false) public String name; + @Column + public String description; + + /** + * Declared by the monitored-environments file or a worker, and kept in sync by the reconciler: read-only for users. + * {@code false} for the environments created through the API. + */ + @Convert(converter = BooleanFlagConverter.class) + @Column(nullable = false, columnDefinition = "INTEGER") + public boolean provisioned; + @Column(name = "created_at", nullable = false, columnDefinition = "INTEGER") public Instant createdAt; @Column(name = "updated_at", nullable = false, columnDefinition = "INTEGER") public Instant updatedAt; + /** Inactive: skipped by processing, still returned by the API. */ @Column(name = "disabled_at", columnDefinition = "INTEGER") public Instant disabledAt; + /** Soft delete: ignored everywhere. */ + @Column(name = "deleted_at", columnDefinition = "INTEGER") + public Instant deletedAt; + @PrePersist void onPersist() { diff --git a/src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepository.java b/src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepository.java new file mode 100644 index 0000000..ffe6938 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepository.java @@ -0,0 +1,52 @@ +package tech.illuin.wombat.engine.context.environment.persistence; + +import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; + +import java.util.List; +import java.util.Optional; + +/** + * Visible environments are those not soft-deleted, as the API sees them; active ones are also not disabled, as + * processing sees them. + */ +@ApplicationScoped +public class EnvironmentRepository extends Repository +{ + public EnvironmentRepository() + { + super(EnvironmentEntity.class); + } + + public List findActive() + { + return getEntityManager() + .createQuery("FROM EnvironmentEntity WHERE deletedAt IS NULL AND disabledAt IS NULL", EnvironmentEntity.class) + .getResultList(); + } + + public List findVisible() + { + return getEntityManager() + .createQuery("FROM EnvironmentEntity WHERE deletedAt IS NULL", EnvironmentEntity.class) + .getResultList(); + } + + public Optional findVisibleById(String id) + { + return getEntityManager() + .createQuery("FROM EnvironmentEntity WHERE id = :id AND deletedAt IS NULL", EnvironmentEntity.class) + .setParameter("id", id) + .getResultStream() + .findFirst(); + } + + public Optional findVisibleByUuid(String uuid) + { + return getEntityManager() + .createQuery("FROM EnvironmentEntity WHERE uuid = :uuid AND deletedAt IS NULL", EnvironmentEntity.class) + .setParameter("uuid", uuid) + .getResultStream() + .findFirst(); + } +} diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetRepository.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetRepository.java deleted file mode 100644 index 7b9ae3c..0000000 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetRepository.java +++ /dev/null @@ -1,30 +0,0 @@ -package tech.illuin.wombat.engine.context.persistence; - -import jakarta.enterprise.context.ApplicationScoped; -import tech.illuin.wombat.persistence.backend.api.repository.Repository; - -import java.util.List; - -@ApplicationScoped -public class AssetRepository extends Repository -{ - public AssetRepository() - { - super(AssetEntity.class); - } - - public List findByEnvironment(String environmentId) - { - return getEntityManager() - .createQuery("FROM AssetEntity WHERE environmentId = :environmentId AND deletedAt IS NULL", AssetEntity.class) - .setParameter("environmentId", environmentId) - .getResultList(); - } - - public List findActive() - { - return getEntityManager() - .createQuery("FROM AssetEntity WHERE deletedAt IS NULL", AssetEntity.class) - .getResultList(); - } -} diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepository.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepository.java deleted file mode 100644 index 4b1f967..0000000 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepository.java +++ /dev/null @@ -1,22 +0,0 @@ -package tech.illuin.wombat.engine.context.persistence; - -import jakarta.enterprise.context.ApplicationScoped; -import tech.illuin.wombat.persistence.backend.api.repository.Repository; - -import java.util.List; - -@ApplicationScoped -public class EnvironmentRepository extends Repository -{ - public EnvironmentRepository() - { - super(EnvironmentEntity.class); - } - - public List findActive() - { - return getEntityManager() - .createQuery("FROM EnvironmentEntity WHERE disabledAt IS NULL", EnvironmentEntity.class) - .getResultList(); - } -} diff --git a/src/main/java/tech/illuin/wombat/engine/module/WombatModuleConfig.java b/src/main/java/tech/illuin/wombat/engine/module/WombatModuleConfig.java index 199b3ed..94b6608 100644 --- a/src/main/java/tech/illuin/wombat/engine/module/WombatModuleConfig.java +++ b/src/main/java/tech/illuin/wombat/engine/module/WombatModuleConfig.java @@ -16,7 +16,7 @@ import jakarta.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import tech.illuin.wombat.engine.context.model.UnrecognizedAssetProblemHandler; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAssetProblemHandler; import tech.illuin.wombat.core.activity.WombatActivityResolver; import tech.illuin.wombat.core.activity.commons.ActivityData; import tech.illuin.wombat.core.activity.kubernetes.KubernetesActivityResolver; diff --git a/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretEntity.java b/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretEntity.java index 21ea68b..fd90957 100644 --- a/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretEntity.java +++ b/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretEntity.java @@ -10,7 +10,7 @@ import java.time.Instant; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; @Entity @Table(name = "secrets") diff --git a/src/main/java/tech/illuin/wombat/persistence/model/CompactionFlagConverter.java b/src/main/java/tech/illuin/wombat/persistence/model/BooleanFlagConverter.java similarity index 73% rename from src/main/java/tech/illuin/wombat/persistence/model/CompactionFlagConverter.java rename to src/main/java/tech/illuin/wombat/persistence/model/BooleanFlagConverter.java index 1d6da7a..f500d5e 100644 --- a/src/main/java/tech/illuin/wombat/persistence/model/CompactionFlagConverter.java +++ b/src/main/java/tech/illuin/wombat/persistence/model/BooleanFlagConverter.java @@ -4,11 +4,11 @@ import jakarta.persistence.Converter; /** - * Stores the compaction flag as 0/1. SQLite has no boolean type, and letting each dialect pick its + * Stores a boolean flag as 0/1. SQLite has no boolean type, and letting each dialect pick its * own would land the two migration chains on column types that are not equivalent. */ @Converter -public class CompactionFlagConverter implements AttributeConverter +public class BooleanFlagConverter implements AttributeConverter { @Override public Long convertToDatabaseColumn(Boolean attribute) diff --git a/src/main/java/tech/illuin/wombat/persistence/model/KubernetesMetricEntity.java b/src/main/java/tech/illuin/wombat/persistence/model/KubernetesMetricEntity.java index 015a565..0c6c450 100644 --- a/src/main/java/tech/illuin/wombat/persistence/model/KubernetesMetricEntity.java +++ b/src/main/java/tech/illuin/wombat/persistence/model/KubernetesMetricEntity.java @@ -34,7 +34,7 @@ public class KubernetesMetricEntity extends MetricEntity @Column(name = "ram_bytes", nullable = false, columnDefinition = "REAL") public double ramBytes; - @Convert(converter = CompactionFlagConverter.class) + @Convert(converter = BooleanFlagConverter.class) @Column(name = "compacted", nullable = false, columnDefinition = "INTEGER") public boolean compacted; } diff --git a/src/main/java/tech/illuin/wombat/persistence/model/LLMMetricEntity.java b/src/main/java/tech/illuin/wombat/persistence/model/LLMMetricEntity.java index 90b6667..64530ef 100644 --- a/src/main/java/tech/illuin/wombat/persistence/model/LLMMetricEntity.java +++ b/src/main/java/tech/illuin/wombat/persistence/model/LLMMetricEntity.java @@ -31,7 +31,7 @@ public class LLMMetricEntity extends MetricEntity @Column(name = "request_count", nullable = false, columnDefinition = "INTEGER") public long requestCount; - @Convert(converter = CompactionFlagConverter.class) + @Convert(converter = BooleanFlagConverter.class) @Column(name = "compacted", nullable = false, columnDefinition = "INTEGER") public boolean compacted; } diff --git a/src/main/java/tech/illuin/wombat/security/Permission.java b/src/main/java/tech/illuin/wombat/security/Permission.java index 6d34573..86b84e7 100644 --- a/src/main/java/tech/illuin/wombat/security/Permission.java +++ b/src/main/java/tech/illuin/wombat/security/Permission.java @@ -12,6 +12,8 @@ public enum Permission API_SIMULATION_READ(Names.API_SIMULATION_READ, true), API_ENVIRONMENT_READ(Names.API_ENVIRONMENT_READ, true), API_ENVIRONMENT_WRITE(Names.API_ENVIRONMENT_WRITE, true), + API_ASSET_READ(Names.API_ASSET_READ, true), + API_ASSET_WRITE(Names.API_ASSET_WRITE, true), API_METRIC_WRITE(Names.API_METRIC_WRITE, true), API_MODULE_READ(Names.API_MODULE_READ, true), API_APIKEY_MANAGE(Names.API_APIKEY_MANAGE, false), @@ -57,6 +59,8 @@ public static final class Names public static final String API_MODULE_READ = "api.module.read"; public static final String API_ENVIRONMENT_READ = "api.environment.read"; public static final String API_ENVIRONMENT_WRITE = "api.environment.write"; + public static final String API_ASSET_READ = "api.asset.read"; + public static final String API_ASSET_WRITE = "api.asset.write"; public static final String API_METRIC_WRITE = "api.metric.write"; public static final String API_APIKEY_MANAGE = "api.apikey.manage"; public static final String API_APIKEY_ADMIN = "api.apikey.admin"; diff --git a/src/main/java/tech/illuin/wombat/security/Role.java b/src/main/java/tech/illuin/wombat/security/Role.java index a4482b6..af0aa36 100644 --- a/src/main/java/tech/illuin/wombat/security/Role.java +++ b/src/main/java/tech/illuin/wombat/security/Role.java @@ -60,6 +60,7 @@ private static final class Base API_IMPACT_READ, API_SIMULATION_READ, API_ENVIRONMENT_READ, + API_ASSET_READ, API_MODULE_READ )); diff --git a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java index c8145a3..fc456e4 100644 --- a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java +++ b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java @@ -13,7 +13,7 @@ import java.util.Set; import java.util.UUID; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; /** A key belongs to the user who created it, and never grants more than its owner currently holds. */ @Entity diff --git a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java index 505b5a0..c2cc6b4 100644 --- a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java +++ b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java @@ -25,7 +25,7 @@ import java.util.function.Function; import java.util.stream.Collectors; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; /** Every user manages their own API keys, admins see and revoke everyone's; a key never grants more than its owner holds. */ @ApplicationScoped diff --git a/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java b/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java index 248e2cb..7ef0318 100644 --- a/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java +++ b/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java @@ -9,7 +9,7 @@ import java.time.Instant; import java.util.UUID; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; /** A Wombat role granted to a user by an admin, held on top of the roles mapped from the identity provider. */ @Entity diff --git a/src/main/java/tech/illuin/wombat/security/user/UserEntity.java b/src/main/java/tech/illuin/wombat/security/user/UserEntity.java index 43bacc1..77326bd 100644 --- a/src/main/java/tech/illuin/wombat/security/user/UserEntity.java +++ b/src/main/java/tech/illuin/wombat/security/user/UserEntity.java @@ -14,7 +14,7 @@ import java.util.Set; import java.util.UUID; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; /** * A user who signed in at least once. {@code roles} are the ones mapped from the identity provider and {@code auth.roles.*} diff --git a/src/main/java/tech/illuin/wombat/security/user/UserService.java b/src/main/java/tech/illuin/wombat/security/user/UserService.java index 4ab3f6e..a024a11 100644 --- a/src/main/java/tech/illuin/wombat/security/user/UserService.java +++ b/src/main/java/tech/illuin/wombat/security/user/UserService.java @@ -8,7 +8,7 @@ import java.util.EnumSet; import java.util.List; -import static tech.illuin.wombat.engine.context.persistence.EnvironmentEntity.now; +import static tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity.now; @ApplicationScoped public class UserService diff --git a/src/main/resources/db/migration/postgresql/V14__editable_assets.sql b/src/main/resources/db/migration/postgresql/V14__editable_assets.sql new file mode 100644 index 0000000..67d9bfd --- /dev/null +++ b/src/main/resources/db/migration/postgresql/V14__editable_assets.sql @@ -0,0 +1,14 @@ +-- Environments and assets become editable through the API. `provisioned` tells the rows declared by the +-- monitored-environments file or a worker (read-only, reconciled) from those created by users; every existing row +-- comes from a declaration. deleted_at is a soft delete (hidden everywhere), disabled_at an inactive state (skipped +-- by processing, still returned by the API). +ALTER TABLE environments ADD COLUMN description TEXT; +ALTER TABLE environments ADD COLUMN provisioned BIGINT NOT NULL DEFAULT 1; +ALTER TABLE environments ADD COLUMN deleted_at TIMESTAMP WITH TIME ZONE; + +-- Until now disabled_at was only set by the reconciler once nothing declared the environment: a soft delete. +UPDATE environments SET deleted_at = disabled_at, disabled_at = NULL WHERE disabled_at IS NOT NULL; + +ALTER TABLE assets ADD COLUMN description TEXT; +ALTER TABLE assets ADD COLUMN provisioned BIGINT NOT NULL DEFAULT 1; +ALTER TABLE assets ADD COLUMN disabled_at TIMESTAMP WITH TIME ZONE; diff --git a/src/main/resources/db/migration/sqlite/V23__editable_assets.sql b/src/main/resources/db/migration/sqlite/V23__editable_assets.sql new file mode 100644 index 0000000..6c2d7e0 --- /dev/null +++ b/src/main/resources/db/migration/sqlite/V23__editable_assets.sql @@ -0,0 +1,14 @@ +-- Environments and assets become editable through the API. `provisioned` tells the rows declared by the +-- monitored-environments file or a worker (read-only, reconciled) from those created by users; every existing row +-- comes from a declaration. deleted_at is a soft delete (hidden everywhere), disabled_at an inactive state (skipped +-- by processing, still returned by the API). +ALTER TABLE environments ADD COLUMN description TEXT; +ALTER TABLE environments ADD COLUMN provisioned INTEGER NOT NULL DEFAULT 1; +ALTER TABLE environments ADD COLUMN deleted_at INTEGER; + +-- Until now disabled_at was only set by the reconciler once nothing declared the environment: a soft delete. +UPDATE environments SET deleted_at = disabled_at, disabled_at = NULL WHERE disabled_at IS NOT NULL; + +ALTER TABLE assets ADD COLUMN description TEXT; +ALTER TABLE assets ADD COLUMN provisioned INTEGER NOT NULL DEFAULT 1; +ALTER TABLE assets ADD COLUMN disabled_at INTEGER; diff --git a/src/main/webui/src/domain/access.ts b/src/main/webui/src/domain/access.ts index e7c6971..1a1c119 100644 --- a/src/main/webui/src/domain/access.ts +++ b/src/main/webui/src/domain/access.ts @@ -6,6 +6,8 @@ export type Permission = | 'api.simulation.read' | 'api.environment.read' | 'api.environment.write' + | 'api.asset.read' + | 'api.asset.write' | 'api.metric.write' | 'api.apikey.manage' | 'api.apikey.admin' diff --git a/src/main/webui/src/domain/environment.spec.ts b/src/main/webui/src/domain/environment.spec.ts index 99d1ecd..142f04e 100644 --- a/src/main/webui/src/domain/environment.spec.ts +++ b/src/main/webui/src/domain/environment.spec.ts @@ -2,11 +2,12 @@ import {describe, expect, it} from 'vitest' import {findUnrecognizedAssets, withOwners, type AssetInfo} from '@/domain/environment' describe('unrecognized asset derivation', () => { - it('keeps only undeleted database assets missing from the live environment', () => { + it('keeps only undeleted, enabled database assets missing from the live environment', () => { const databaseAssets: AssetInfo[] = [ {id: 'active', name: 'Active', type: 'container'}, {id: 'unknown', name: 'Unknown', type: 'custom'}, {id: 'deleted', name: 'Deleted', type: 'custom', deletedAt: '2026-01-01T00:00:00Z'}, + {id: 'disabled', name: 'Disabled', type: 'custom', disabledAt: '2026-01-01T00:00:00Z'}, ] const liveAssets: AssetInfo[] = [{id: 'active', name: 'Active', type: {namespace: 'test', localName: 'container', name: 'Container', regime: 'MEASURED', family: 'KUBERNETES_CONTAINER'}}] diff --git a/src/main/webui/src/domain/environment.ts b/src/main/webui/src/domain/environment.ts index 9566bc7..e925fe0 100644 --- a/src/main/webui/src/domain/environment.ts +++ b/src/main/webui/src/domain/environment.ts @@ -18,6 +18,9 @@ export interface AssetInfo { type?: string | AssetType namespace?: string | null profile?: unknown + description?: string | null + provisioned?: boolean + disabledAt?: string | null deletedAt?: string | null [key: string]: unknown } @@ -26,6 +29,9 @@ export interface EnvironmentInfo { id: string uuid?: string name: string | null + description?: string | null + provisioned?: boolean + disabledAt?: string | null assets: AssetInfo[] } @@ -36,10 +42,10 @@ export interface LiveEnvironment { assets: AssetInfo[] } -/** Database assets outside the active runtime context, excluding soft-deleted records. */ +/** Database assets outside the active runtime context, excluding soft-deleted and disabled records (left out on purpose). */ export function findUnrecognizedAssets(databaseAssets: readonly AssetInfo[], liveAssets: readonly AssetInfo[]): AssetInfo[] { const liveIds = new Set(liveAssets.map(asset => asset.id)) - return databaseAssets.filter(asset => asset.deletedAt == null && !liveIds.has(asset.id)) + return databaseAssets.filter(asset => asset.deletedAt == null && asset.disabledAt == null && !liveIds.has(asset.id)) } /** The live assets with the worker owning each one, which only the database records know. */ diff --git a/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java b/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java index 110daa6..9f295e7 100644 --- a/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java +++ b/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java @@ -14,6 +14,9 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; import tech.illuin.wombat.module.llm_prometheus.LLMPrometheusModule; import tech.illuin.wombat.module.llm_anthropic.LLMAnthropicModule; import tech.illuin.wombat.module.kubernetes_api.KubernetesAPIModule; @@ -32,9 +35,6 @@ import tech.illuin.wombat.core.source.persistence.WombatMetricPersister; import tech.illuin.wombat.core.source.Period; import tech.illuin.wombat.core.source.persistence.micrometer.MicrometerMetricPersister; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; import tech.illuin.wombat.engine.impact.kubernetes.KubernetesMetricRepository; import tech.illuin.wombat.engine.impact.llm.LLMModelMetricRepository; import tech.illuin.wombat.engine.monitor.MonitoredEnvironments; @@ -177,8 +177,8 @@ void workers_declareTheirEnvironments_whichTheAggregatorEvaluatesAsTheirs() assertEquals("east.declared", this.asset("east.declared").properties.identity().id()); assertEquals("west", this.asset("west.declared").owner); assertNull(this.asset("declared")); - assertNull(this.environments.findById("east").disabledAt); - assertNull(this.environments.findById("west").disabledAt); + assertNull(this.environments.findById("east").deletedAt); + assertNull(this.environments.findById("west").deletedAt); } @Test diff --git a/src/test/java/tech/illuin/wombat/endpoint/AssetControllerTest.java b/src/test/java/tech/illuin/wombat/endpoint/AssetControllerTest.java new file mode 100644 index 0000000..fbf2f32 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/endpoint/AssetControllerTest.java @@ -0,0 +1,224 @@ +package tech.illuin.wombat.endpoint; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.core.context.WombatContextProvider; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; +import tech.illuin.wombat.module.llm_static.LLMStaticModule; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.hasItem; +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The test profile provisions the environment {@code test}, holding the asset {@code test-llm}. + */ +@QuarkusTest +class AssetControllerTest +{ + private static final String ENVIRONMENT = "asset-controller-env"; + private static final String ASSET = "asset-controller-llm"; + + @Inject EnvironmentRepository environments; + @Inject AssetRepository assets; + @Inject AssetConfigHistoryRepository history; + @Inject WombatContextProvider context; + + @BeforeEach + void setUp() + { + this.clean(); + given().contentType(ContentType.JSON) + .body(Map.of("id", ENVIRONMENT, "name", "Asset controller")) + .when().post("/api/environments") + .then().statusCode(201); + } + + @AfterEach + void clean() + { + ContextControllerCleanup.clean(this.environments, this.assets, this.history, List.of(ENVIRONMENT), List.of(ASSET)); + } + + @Test + void get_provisioned_byIdAndUuid() + { + String uuid = given() + .when().get("/api/assets/test-llm") + .then() + .statusCode(200) + .body("payload.id", is("test-llm")) + .body("payload.environmentId", is("test")) + .body("payload.type", is(LLMStaticModule.TYPE.name())) + .body("payload.provisioned", is(true)) + .extract().path("payload.uuid"); + + given().when().get("/api/assets/" + uuid + "/uuid").then().statusCode(200).body("payload.id", is("test-llm")); + } + + @Test + void get_unknown_returns404() + { + given().when().get("/api/assets/does-not-exist").then().statusCode(404); + given().when().get("/api/assets/does-not-exist/uuid").then().statusCode(404); + } + + @Test + void list_filtersByEnvironment() + { + this.create(ASSET, ENVIRONMENT).then().statusCode(201); + + given().when().get("/api/assets").then().statusCode(200).body("payload.id", hasItems("test-llm", ASSET)); + given().queryParam("environmentId", ENVIRONMENT) + .when().get("/api/assets") + .then().statusCode(200).body("payload.id", is(List.of(ASSET))); + given().queryParam("environmentId", "does-not-exist").when().get("/api/assets").then().statusCode(404); + } + + @Test + void create_update_delete() + { + String uuid = this.create(ASSET, ENVIRONMENT) + .then() + .statusCode(201) + .body("payload.id", is(ASSET)) + .body("payload.environmentId", is(ENVIRONMENT)) + .body("payload.name", is("Asset controller LLM")) + .body("payload.description", is("Described")) + .body("payload.type", is(LLMStaticModule.TYPE.name())) + .body("payload.provisioned", is(false)) + .body("payload.profile", notNullValue()) + .extract().path("payload.uuid"); + assertTrue(this.activeAssets().contains(ASSET)); + + Map update = new HashMap<>(); + update.put("name", "Renamed"); + update.put("disabled", true); + update.put("properties", properties()); + given().contentType(ContentType.JSON) + .body(update) + .when().put("/api/assets/" + ASSET) + .then() + .statusCode(200) + .body("payload.name", is("Renamed")) + .body("payload.description", nullValue()) + .body("payload.disabledAt", notNullValue()); + + // Disabled: still served, but skipped by processing. + given().when().get("/api/assets/" + uuid + "/uuid").then().statusCode(200).body("payload.name", is("Renamed")); + assertFalse(this.activeAssets().contains(ASSET)); + + given().when().delete("/api/assets/" + ASSET).then().statusCode(204); + + given().when().get("/api/assets/" + ASSET).then().statusCode(404); + given().when().get("/api/assets").then().statusCode(200).body("payload.id", not(hasItem(ASSET))); + given().when().get("/api/environments/" + ENVIRONMENT + "/assets/" + ASSET + "/history") + .then().statusCode(200).body("payload.action", is(List.of("CREATE", "UPDATE", "DELETE"))); + } + + @Test + void create_inAProvisionedEnvironment() + { + this.create(ASSET, "test").then().statusCode(201).body("payload.environmentId", is("test")); + } + + @Test + void create_invalidPayload_returns400() + { + this.create("Not A Slug", ENVIRONMENT).then().statusCode(400); + + Map missingProperties = createBody(ASSET, ENVIRONMENT, properties()); + missingProperties.remove("properties"); + given().contentType(ContentType.JSON).body(missingProperties).when().post("/api/assets").then().statusCode(400); + + Map unknownType = createBody(ASSET, ENVIRONMENT, properties()); + unknownType.put("type", "tech.illuin.unknown"); + given().contentType(ContentType.JSON).body(unknownType).when().post("/api/assets").then().statusCode(400); + + Map invalidProperties = createBody(ASSET, ENVIRONMENT, Map.of("profile", Map.of("models", "not-a-list"))); + given().contentType(ContentType.JSON).body(invalidProperties).when().post("/api/assets").then().statusCode(400); + } + + @Test + void create_unknownEnvironment_returns404() + { + this.create(ASSET, "does-not-exist").then().statusCode(404); + } + + @Test + void create_existing_returns409() + { + this.create("test-llm", ENVIRONMENT).then().statusCode(409); + this.create(ASSET, ENVIRONMENT).then().statusCode(201); + this.create(ASSET, ENVIRONMENT).then().statusCode(409); + } + + @Test + void updateAndDelete_provisioned_return409() + { + given().contentType(ContentType.JSON) + .body(Map.of("name", "Test LLM", "properties", properties())) + .when().put("/api/assets/test-llm") + .then().statusCode(409); + given().when().delete("/api/assets/test-llm").then().statusCode(409); + } + + @Test + void update_unknown_returns404() + { + given().contentType(ContentType.JSON) + .body(Map.of("name", "Nope", "properties", properties())) + .when().put("/api/assets/does-not-exist") + .then().statusCode(404); + } + + private io.restassured.response.Response create(String id, String environmentId) + { + return given().contentType(ContentType.JSON).body(createBody(id, environmentId, properties())).when().post("/api/assets"); + } + + static Map createBody(String id, String environmentId, Map properties) + { + Map body = new HashMap<>(); + body.put("id", id); + body.put("environmentId", environmentId); + body.put("name", "Asset controller LLM"); + body.put("type", LLMStaticModule.TYPE.name()); + body.put("description", "Described"); + body.put("properties", properties); + return body; + } + + /** The type-specific properties of the provisioned llm-static asset, as the API serves them. */ + static Map properties() + { + Map asset = new HashMap<>(given().when().get("/api/assets/test-llm").then().statusCode(200).extract().path("payload")); + for (String key : List.of("id", "environmentId", "name", "type", "uuid", "owner", "description", "provisioned", "createdAt", "updatedAt", "disabledAt", "deletedAt")) + asset.remove(key); + return asset; + } + + private List activeAssets() + { + return this.context.provide().environments().stream() + .flatMap(environment -> environment.assets().stream()) + .map(asset -> asset.identity().id()) + .toList(); + } +} diff --git a/src/test/java/tech/illuin/wombat/endpoint/ContextControllerCleanup.java b/src/test/java/tech/illuin/wombat/endpoint/ContextControllerCleanup.java new file mode 100644 index 0000000..cb6c490 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/endpoint/ContextControllerCleanup.java @@ -0,0 +1,29 @@ +package tech.illuin.wombat.endpoint; + +import io.quarkus.narayana.jta.QuarkusTransaction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; + +import java.util.List; + +/** Removes the environments and assets a controller test created through the API, with their history. */ +final class ContextControllerCleanup +{ + private ContextControllerCleanup() {} + + static void clean( + EnvironmentRepository environments, AssetRepository assets, AssetConfigHistoryRepository history, + List environmentIds, List assetIds + ) { + QuarkusTransaction.requiringNew().run(() -> { + for (String id : assetIds) + { + assets.findByIdOptional(id).ifPresent(assets::delete); + history.findByAsset(id).forEach(history::delete); + } + for (String id : environmentIds) + environments.findByIdOptional(id).ifPresent(environments::delete); + }); + } +} diff --git a/src/test/java/tech/illuin/wombat/endpoint/EnvironmentControllerTest.java b/src/test/java/tech/illuin/wombat/endpoint/EnvironmentControllerTest.java index a6294ff..4db8a81 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/EnvironmentControllerTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/EnvironmentControllerTest.java @@ -1,11 +1,22 @@ package tech.illuin.wombat.endpoint; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static io.restassured.RestAssured.given; import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -13,6 +24,18 @@ @QuarkusTest class EnvironmentControllerTest { + private static final String CREATED = "env-controller"; + + @Inject EnvironmentRepository environments; + @Inject AssetRepository assets; + @Inject AssetConfigHistoryRepository history; + + @AfterEach + void clean() + { + ContextControllerCleanup.clean(this.environments, this.assets, this.history, List.of(CREATED), List.of("env-controller-asset")); + } + @Test void list_returnsReconciledEnvironments() { @@ -23,6 +46,7 @@ void list_returnsReconciledEnvironments() .body("payload.id", hasItem("test")) .body("payload.find { it.id == 'test' }.name", is("test")) .body("payload.find { it.id == 'test' }.uuid", notNullValue()) + .body("payload.find { it.id == 'test' }.provisioned", is(true)) .body("payload.find { it.id == 'test' }.'createdAt'", notNullValue()) .body("payload.find { it.id == 'test' }.'disabledAt'", nullValue()) .body("payload.find { it.id == 'test' }.assets.id", hasItem("test-cluster")) @@ -30,12 +54,117 @@ void list_returnsReconciledEnvironments() .body("payload.find { it.id == 'test' }.assets.find { it.id == 'test-cluster' }.namespace", is("test-ns")) .body("payload.find { it.id == 'test' }.assets.find { it.id == 'test-cluster' }.environmentId", is("test")) .body("payload.find { it.id == 'test' }.assets.find { it.id == 'test-cluster' }.profile.'instanceType'", is("c5.large")) + .body("payload.find { it.id == 'test' }.assets.find { it.id == 'test-cluster' }.provisioned", is(true)) .body("payload.find { it.id == 'test' }.assets.find { it.id == 'test-cluster' }.'createdAt'", notNullValue()) .extract().asString(); assertFalse(response.contains("\"environment-id\"")); assertFalse(response.contains("\"instance-type\"")); } + @Test + void get_byIdAndUuid() + { + String uuid = given() + .when().get("/api/environments/test") + .then() + .statusCode(200) + .body("payload.id", is("test")) + .body("payload.provisioned", is(true)) + .body("payload.assets.id", hasItem("test-llm")) + .extract().path("payload.uuid"); + + given().when().get("/api/environments/" + uuid + "/uuid").then().statusCode(200).body("payload.id", is("test")); + } + + @Test + void get_unknown_returns404() + { + given().when().get("/api/environments/does-not-exist").then().statusCode(404); + given().when().get("/api/environments/does-not-exist/uuid").then().statusCode(404); + } + + @Test + void create_update_delete() + { + String uuid = this.create(CREATED) + .then() + .statusCode(201) + .body("payload.id", is(CREATED)) + .body("payload.name", is("Env controller")) + .body("payload.description", is("Described")) + .body("payload.provisioned", is(false)) + .body("payload.disabledAt", nullValue()) + .extract().path("payload.uuid"); + + given().contentType(ContentType.JSON) + .body(Map.of("name", "Renamed", "disabled", true)) + .when().put("/api/environments/" + CREATED) + .then() + .statusCode(200) + .body("payload.name", is("Renamed")) + .body("payload.description", nullValue()) + .body("payload.disabledAt", notNullValue()); + + given().when().get("/api/environments/" + uuid + "/uuid").then().statusCode(200).body("payload.name", is("Renamed")); + + given().when().delete("/api/environments/" + CREATED).then().statusCode(204); + + given().when().get("/api/environments/" + CREATED).then().statusCode(404); + given().when().get("/api/environments/" + uuid + "/uuid").then().statusCode(404); + given().when().get("/api/environments").then().statusCode(200).body("payload.id", not(hasItem(CREATED))); + given().when().delete("/api/environments/" + CREATED).then().statusCode(404); + } + + @Test + void create_invalidPayload_returns400() + { + this.create("Not A Slug").then().statusCode(400); + given().contentType(ContentType.JSON) + .body(Map.of("id", CREATED)) + .when().post("/api/environments") + .then().statusCode(400); + } + + @Test + void create_existing_returns409() + { + this.create("test").then().statusCode(409); + this.create(CREATED).then().statusCode(201); + this.create(CREATED).then().statusCode(409); + } + + @Test + void updateAndDelete_provisioned_return409() + { + given().contentType(ContentType.JSON) + .body(Map.of("name", "test")) + .when().put("/api/environments/test") + .then().statusCode(409); + given().when().delete("/api/environments/test").then().statusCode(409); + } + + @Test + void update_unknown_returns404() + { + given().contentType(ContentType.JSON) + .body(Map.of("name", "Nope")) + .when().put("/api/environments/does-not-exist") + .then().statusCode(404); + } + + @Test + void delete_holdingAssets_returns409() + { + this.create(CREATED).then().statusCode(201); + Map properties = AssetControllerTest.properties(); + given().contentType(ContentType.JSON) + .body(AssetControllerTest.createBody("env-controller-asset", CREATED, properties)) + .when().post("/api/assets") + .then().statusCode(201); + + given().when().delete("/api/environments/" + CREATED).then().statusCode(409); + } + @Test void history_returnsCreateEntryForReconciledAsset() { @@ -56,4 +185,13 @@ void history_unknownEnvironment_returns404() .then() .statusCode(404); } + + private io.restassured.response.Response create(String id) + { + Map body = new HashMap<>(); + body.put("id", id); + body.put("name", "Env controller"); + body.put("description", "Described"); + return given().contentType(ContentType.JSON).body(body).when().post("/api/environments"); + } } diff --git a/src/test/java/tech/illuin/wombat/endpoint/WorkerControllerDisabledModuleTest.java b/src/test/java/tech/illuin/wombat/endpoint/WorkerControllerDisabledModuleTest.java index 5d40184..8c87f9d 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/WorkerControllerDisabledModuleTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/WorkerControllerDisabledModuleTest.java @@ -13,7 +13,7 @@ import tech.illuin.wombat.core.asset.profile.Lifetime; import tech.illuin.wombat.core.asset.profile.ServerProvider; import tech.illuin.wombat.core.source.Period; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; import tech.illuin.wombat.engine.module.registry.ModuleMetadata; import tech.illuin.wombat.engine.module.registry.ModuleRegistry; import tech.illuin.wombat.engine.monitor.MonitoredEnvironments; diff --git a/src/test/java/tech/illuin/wombat/endpoint/access/ContextAccessControlTest.java b/src/test/java/tech/illuin/wombat/endpoint/access/ContextAccessControlTest.java new file mode 100644 index 0000000..9889911 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/endpoint/access/ContextAccessControlTest.java @@ -0,0 +1,68 @@ +package tech.illuin.wombat.endpoint.access; + +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.quarkus.test.security.TestSecurity; +import io.restassured.http.ContentType; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; +import tech.illuin.wombat.security.PermissionAugmentor; +import tech.illuin.wombat.ui.AuthenticationEnabledTest; + +import java.util.Map; + +import static io.restassured.RestAssured.given; + +/** + * Users read environments and assets, admins also manage them. + */ +@QuarkusTest +@TestProfile(AuthenticationEnabledTest.AuthenticationEnabledProfile.class) +class ContextAccessControlTest +{ + private static final String CREATED = "access-control-env"; + + @Inject EnvironmentRepository environments; + + @AfterEach + void clean() + { + QuarkusTransaction.requiringNew().run(() -> this.environments.findByIdOptional(CREATED).ifPresent(this.environments::delete)); + } + + @Test + void anonymous_isRejected() + { + given().when().get("/api/environments").then().statusCode(401); + given().when().get("/api/assets").then().statusCode(401); + } + + @Test + @TestSecurity(user = "reader", roles = "wombat-users", augmentors = PermissionAugmentor.class) + void users_read_butDoNotManage() + { + given().when().get("/api/environments/test").then().statusCode(200); + given().when().get("/api/assets/test-llm").then().statusCode(200); + + given().contentType(ContentType.JSON).body(Map.of("id", CREATED, "name", "Nope")).when().post("/api/environments").then().statusCode(403); + given().contentType(ContentType.JSON).body(Map.of("name", "Nope")).when().put("/api/environments/test").then().statusCode(403); + given().when().delete("/api/environments/test").then().statusCode(403); + given().contentType(ContentType.JSON).body(Map.of("id", "nope", "environmentId", "test", "name", "Nope", "type", "x", "properties", Map.of())) + .when().post("/api/assets").then().statusCode(403); + given().contentType(ContentType.JSON).body(Map.of("name", "Nope", "properties", Map.of())).when().put("/api/assets/test-llm").then().statusCode(403); + given().when().delete("/api/assets/test-llm").then().statusCode(403); + } + + @Test + @TestSecurity(user = "boss", roles = "wombat-admins", augmentors = PermissionAugmentor.class) + void admins_manage() + { + given().contentType(ContentType.JSON).body(Map.of("id", CREATED, "name", "Created")).when().post("/api/environments").then().statusCode(201); + given().when().delete("/api/environments/" + CREATED).then().statusCode(204); + // Past the permission check: provisioned assets are read-only. + given().when().delete("/api/assets/test-llm").then().statusCode(409); + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java b/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java index cdcfa4a..7bbf5bd 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java @@ -2,10 +2,19 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import tech.illuin.wombat.engine.context.asset.AssetConflictException; +import tech.illuin.wombat.engine.context.asset.AssetHistoryRecorder; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistory; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.EnvironmentConflictException; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; import tech.illuin.wombat.core.asset.profile.Lifetime; import tech.illuin.wombat.core.source.Period; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; -import tech.illuin.wombat.engine.context.persistence.*; import tech.illuin.wombat.module.kubernetes_api.KubernetesAPIModule; import tech.illuin.wombat.module.kubernetes_api.KubernetesAPIServerProfile; import tech.illuin.wombat.core.asset.profile.ServerProvider; @@ -23,6 +32,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; @@ -88,7 +98,7 @@ void undeletesReturningAsset_withCreateHistory() void softDeletesAssetAbsentFromYaml_withDeleteHistory() { AssetEntity orphan = AssetEntity.from("e1", k8s("gone", Lifetime.ofYears(5))); - when(this.assets.findActive()).thenReturn(List.of(orphan)); + when(this.assets.findVisible()).thenReturn(List.of(orphan)); this.reconcile(desired("e1", "Env 1")); // env kept, but no assets -> "gone" must be removed @@ -108,8 +118,9 @@ void softDeletesUnrecognizedAssetAbsentFromYaml_withDeleteHistory() orphan.name = "Gone Asset"; orphan.type = "tech.illuin.unknown"; orphan.properties = unrecognized; + orphan.provisioned = true; - when(this.assets.findActive()).thenReturn(List.of(orphan)); + when(this.assets.findVisible()).thenReturn(List.of(orphan)); this.reconcile(desired("e1", "Env 1")); @@ -129,6 +140,7 @@ void updatesUnrecognizedAsset_withValidAssetFromYaml() existing.name = "Old Unrecognized"; existing.type = "tech.illuin.unknown"; existing.properties = unrecognized; + existing.provisioned = true; when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(existing)); @@ -140,23 +152,19 @@ void updatesUnrecognizedAsset_withValidAssetFromYaml() } @Test - void reEnablesReturningEnvironmentAndDisablesEnvironmentsAbsentFromYaml() + void restoresReturningEnvironmentAndSoftDeletesEnvironmentsAbsentFromYaml() { - EnvironmentEntity returning = new EnvironmentEntity(); - returning.id = "e1"; - returning.name = "Env 1"; - returning.disabledAt = EnvironmentEntity.now(); + EnvironmentEntity returning = provisioned("e1", "Env 1"); + returning.deletedAt = EnvironmentEntity.now(); when(this.environments.findByIdOptional("e1")).thenReturn(Optional.of(returning)); - EnvironmentEntity orphan = new EnvironmentEntity(); - orphan.id = "old"; - orphan.name = "Old"; - when(this.environments.findActive()).thenReturn(List.of(orphan)); + EnvironmentEntity orphan = provisioned("old", "Old"); + when(this.environments.findVisible()).thenReturn(List.of(orphan)); this.reconcile(desired("e1", "Env 1")); // no assets - assertNull(returning.disabledAt); - assertNotNull(orphan.disabledAt); + assertNull(returning.deletedAt); + assertNotNull(orphan.deletedAt); } /* Ownership: a worker's declaration and the YAML each manage their own assets of a shared environment. */ @@ -175,7 +183,7 @@ void worker_cannotDeclareAnAssetOwnedByTheYaml() AssetEntity local = AssetEntity.from("e1", k8s("a1", Lifetime.ofYears(5))); when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(local)); - assertThrows(EnvironmentConflictException.class, () -> this.reconcileAsWorker("east", desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); + assertThrows(AssetConflictException.class, () -> this.reconcileAsWorker("east", desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); assertNull(local.owner); } @@ -185,7 +193,7 @@ void worker_cannotDeclareAnAssetOwnedByAnotherWorker() AssetEntity other = owned("west", AssetEntity.from("e1", k8s("a1", Lifetime.ofYears(5)))); when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(other)); - assertThrows(EnvironmentConflictException.class, () -> this.reconcileAsWorker("east", desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); + assertThrows(AssetConflictException.class, () -> this.reconcileAsWorker("east", desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); } @Test @@ -207,7 +215,7 @@ void worker_onlyDeletesItsOwnAssets() AssetEntity local = AssetEntity.from("e1", k8s("local", Lifetime.ofYears(5))); AssetEntity mine = owned("east", AssetEntity.from("e1", k8s("mine", Lifetime.ofYears(5)))); AssetEntity theirs = owned("west", AssetEntity.from("e1", k8s("theirs", Lifetime.ofYears(5)))); - when(this.assets.findActive()).thenReturn(List.of(local, mine, theirs)); + when(this.assets.findVisible()).thenReturn(List.of(local, mine, theirs)); this.reconciler().reconcile("east", Map.of()); @@ -220,15 +228,14 @@ void worker_onlyDeletesItsOwnAssets() void yaml_keepsTheAssetsOfWorkers_andTheEnvironmentsHoldingThem() { AssetEntity pushed = owned("east", AssetEntity.from("pushed-env", k8s("pushed", Lifetime.ofYears(5)))); - EnvironmentEntity pushedEnvironment = new EnvironmentEntity(); - pushedEnvironment.id = "pushed-env"; - when(this.assets.findActive()).thenReturn(List.of(pushed)); - when(this.environments.findActive()).thenReturn(List.of(pushedEnvironment)); + EnvironmentEntity pushedEnvironment = provisioned("pushed-env", "pushed-env"); + when(this.assets.findVisible()).thenReturn(List.of(pushed)); + when(this.environments.findVisible()).thenReturn(List.of(pushedEnvironment)); this.reconcile(desired("e1", "Env 1")); assertNull(pushed.deletedAt); - assertNull(pushedEnvironment.disabledAt); + assertNull(pushedEnvironment.deletedAt); } @Test @@ -243,22 +250,112 @@ void yaml_takesOverTheAssetsItDeclares() } @Test - void worker_disablesTheEnvironmentItEmptied_unlessTheYamlDeclaresIt() + void worker_softDeletesTheEnvironmentItEmptied_unlessTheYamlDeclaresIt() { AssetEntity gone = owned("east", AssetEntity.from("pushed-env", k8s("gone", Lifetime.ofYears(5)))); AssetEntity alsoGone = owned("east", AssetEntity.from("e1", k8s("also-gone", Lifetime.ofYears(5)))); - EnvironmentEntity pushedEnvironment = new EnvironmentEntity(); - pushedEnvironment.id = "pushed-env"; - EnvironmentEntity yamlEnvironment = new EnvironmentEntity(); - yamlEnvironment.id = "e1"; - when(this.assets.findActive()).thenReturn(List.of(gone, alsoGone)); - when(this.environments.findActive()).thenReturn(List.of(pushedEnvironment, yamlEnvironment)); - - new EnvironmentReconciler(this.environments, this.assets, this.history, new MonitoredEnvironments(desired("e1", "Env 1"))) + EnvironmentEntity pushedEnvironment = provisioned("pushed-env", "pushed-env"); + EnvironmentEntity yamlEnvironment = provisioned("e1", "e1"); + when(this.assets.findVisible()).thenReturn(List.of(gone, alsoGone)); + when(this.environments.findVisible()).thenReturn(List.of(pushedEnvironment, yamlEnvironment)); + + new EnvironmentReconciler(this.environments, this.assets, new AssetHistoryRecorder(this.history), new MonitoredEnvironments(desired("e1", "Env 1"))) .reconcile("east", Map.of()); - assertNotNull(pushedEnvironment.disabledAt); - assertNull(yamlEnvironment.disabledAt); + assertNotNull(pushedEnvironment.deletedAt); + assertNull(yamlEnvironment.deletedAt); + } + + /* Environments and assets created through the API: never touched by a declaration, which must not clash with them. */ + + @Test + void yaml_failsOnAnEnvironmentCreatedThroughTheApi() + { + when(this.environments.findByIdOptional("e1")).thenReturn(Optional.of(created("e1"))); + + assertThrows(EnvironmentConflictException.class, () -> this.reconcile(desired("e1", "Env 1"))); + } + + @Test + void worker_failsOnAnEnvironmentCreatedThroughTheApi() + { + when(this.environments.findByIdOptional("e1")).thenReturn(Optional.of(created("e1"))); + + assertThrows(EnvironmentConflictException.class, () -> this.reconciler().reconcile("east", desired("e1", "Env 1"))); + } + + @Test + void yaml_failsOnAnAssetCreatedThroughTheApi() + { + AssetEntity user = created(AssetEntity.from("e1", k8s("a1", Lifetime.ofYears(5)))); + when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(user)); + + assertThrows(AssetConflictException.class, () -> this.reconcile(desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); + verify(this.history, never()).persist(any(AssetConfigHistory.class)); + } + + @Test + void worker_failsOnAnAssetCreatedThroughTheApi() + { + AssetEntity user = created(AssetEntity.from("e1", k8s("a1", Lifetime.ofYears(5)))); + when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(user)); + + assertThrows(AssetConflictException.class, () -> this.reconciler().reconcile("east", desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5))))); + } + + @Test + void takesOverSoftDeletedRowsCreatedThroughTheApi() + { + EnvironmentEntity environment = created("e1"); + environment.deletedAt = EnvironmentEntity.now(); + AssetEntity asset = created(AssetEntity.from("e1", k8s("a1", Lifetime.ofYears(5)))); + asset.deletedAt = EnvironmentEntity.now(); + when(this.environments.findByIdOptional("e1")).thenReturn(Optional.of(environment)); + when(this.assets.findByIdOptional("a1")).thenReturn(Optional.of(asset)); + + this.reconcile(desired("e1", "Env 1", k8s("a1", Lifetime.ofYears(5)))); + + assertNull(environment.deletedAt); + assertTrue(environment.provisioned); + assertNull(asset.deletedAt); + assertTrue(asset.provisioned); + } + + @Test + void yaml_keepsTheAssetsCreatedThroughTheApi() + { + // Same owner as the YAML (null): only the provisioned flag tells them apart. + AssetEntity user = created(AssetEntity.from("e1", k8s("user", Lifetime.ofYears(5)))); + when(this.assets.findVisible()).thenReturn(List.of(user)); + + this.reconcile(desired("e1", "Env 1")); + + assertNull(user.deletedAt); + verify(this.history, never()).persist(any(AssetConfigHistory.class)); + } + + @Test + void yaml_keepsTheEnvironmentsCreatedThroughTheApi() + { + EnvironmentEntity user = created("user-env"); + when(this.environments.findVisible()).thenReturn(List.of(user)); + + this.reconcile(desired("e1", "Env 1")); + + assertNull(user.deletedAt); + } + + @Test + void yaml_keepsAnUndeclaredEnvironmentHoldingAssetsCreatedThroughTheApi() + { + EnvironmentEntity old = provisioned("old", "Old"); + AssetEntity user = created(AssetEntity.from("old", k8s("user", Lifetime.ofYears(5)))); + when(this.environments.findVisible()).thenReturn(List.of(old)); + when(this.assets.findVisible()).thenReturn(List.of(user)); + + this.reconcile(desired("e1", "Env 1")); + + assertNull(old.deletedAt); } private AssetEntity reconcileAsWorker(String worker, Map desired) @@ -272,7 +369,30 @@ private AssetEntity reconcileAsWorker(String worker, Map de /* A reconciler whose YAML declares nothing, so only the worker's declaration is at play. */ private EnvironmentReconciler reconciler() { - return new EnvironmentReconciler(this.environments, this.assets, this.history, new MonitoredEnvironments(Map.of())); + return new EnvironmentReconciler(this.environments, this.assets, new AssetHistoryRecorder(this.history), new MonitoredEnvironments(Map.of())); + } + + private static EnvironmentEntity provisioned(String id, String name) + { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = id; + entity.name = name; + entity.provisioned = true; + return entity; + } + + private static EnvironmentEntity created(String id) + { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = id; + entity.name = id; + return entity; + } + + private static AssetEntity created(AssetEntity entity) + { + entity.provisioned = false; + return entity; } private static AssetEntity owned(String owner, AssetEntity entity) @@ -283,7 +403,7 @@ private static AssetEntity owned(String owner, AssetEntity entity) private void reconcile(Map desired) { - new EnvironmentReconciler(this.environments, this.assets, this.history, new MonitoredEnvironments(desired)) + new EnvironmentReconciler(this.environments, this.assets, new AssetHistoryRecorder(this.history), new MonitoredEnvironments(desired)) .onStart(null); } diff --git a/src/test/java/tech/illuin/wombat/engine/context/RepositoryContextProviderTest.java b/src/test/java/tech/illuin/wombat/engine/context/RepositoryContextProviderTest.java index 11faff9..d94886c 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/RepositoryContextProviderTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/RepositoryContextProviderTest.java @@ -1,12 +1,12 @@ package tech.illuin.wombat.engine.context; import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; import tech.illuin.wombat.module.llm_static.LLMStaticModule; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; -import tech.illuin.wombat.engine.context.persistence.AssetRepository; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; import tech.illuin.wombat.core.asset.AssetIdentity; import tech.illuin.wombat.core.asset.Environment; import tech.illuin.wombat.core.asset.profile.LLMProvider; diff --git a/src/test/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorderTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorderTest.java new file mode 100644 index 0000000..34f7683 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetHistoryRecorderTest.java @@ -0,0 +1,46 @@ +package tech.illuin.wombat.engine.context.asset; + +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import tech.illuin.wombat.core.asset.AssetIdentity; +import tech.illuin.wombat.core.asset.profile.LLMProvider; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistory; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.module.llm_static.LLMStaticAsset; +import tech.illuin.wombat.module.llm_static.LLMStaticModule; +import tech.illuin.wombat.module.llm_static.LLMStaticProfile; +import tech.illuin.wombat.module.llm_static.scenario.ConstantScenario; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static tech.illuin.wombat.core.activity.commons.Country.FRANCE; + +class AssetHistoryRecorderTest +{ + @Test + void persistsASnapshotOfTheAsset() + { + AssetConfigHistoryRepository repository = mock(AssetConfigHistoryRepository.class); + AssetEntity entity = AssetEntity.from("e1", new LLMStaticAsset( + AssetIdentity.of("a1", "e1", "A1", LLMStaticModule.TYPE), + new LLMStaticProfile(LLMProvider.mistralai, "m", FRANCE, List.of(new ConstantScenario(500, 1000))) + )); + + new AssetHistoryRecorder(repository).record(AssetConfigAction.UPDATE, entity); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AssetConfigHistory.class); + verify(repository).persist(captor.capture()); + AssetConfigHistory history = captor.getValue(); + assertEquals(AssetConfigAction.UPDATE, history.action); + assertEquals("a1", history.assetId); + assertEquals("e1", history.environmentId); + assertTrue(history.snapshot.contains("\"id\":\"a1\"")); + assertTrue(history.snapshot.contains("\"type\":\"" + LLMStaticModule.TYPE.name() + "\"")); + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/asset/AssetServiceTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetServiceTest.java new file mode 100644 index 0000000..244b3bc --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetServiceTest.java @@ -0,0 +1,217 @@ +package tech.illuin.wombat.engine.context.asset; + +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistoryRepository; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.EnvironmentConflictException; +import tech.illuin.wombat.engine.context.environment.EnvironmentService; +import tech.illuin.wombat.engine.context.environment.UnknownEnvironmentException; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; +import tech.illuin.wombat.module.llm_static.LLMStaticAsset; +import tech.illuin.wombat.module.llm_static.LLMStaticModule; + +import java.util.List; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Against the real mapper, validator and database, since an asset is read from its JSON properties. + * The test profile provisions the environment {@code test}, holding the asset {@code test-llm}. + */ +@QuarkusTest +class AssetServiceTest +{ + private static final String ENVIRONMENT = "asset-service-env"; + private static final String TYPE = LLMStaticModule.TYPE.name(); + + @Inject AssetService service; + @Inject EnvironmentService environments; + @Inject AssetRepository assetRepository; + @Inject EnvironmentRepository environmentRepository; + @Inject AssetConfigHistoryRepository historyRepository; + @Inject JsonMapper mapper; + + @BeforeEach + void setUp() + { + this.clean(); + this.environments.create(ENVIRONMENT, "Asset service", null, false); + } + + @AfterEach + void clean() + { + QuarkusTransaction.requiringNew().run(() -> { + for (String id : List.of("user-llm", "other-llm")) + { + this.assetRepository.findByIdOptional(id).ifPresent(this.assetRepository::delete); + this.historyRepository.findByAsset(id).forEach(this.historyRepository::delete); + } + this.environmentRepository.findByIdOptional(ENVIRONMENT).ifPresent(this.environmentRepository::delete); + }); + } + + @Test + void create_readsTheAssetFromItsProperties_andHistorizesIt() + { + AssetEntity created = this.create("user-llm", ENVIRONMENT); + + AssetEntity found = QuarkusTransaction.requiringNew().call(() -> this.assetRepository.findById("user-llm")); + assertFalse(found.provisioned); + assertNull(found.owner); + assertEquals("User LLM", found.name); + assertEquals("Described", found.description); + assertEquals(TYPE, found.type); + LLMStaticAsset asset = assertInstanceOf(LLMStaticAsset.class, found.properties); + assertEquals("user-llm", asset.identity().id()); + assertEquals(ENVIRONMENT, asset.identity().environmentId()); + assertEquals(created.uuid, found.uuid); + assertEquals(List.of(AssetConfigAction.CREATE), this.actions("user-llm")); + } + + @Test + void create_canTargetAProvisionedEnvironment() + { + assertEquals("test", this.create("user-llm", "test").environmentId); + } + + @Test + void create_failsOnAnUnknownEnvironment() + { + assertThrows(UnknownEnvironmentException.class, () -> this.create("user-llm", "nowhere")); + } + + @Test + void create_failsOnAnExistingAsset_provisionedOrNot() + { + this.create("user-llm", ENVIRONMENT); + + assertThrows(AssetConflictException.class, () -> this.create("user-llm", ENVIRONMENT)); + assertThrows(AssetConflictException.class, () -> this.create("test-llm", ENVIRONMENT)); + } + + @Test + void create_failsOnAnUnknownType() + { + ObjectNode properties = this.properties(); + + assertThrows(InvalidAssetException.class, () -> this.service.create("user-llm", ENVIRONMENT, "User LLM", "tech.illuin.unknown", null, false, properties)); + } + + @Test + void create_failsOnInvalidProperties() + { + ObjectNode properties = this.mapper.createObjectNode(); + properties.putObject("profile").put("models", "not-a-list"); + + assertThrows(InvalidAssetException.class, () -> this.service.create("user-llm", ENVIRONMENT, "User LLM", TYPE, null, false, properties)); + } + + @Test + void create_takesOverASoftDeletedAsset() + { + String uuid = this.create("user-llm", ENVIRONMENT).uuid; + this.service.delete("user-llm"); + + AssetEntity created = this.create("user-llm", ENVIRONMENT); + + assertEquals(uuid, created.uuid); + assertNull(created.deletedAt); + assertEquals(List.of(AssetConfigAction.CREATE, AssetConfigAction.DELETE, AssetConfigAction.CREATE), this.actions("user-llm")); + } + + @Test + void update_replacesTheEditableFields_keepingTheIdentity() + { + this.create("user-llm", ENVIRONMENT); + + this.service.update("user-llm", "Renamed", null, true, this.properties()); + + AssetEntity found = QuarkusTransaction.requiringNew().call(() -> this.assetRepository.findById("user-llm")); + assertEquals("Renamed", found.name); + assertEquals("Renamed", found.properties.identity().name()); + assertEquals(ENVIRONMENT, found.environmentId); + assertNull(found.description); + assertNotNull(found.disabledAt); + assertEquals(List.of(AssetConfigAction.CREATE, AssetConfigAction.UPDATE), this.actions("user-llm")); + } + + @Test + void update_onlyHistorizesChangedProperties() + { + this.create("user-llm", ENVIRONMENT); + + this.service.update("user-llm", "User LLM", "Other", true, this.properties()); + + assertEquals(List.of(AssetConfigAction.CREATE), this.actions("user-llm")); + } + + @Test + void updateAndDelete_failOnAProvisionedAsset() + { + assertThrows(AssetConflictException.class, () -> this.service.update("test-llm", "Test LLM", null, false, this.properties())); + assertThrows(AssetConflictException.class, () -> this.service.delete("test-llm")); + } + + @Test + void delete_hidesTheAsset_andUnblocksItsEnvironment() + { + this.create("user-llm", ENVIRONMENT); + assertThrows(EnvironmentConflictException.class, () -> this.environments.delete(ENVIRONMENT)); + + this.service.delete("user-llm"); + + assertThrows(UnknownAssetException.class, () -> this.service.get("user-llm")); + assertTrue(this.service.list(Optional.of(ENVIRONMENT)).isEmpty()); + this.environments.delete(ENVIRONMENT); + assertThrows(UnknownEnvironmentException.class, () -> this.environments.get(ENVIRONMENT)); + } + + @Test + void list_filtersByEnvironment() + { + this.create("user-llm", ENVIRONMENT); + this.create("other-llm", "test"); + + assertEquals(List.of("user-llm"), this.service.list(Optional.of(ENVIRONMENT)).stream().map(a -> a.id).toList()); + assertTrue(this.service.list(Optional.empty()).stream().map(a -> a.id).toList().containsAll(List.of("user-llm", "other-llm", "test-llm"))); + assertThrows(UnknownEnvironmentException.class, () -> this.service.list(Optional.of("nowhere"))); + } + + private AssetEntity create(String id, String environmentId) + { + return this.service.create(id, environmentId, "User LLM", TYPE, "Described", false, this.properties()); + } + + /** The type-specific properties of the provisioned llm-static asset, as an API caller would send them. */ + private ObjectNode properties() + { + AssetEntity provisioned = QuarkusTransaction.requiringNew().call(() -> this.assetRepository.findById("test-llm")); + ObjectNode node = this.mapper.valueToTree(provisioned.properties); + node.remove(List.of("id", "environment-id", "environmentId", "name", "type")); + return node; + } + + private List actions(String id) + { + return QuarkusTransaction.requiringNew().call(() -> this.historyRepository.findByAsset(id)).stream() + .map(history -> history.action) + .toList(); + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/asset/AssetValidatorTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetValidatorTest.java new file mode 100644 index 0000000..aa96dc2 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/AssetValidatorTest.java @@ -0,0 +1,64 @@ +package tech.illuin.wombat.engine.context.asset; + +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.core.asset.AssetIdentity; +import tech.illuin.wombat.core.asset.profile.LLMProvider; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.module.registry.InMemoryModuleRegistry; +import tech.illuin.wombat.engine.module.registry.ModuleRegistries; +import tech.illuin.wombat.module.kubernetes_api.KubernetesAPIModule; +import tech.illuin.wombat.module.llm_static.LLMStaticAsset; +import tech.illuin.wombat.module.llm_static.LLMStaticModule; +import tech.illuin.wombat.module.llm_static.LLMStaticProfile; +import tech.illuin.wombat.module.llm_static.scenario.ConstantScenario; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static tech.illuin.wombat.core.activity.commons.Country.FRANCE; + +class AssetValidatorTest +{ + private static final LLMStaticAsset ASSET = new LLMStaticAsset( + AssetIdentity.of("a1", "e1", "A1", LLMStaticModule.TYPE), + new LLMStaticProfile(LLMProvider.mistralai, "m", FRANCE, List.of(new ConstantScenario(500, 1000))) + ); + + @Test + void acceptsAnAssetWithAnEnabledModule() + { + AssetValidator validator = new AssetValidator(ModuleRegistries.enabled(List.of(new LLMStaticModule()))); + + assertDoesNotThrow(() -> validator.validate(ASSET)); + } + + @Test + void acceptsAnAssetWithADisabledModule() + { + InMemoryModuleRegistry registry = new InMemoryModuleRegistry(); + registry.registerModule(new LLMStaticModule(), false); + + assertDoesNotThrow(() -> new AssetValidator(registry).validate(ASSET)); + } + + @Test + void rejectsAnAssetWithoutModule() + { + AssetValidator validator = new AssetValidator(ModuleRegistries.enabled(List.of(new KubernetesAPIModule()))); + + InvalidAssetException e = assertThrows(InvalidAssetException.class, () -> validator.validate(ASSET)); + assertTrue(e.getMessage().contains("No module")); + } + + @Test + void rejectsAnUnrecognizedAsset() + { + AssetValidator validator = new AssetValidator(ModuleRegistries.enabled(List.of(new LLMStaticModule()))); + UnrecognizedAsset unrecognized = new UnrecognizedAsset(AssetIdentity.of("u", "e1", "U", "tech.illuin.unknown"), "{}"); + + InvalidAssetException e = assertThrows(InvalidAssetException.class, () -> validator.validate(unrecognized)); + assertTrue(e.getMessage().contains("Unknown asset type")); + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfoTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfoTest.java similarity index 83% rename from src/test/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfoTest.java rename to src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfoTest.java index 7dd3058..c5ba898 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/model/AssetHistoryInfoTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetHistoryInfoTest.java @@ -1,9 +1,8 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import org.junit.jupiter.api.Test; -import tech.illuin.wombat.engine.context.model.AssetHistoryInfo; -import tech.illuin.wombat.engine.context.persistence.AssetConfigAction; -import tech.illuin.wombat.engine.context.persistence.AssetConfigHistory; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigAction; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConfigHistory; import java.time.Instant; diff --git a/src/test/java/tech/illuin/wombat/engine/context/model/AssetInfoTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetInfoTest.java similarity index 98% rename from src/test/java/tech/illuin/wombat/engine/context/model/AssetInfoTest.java rename to src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetInfoTest.java index 8703785..24620eb 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/model/AssetInfoTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/model/AssetInfoTest.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.model; +package tech.illuin.wombat.engine.context.asset.model; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonUnwrapped; @@ -9,10 +9,10 @@ import com.fasterxml.jackson.databind.jsontype.NamedType; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; import tech.illuin.wombat.module.llm_prometheus.LLMPrometheusModule; import tech.illuin.wombat.core.asset.profile.Lifetime; import tech.illuin.wombat.core.source.Period; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; import tech.illuin.wombat.core.asset.type.ActivityRegime; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.AssetIdentity; diff --git a/src/test/java/tech/illuin/wombat/engine/context/persistence/AssetConverterTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverterTest.java similarity index 97% rename from src/test/java/tech/illuin/wombat/engine/context/persistence/AssetConverterTest.java rename to src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverterTest.java index 02f707f..b71af4c 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/persistence/AssetConverterTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetConverterTest.java @@ -1,9 +1,9 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; import tech.illuin.wombat.core.asset.profile.Lifetime; import tech.illuin.wombat.core.source.Period; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; import tech.illuin.wombat.core.asset.type.ActivityRegime; import tech.illuin.wombat.core.asset.Asset; import tech.illuin.wombat.core.asset.AssetIdentity; diff --git a/src/test/java/tech/illuin/wombat/engine/context/persistence/AssetEntityTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntityTest.java similarity index 98% rename from src/test/java/tech/illuin/wombat/engine/context/persistence/AssetEntityTest.java rename to src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntityTest.java index fc349c7..4501ff1 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/persistence/AssetEntityTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetEntityTest.java @@ -1,4 +1,4 @@ -package tech.illuin.wombat.engine.context.persistence; +package tech.illuin.wombat.engine.context.asset.persistence; import org.junit.jupiter.api.Test; import tech.illuin.wombat.core.asset.AssetIdentity; diff --git a/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepositoryTest.java b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepositoryTest.java new file mode 100644 index 0000000..f3166f3 --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/asset/persistence/AssetRepositoryTest.java @@ -0,0 +1,110 @@ +package tech.illuin.wombat.engine.context.asset.persistence; + +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; +import tech.illuin.wombat.core.asset.AssetIdentity; +import tech.illuin.wombat.module.llm_static.LLMStaticAsset; +import tech.illuin.wombat.module.llm_static.LLMStaticModule; +import tech.illuin.wombat.module.llm_static.LLMStaticProfile; +import tech.illuin.wombat.module.llm_static.scenario.ConstantScenario; +import tech.illuin.wombat.core.asset.profile.LLMProvider; + +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static tech.illuin.wombat.core.activity.commons.Country.FRANCE; + +@QuarkusTest +class AssetRepositoryTest +{ + private static final String ENVIRONMENT = "asset-repo-env"; + private static final List ASSETS = List.of("asset-active", "asset-disabled", "asset-deleted"); + + @Inject AssetRepository repository; + @Inject EnvironmentRepository environments; + + @BeforeEach + void setUp() + { + this.clean(); + QuarkusTransaction.requiringNew().run(() -> { + EnvironmentEntity environment = new EnvironmentEntity(); + environment.id = ENVIRONMENT; + environment.name = ENVIRONMENT; + this.environments.persist(environment); + + AssetEntity active = asset("asset-active", null, null); + active.description = "Described"; + this.repository.persist(active); + this.repository.persist(asset("asset-disabled", Instant.now(), null)); + this.repository.persist(asset("asset-deleted", null, Instant.now())); + }); + } + + @AfterEach + void clean() + { + QuarkusTransaction.requiringNew().run(() -> { + for (String id : ASSETS) + this.repository.findByIdOptional(id).ifPresent(this.repository::delete); + this.environments.findByIdOptional(ENVIRONMENT).ifPresent(this.environments::delete); + }); + } + + @Test + void newColumnsRoundTrip() + { + AssetEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("asset-active")); + + assertEquals("Described", found.description); + assertTrue(found.provisioned); + assertNull(found.disabledAt); + assertNull(found.deletedAt); + } + + @Test + void byEnvironment_processingSkipsDisabled_apiKeepsThem() + { + List active = QuarkusTransaction.requiringNew().call(() -> this.repository.findByEnvironment(ENVIRONMENT)).stream().map(a -> a.id).toList(); + List visible = QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleByEnvironment(ENVIRONMENT)).stream().map(a -> a.id).toList(); + + assertEquals(List.of("asset-active"), active); + assertEquals(List.of("asset-active", "asset-disabled"), visible.stream().sorted().toList()); + assertEquals(2L, QuarkusTransaction.requiringNew().call(() -> this.repository.countVisibleByEnvironment(ENVIRONMENT))); + } + + @Test + void visibleLookupsIgnoreDeleted() + { + AssetEntity deleted = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("asset-deleted")); + AssetEntity disabled = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("asset-disabled")); + List visible = QuarkusTransaction.requiringNew().call(() -> this.repository.findVisible()).stream().map(a -> a.id).toList(); + + assertTrue(visible.containsAll(List.of("asset-active", "asset-disabled"))); + assertFalse(visible.contains("asset-deleted")); + assertTrue(QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleById("asset-deleted")).isEmpty()); + assertTrue(QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleByUuid(deleted.uuid)).isEmpty()); + assertEquals("asset-disabled", QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleByUuid(disabled.uuid).orElseThrow()).id); + } + + private static AssetEntity asset(String id, Instant disabledAt, Instant deletedAt) + { + AssetEntity entity = AssetEntity.from(ENVIRONMENT, new LLMStaticAsset( + AssetIdentity.of(id, ENVIRONMENT, id, LLMStaticModule.TYPE), + new LLMStaticProfile(LLMProvider.mistralai, "m", FRANCE, List.of(new ConstantScenario(500, 1000))) + )); + entity.disabledAt = disabledAt; + entity.deletedAt = deletedAt; + return entity; + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/environment/EnvironmentServiceTest.java b/src/test/java/tech/illuin/wombat/engine/context/environment/EnvironmentServiceTest.java new file mode 100644 index 0000000..a050b0f --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/environment/EnvironmentServiceTest.java @@ -0,0 +1,142 @@ +package tech.illuin.wombat.engine.context.environment; + +import org.junit.jupiter.api.Test; +import tech.illuin.wombat.engine.context.asset.persistence.AssetRepository; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentEntity; +import tech.illuin.wombat.engine.context.environment.persistence.EnvironmentRepository; + +import java.time.Instant; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class EnvironmentServiceTest +{ + private final EnvironmentRepository environments = mock(EnvironmentRepository.class); + private final AssetRepository assets = mock(AssetRepository.class); + private final EnvironmentService service = new EnvironmentService(this.environments, this.assets); + + @Test + void create_persistsANewEnvironmentCreatedThroughTheApi() + { + EnvironmentEntity created = this.service.create("prod", "Production", "Main", true); + + verify(this.environments).persist(created); + assertEquals("prod", created.id); + assertEquals("Production", created.name); + assertEquals("Main", created.description); + assertFalse(created.provisioned); + assertNotNull(created.disabledAt); + } + + @Test + void create_failsOnAnExistingEnvironment_provisionedOrNot() + { + when(this.environments.findByIdOptional("prod")).thenReturn(Optional.of(environment("prod", false))); + when(this.environments.findByIdOptional("test")).thenReturn(Optional.of(environment("test", true))); + + assertThrows(EnvironmentConflictException.class, () -> this.service.create("prod", "Production", null, false)); + assertThrows(EnvironmentConflictException.class, () -> this.service.create("test", "Test", null, false)); + } + + @Test + void create_takesOverASoftDeletedEnvironment() + { + EnvironmentEntity deleted = environment("prod", true); + deleted.uuid = "kept"; + deleted.deletedAt = Instant.now(); + when(this.environments.findByIdOptional("prod")).thenReturn(Optional.of(deleted)); + + EnvironmentEntity created = this.service.create("prod", "Production", null, false); + + assertSame(deleted, created); + assertEquals("kept", created.uuid); + assertNull(created.deletedAt); + assertFalse(created.provisioned); + verify(this.environments, never()).persist(created); + } + + @Test + void get_ignoresUnknownAndSoftDeletedEnvironments() + { + assertThrows(UnknownEnvironmentException.class, () -> this.service.get("prod")); + assertThrows(UnknownEnvironmentException.class, () -> this.service.getByUuid("uuid")); + } + + @Test + void update_replacesTheEditableFields() + { + EnvironmentEntity entity = environment("prod", false); + when(this.environments.findVisibleById("prod")).thenReturn(Optional.of(entity)); + + this.service.update("prod", "Renamed", "Described", true); + + assertEquals("Renamed", entity.name); + assertEquals("Described", entity.description); + assertNotNull(entity.disabledAt); + } + + @Test + void update_keepsWhenItWasDisabled_andReenables() + { + Instant disabledAt = Instant.parse("2026-01-01T00:00:00Z"); + EnvironmentEntity entity = environment("prod", false); + entity.disabledAt = disabledAt; + when(this.environments.findVisibleById("prod")).thenReturn(Optional.of(entity)); + + this.service.update("prod", "Production", null, true); + assertEquals(disabledAt, entity.disabledAt); + + this.service.update("prod", "Production", null, false); + assertNull(entity.disabledAt); + } + + @Test + void updateAndDelete_failOnAProvisionedEnvironment() + { + when(this.environments.findVisibleById("test")).thenReturn(Optional.of(environment("test", true))); + + assertThrows(EnvironmentConflictException.class, () -> this.service.update("test", "Test", null, false)); + assertThrows(EnvironmentConflictException.class, () -> this.service.delete("test")); + } + + @Test + void delete_softDeletesAnEmptyEnvironment() + { + EnvironmentEntity entity = environment("prod", false); + when(this.environments.findVisibleById("prod")).thenReturn(Optional.of(entity)); + + this.service.delete("prod"); + + assertNotNull(entity.deletedAt); + } + + @Test + void delete_failsOnAnEnvironmentHoldingAssets() + { + EnvironmentEntity entity = environment("prod", false); + when(this.environments.findVisibleById("prod")).thenReturn(Optional.of(entity)); + when(this.assets.countVisibleByEnvironment("prod")).thenReturn(1L); + + assertThrows(EnvironmentConflictException.class, () -> this.service.delete("prod")); + assertNull(entity.deletedAt); + } + + private static EnvironmentEntity environment(String id, boolean provisioned) + { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = id; + entity.name = id; + entity.provisioned = provisioned; + return entity; + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepositoryTest.java b/src/test/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepositoryTest.java new file mode 100644 index 0000000..500a9bc --- /dev/null +++ b/src/test/java/tech/illuin/wombat/engine/context/environment/persistence/EnvironmentRepositoryTest.java @@ -0,0 +1,131 @@ +package tech.illuin.wombat.engine.context.environment.persistence; + +import io.quarkus.narayana.jta.QuarkusTransaction; +import io.quarkus.test.junit.QuarkusTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@QuarkusTest +class EnvironmentRepositoryTest +{ + + @Inject + EnvironmentRepository repository; + + @BeforeEach + @AfterEach + void clean() + { + QuarkusTransaction.requiringNew().run(() -> { + for (EnvironmentEntity e : this.repository.listAll()) + if (List.of("env-prod", "env-staging", "env-active", "env-disabled", "env-deleted").contains(e.id)) + this.repository.delete(e); + }); + } + + @Test + void persistSetsTimestampsAndRoundTrips() + { + QuarkusTransaction.requiringNew().run(() -> { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = "env-prod"; + entity.name = "Production"; + this.repository.persist(entity); + }); + + EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-prod").orElse(null)); + assertNotNull(found); + assertNotNull(found.uuid); + assertEquals("Production", found.name); + assertNotNull(found.createdAt); + assertEquals(found.createdAt, found.updatedAt); + assertNull(found.disabledAt); + assertNull(found.deletedAt); + assertNull(found.description); + assertFalse(found.provisioned); + } + + @Test + void updateBumpsUpdatedAtAndDisableIsRecorded() + { + QuarkusTransaction.requiringNew().run(() -> { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = "env-staging"; + entity.name = "Staging"; + this.repository.persist(entity); + }); + + Instant createdAt = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-staging").orElse(null)).createdAt; + + QuarkusTransaction.requiringNew().run(() -> { + EnvironmentEntity entity = this.repository.findByIdOptional("env-staging").orElse(null); + entity.disabledAt = Instant.now(); + }); + + EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-staging").orElse(null)); + assertEquals(createdAt, found.createdAt); + assertNotNull(found.disabledAt); + assertFalse(found.updatedAt.isBefore(found.createdAt)); + } + + @Test + void visibleExcludesDeleted_activeAlsoExcludesDisabled() + { + QuarkusTransaction.requiringNew().run(() -> { + this.repository.persist(environment("env-active", null, null)); + this.repository.persist(environment("env-disabled", Instant.now(), null)); + this.repository.persist(environment("env-deleted", null, Instant.now())); + }); + + List visible = QuarkusTransaction.requiringNew().call(() -> this.repository.findVisible()).stream().map(e -> e.id).toList(); + List active = QuarkusTransaction.requiringNew().call(() -> this.repository.findActive()).stream().map(e -> e.id).toList(); + + assertTrue(visible.containsAll(List.of("env-active", "env-disabled"))); + assertFalse(visible.contains("env-deleted")); + assertTrue(active.contains("env-active")); + assertFalse(active.contains("env-disabled")); + assertFalse(active.contains("env-deleted")); + } + + @Test + void findVisibleByIdAndUuidIgnoreDeleted() + { + QuarkusTransaction.requiringNew().run(() -> { + EnvironmentEntity active = environment("env-active", null, null); + active.description = "Described"; + active.provisioned = true; + this.repository.persist(active); + this.repository.persist(environment("env-deleted", null, Instant.now())); + }); + + EnvironmentEntity active = QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleById("env-active").orElseThrow()); + EnvironmentEntity deleted = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("env-deleted")); + + assertEquals("Described", active.description); + assertTrue(active.provisioned); + assertEquals("env-active", QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleByUuid(active.uuid).orElseThrow()).id); + assertTrue(QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleById("env-deleted")).isEmpty()); + assertTrue(QuarkusTransaction.requiringNew().call(() -> this.repository.findVisibleByUuid(deleted.uuid)).isEmpty()); + } + + private static EnvironmentEntity environment(String id, Instant disabledAt, Instant deletedAt) + { + EnvironmentEntity entity = new EnvironmentEntity(); + entity.id = id; + entity.name = id; + entity.disabledAt = disabledAt; + entity.deletedAt = deletedAt; + return entity; + } +} diff --git a/src/test/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepositoryTest.java b/src/test/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepositoryTest.java deleted file mode 100644 index 04fe9db..0000000 --- a/src/test/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepositoryTest.java +++ /dev/null @@ -1,79 +0,0 @@ -package tech.illuin.wombat.engine.context.persistence; - -import io.quarkus.narayana.jta.QuarkusTransaction; -import io.quarkus.test.junit.QuarkusTest; -import jakarta.inject.Inject; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import tech.illuin.wombat.engine.context.persistence.EnvironmentEntity; -import tech.illuin.wombat.engine.context.persistence.EnvironmentRepository; - -import java.time.Instant; -import java.util.List; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; - -@QuarkusTest -class EnvironmentRepositoryTest -{ - - @Inject - EnvironmentRepository repository; - - @BeforeEach - @AfterEach - void clean() - { - QuarkusTransaction.requiringNew().run(() -> { - for (EnvironmentEntity e : this.repository.listAll()) - if (List.of("env-prod", "env-staging").contains(e.id)) - this.repository.delete(e); - }); - } - - @Test - void persistSetsTimestampsAndRoundTrips() - { - QuarkusTransaction.requiringNew().run(() -> { - EnvironmentEntity entity = new EnvironmentEntity(); - entity.id = "env-prod"; - entity.name = "Production"; - this.repository.persist(entity); - }); - - EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-prod").orElse(null)); - assertNotNull(found); - assertNotNull(found.uuid); - assertEquals("Production", found.name); - assertNotNull(found.createdAt); - assertEquals(found.createdAt, found.updatedAt); - assertNull(found.disabledAt); - } - - @Test - void updateBumpsUpdatedAtAndDisableIsRecorded() - { - QuarkusTransaction.requiringNew().run(() -> { - EnvironmentEntity entity = new EnvironmentEntity(); - entity.id = "env-staging"; - entity.name = "Staging"; - this.repository.persist(entity); - }); - - Instant createdAt = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-staging").orElse(null)).createdAt; - - QuarkusTransaction.requiringNew().run(() -> { - EnvironmentEntity entity = this.repository.findByIdOptional("env-staging").orElse(null); - entity.disabledAt = Instant.now(); - }); - - EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-staging").orElse(null)); - assertEquals(createdAt, found.createdAt); - assertNotNull(found.disabledAt); - assertFalse(found.updatedAt.isBefore(found.createdAt)); - } -} diff --git a/src/test/java/tech/illuin/wombat/engine/module/extension/DynamicModuleIntegrationTest.java b/src/test/java/tech/illuin/wombat/engine/module/extension/DynamicModuleIntegrationTest.java index 01fe16c..a503bd5 100644 --- a/src/test/java/tech/illuin/wombat/engine/module/extension/DynamicModuleIntegrationTest.java +++ b/src/test/java/tech/illuin/wombat/engine/module/extension/DynamicModuleIntegrationTest.java @@ -5,10 +5,10 @@ import com.fasterxml.jackson.dataformat.yaml.YAMLMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import tech.illuin.wombat.engine.context.asset.model.UnrecognizedAsset; +import tech.illuin.wombat.engine.context.asset.persistence.AssetConverter; +import tech.illuin.wombat.engine.context.asset.persistence.AssetEntity; import tech.illuin.wombat.core.source.Period; -import tech.illuin.wombat.engine.context.model.UnrecognizedAsset; -import tech.illuin.wombat.engine.context.persistence.AssetConverter; -import tech.illuin.wombat.engine.context.persistence.AssetEntity; import tech.illuin.wombat.core.WombatCore; import tech.illuin.wombat.core.asset.type.ActivityRegime; import tech.illuin.wombat.core.asset.Asset; diff --git a/src/test/java/tech/illuin/wombat/security/RoleTest.java b/src/test/java/tech/illuin/wombat/security/RoleTest.java index db3dfc4..baa6a90 100644 --- a/src/test/java/tech/illuin/wombat/security/RoleTest.java +++ b/src/test/java/tech/illuin/wombat/security/RoleTest.java @@ -29,7 +29,7 @@ void users_readTheReportAndManageTheirOwnKeys() EnumSet.of( Permission.UI_DASHBOARD_READ, Permission.UI_APIKEYS_MANAGE, Permission.API_APIKEY_MANAGE, Permission.API_IMPACT_READ, Permission.API_SIMULATION_READ, Permission.API_ENVIRONMENT_READ, - Permission.API_MODULE_READ + Permission.API_ASSET_READ, Permission.API_MODULE_READ ), Role.USER.permissions() ); diff --git a/src/test/java/tech/illuin/wombat/ui/AuthenticationEnabledTest.java b/src/test/java/tech/illuin/wombat/ui/AuthenticationEnabledTest.java index 0156de7..02bf3ef 100644 --- a/src/test/java/tech/illuin/wombat/ui/AuthenticationEnabledTest.java +++ b/src/test/java/tech/illuin/wombat/ui/AuthenticationEnabledTest.java @@ -148,7 +148,7 @@ void admin_managesApiKeys() .when().get("/api/keys/settings") .then() .statusCode(200) - .body("payload.grantablePermissions", containsInAnyOrder("api.impact.read", "api.simulation.read", "api.environment.read", "api.module.read", "api.environment.write", "api.metric.write")) + .body("payload.grantablePermissions", containsInAnyOrder("api.impact.read", "api.simulation.read", "api.environment.read", "api.module.read", "api.environment.write", "api.asset.read", "api.asset.write", "api.metric.write")) .body("payload.maxLifetimeDays", is(365)) .body("payload.allowNeverExpiring", is(false)); }