diff --git a/pom.xml b/pom.xml index 5cbaebf..bc4d8ca 100644 --- a/pom.xml +++ b/pom.xml @@ -164,7 +164,7 @@ io.quarkus - quarkus-hibernate-orm-panache + quarkus-hibernate-orm io.quarkus diff --git a/src/main/java/tech/illuin/wombat/commons/ConfigSourceFactories.java b/src/main/java/tech/illuin/wombat/commons/ConfigSourceFactories.java new file mode 100644 index 0000000..7573425 --- /dev/null +++ b/src/main/java/tech/illuin/wombat/commons/ConfigSourceFactories.java @@ -0,0 +1,21 @@ +package tech.illuin.wombat.commons; + +public enum ConfigSourceFactories +{ + NODE_MODE(9001), + BACKEND_MODE(9000), + FEATURE_FLAG(9000), + ; + + private final int priority; + + ConfigSourceFactories(int priority) + { + this.priority = priority; + } + + public int priority() + { + return this.priority; + } +} diff --git a/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java b/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java index ccc2cb1..d27449a 100644 --- a/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java +++ b/src/main/java/tech/illuin/wombat/commons/NodeModeConfigSourceFactory.java @@ -8,45 +8,47 @@ import org.eclipse.microprofile.config.spi.ConfigSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import tech.illuin.wombat.persistence.BackendMode; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.OptionalInt; +import static tech.illuin.wombat.commons.ConfigSourceFactories.NODE_MODE; import static tech.illuin.wombat.persistence.PersistenceBackendConfigSourceFactory.ACTIVE_BACKEND_CONFIG_KEY; +import static tech.illuin.wombat.persistence.PersistenceBackendConfigSourceFactory.PERSISTENCE_BACKEND_MODE_KEY; @StaticInitSafe public class NodeModeConfigSourceFactory implements ConfigSourceFactory { - private static final String WORKER_DB_KIND = "sqlite"; - private static final String WORKER_JDBC_URL = "jdbc:sqlite::memory:"; - private static final Logger logger = LoggerFactory.getLogger(NodeModeConfigSourceFactory.class); @Override public Iterable getConfigSources(ConfigSourceContext context) { - ConfigValue value = context.getValue("wombat.mode"); - NodeMode mode = value.getValue() == null ? null : NodeMode.parse(value.getValue()); + String value = context.getValue("wombat.mode").getValue(); + NodeMode mode = value == null ? NodeMode.standalone : NodeMode.parse(value); Map properties = new HashMap<>(); if (mode == NodeMode.worker) { - String backend = context.getValue(ACTIVE_BACKEND_CONFIG_KEY).getValue(); - if (backend != null && !backend.equals(WORKER_DB_KIND)) - logger.warn("Worker mode only runs on SQLite in-memory: overriding backend {} with {}", backend, WORKER_DB_KIND); - - properties.put("quarkus.datasource.db-kind", WORKER_DB_KIND); - properties.put("quarkus.datasource.jdbc.url", WORKER_JDBC_URL); - properties.put("quarkus.datasource.jdbc.min-size", "1"); - properties.put("quarkus.datasource.jdbc.max-size", "1"); - properties.put(ACTIVE_BACKEND_CONFIG_KEY, WORKER_DB_KIND); + logger.debug("Overriding persistence backend for worker mode: set to in-memory sqlite"); + properties.put(PERSISTENCE_BACKEND_MODE_KEY, BackendMode.sqlite.name()); + properties.put("persistence.backend.sqlite.jdbc-url", "jdbc:sqlite::memory:"); } + logger.debug("Node mode established: {}", mode); return List.of(new PropertiesConfigSource( properties, NodeModeConfigSourceFactory.class.getSimpleName(), - Integer.MAX_VALUE + NODE_MODE.priority() )); } + + @Override + public OptionalInt getPriority() + { + return OptionalInt.of(NODE_MODE.priority()); + } } 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 4a64e57..6e8b4bd 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java +++ b/src/main/java/tech/illuin/wombat/engine/context/EnvironmentReconciler.java @@ -183,7 +183,7 @@ private AssetConfigAction reconcileAsset(String owner, String environmentId, Ass private List deleteMissingAssets(String owner, Set desiredAssetIds) { List deleted = new ArrayList<>(); - for (AssetEntity entity : this.assetRepository.list("deletedAt is null")) + for (AssetEntity entity : this.assetRepository.findActive()) { if (desiredAssetIds.contains(entity.id) || !Objects.equals(entity.owner, owner)) continue; @@ -202,7 +202,7 @@ private void disableEmptyEnvironments(String owner, Set desiredEnvironme declared.addAll(this.monitoredEnvironments.environments().keySet()); Set withAssets = new HashSet<>(); - for (AssetEntity entity : this.assetRepository.list("deletedAt is null")) + for (AssetEntity entity : this.assetRepository.findActive()) { if (entity.deletedAt == null) withAssets.add(entity.environmentId); diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java index 742e64a..25be8d8 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistory.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.EnumType; @@ -19,7 +18,7 @@ */ @Entity @Table(name = "asset_config_history") -public class AssetConfigHistory extends PanacheEntityBase +public class AssetConfigHistory { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java index 2f16713..07a5863 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetConfigHistoryRepository.java @@ -1,15 +1,23 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; @ApplicationScoped -public class AssetConfigHistoryRepository implements PanacheRepositoryBase +public class AssetConfigHistoryRepository extends Repository { + public AssetConfigHistoryRepository() + { + super(AssetConfigHistory.class); + } + public List findByAsset(String assetId) { - return this.list("assetId = ?1 order by changedAt", assetId); + return getEntityManager() + .createQuery("FROM AssetConfigHistory WHERE assetId = :assetId ORDER BY changedAt", AssetConfigHistory.class) + .setParameter("assetId", assetId) + .getResultList(); } } diff --git a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java index 2ee9ad4..9cd0be8 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetEntity.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Convert; import jakarta.persistence.Entity; @@ -15,7 +14,7 @@ @Entity @Table(name = "assets") -public class AssetEntity extends PanacheEntityBase +public class AssetEntity { @Id @Column(nullable = false) 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 index 8d0d990..7b9ae3c 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/AssetRepository.java @@ -1,15 +1,30 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; @ApplicationScoped -public class AssetRepository implements PanacheRepositoryBase +public class AssetRepository extends Repository { + public AssetRepository() + { + super(AssetEntity.class); + } + public List findByEnvironment(String environmentId) { - return this.list("environmentId = ?1 and deletedAt is null", 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/EnvironmentEntity.java b/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java index 94cdac1..aafcade 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentEntity.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -14,7 +13,7 @@ @Entity @Table(name = "environments") -public class EnvironmentEntity extends PanacheEntityBase +public class EnvironmentEntity { @Id @Column(nullable = false) public String id; 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 index 24d8d80..4b1f967 100644 --- a/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepository.java @@ -1,15 +1,22 @@ package tech.illuin.wombat.engine.context.persistence; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; @ApplicationScoped -public class EnvironmentRepository implements PanacheRepositoryBase +public class EnvironmentRepository extends Repository { + public EnvironmentRepository() + { + super(EnvironmentEntity.class); + } + public List findActive() { - return this.list("disabledAt is null"); + return getEntityManager() + .createQuery("FROM EnvironmentEntity WHERE disabledAt IS NULL", EnvironmentEntity.class) + .getResultList(); } } diff --git a/src/main/java/tech/illuin/wombat/engine/impact/kubernetes/KubernetesMetricRepository.java b/src/main/java/tech/illuin/wombat/engine/impact/kubernetes/KubernetesMetricRepository.java index 2659519..e2c63dd 100644 --- a/src/main/java/tech/illuin/wombat/engine/impact/kubernetes/KubernetesMetricRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/impact/kubernetes/KubernetesMetricRepository.java @@ -1,9 +1,10 @@ package tech.illuin.wombat.engine.impact.kubernetes; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; import jakarta.persistence.Query; import jakarta.transaction.Transactional; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import tech.illuin.wombat.persistence.compaction.BucketCompactor; import tech.illuin.wombat.core.activity.commons.TimeRange; import tech.illuin.wombat.core.asset.AssetIdentity; @@ -20,15 +21,22 @@ import static tech.illuin.wombat.core.activity.commons.TimeRange.toEpochMs; @ApplicationScoped -public class KubernetesMetricRepository implements PanacheRepositoryBase, KubernetesMetricResolver, BucketCompactor +public class KubernetesMetricRepository extends Repository implements KubernetesMetricResolver, BucketCompactor { private static final String DATA = "data"; private static final String SERVICE_ID = "serviceId"; private final JsonPathDialect dialect; + public KubernetesMetricRepository() + { + this(null); + } + + @Inject public KubernetesMetricRepository(JsonPathDialect dialect) { + super(KubernetesMetricEntity.class); this.dialect = dialect; } @@ -44,10 +52,53 @@ public void save(Collection entities) persist(entities); } + @Transactional + public void deleteByAssetId(String assetId) + { + this.getEntityManager() + .createNativeQuery("DELETE FROM server_metrics WHERE asset_id = ?1") + .setParameter(1, assetId) + .executeUpdate(); + } + + @Transactional + public void deleteByAssetIds(List assetIds) + { + if (assetIds.isEmpty()) + return; + this.getEntityManager() + .createQuery("DELETE FROM KubernetesMetricEntity WHERE assetId IN :ids") + .setParameter("ids", assetIds) + .executeUpdate(); + } + + @Transactional + public List listByAssetId(String assetId) + { + return getEntityManager() + .createQuery("FROM KubernetesMetricEntity WHERE assetId = :assetId", KubernetesMetricEntity.class) + .setParameter("assetId", assetId) + .getResultList(); + } + + @Transactional + public long countByAssetId(String assetId) + { + return ((Number) getEntityManager() + .createQuery("SELECT COUNT(m) FROM KubernetesMetricEntity m WHERE m.assetId = :assetId") + .setParameter("assetId", assetId) + .getSingleResult() + ).longValue(); + } + @Transactional public List findByRange(long startMs, long endMs) { - return find("instantMs >= ?1 AND instantMs <= ?2", startMs, endMs).list(); + return getEntityManager() + .createQuery("FROM KubernetesMetricEntity WHERE instantMs >= :start AND instantMs <= :end", KubernetesMetricEntity.class) + .setParameter("start", startMs) + .setParameter("end", endMs) + .getResultList(); } @Transactional @@ -173,8 +224,11 @@ public List uncompactedBuckets(long stepMs, long beforeMs) public int compactBucket(long bucketStartMs, long stepMs) { long bucketEndMs = bucketStartMs + stepMs; - List rows = find( - "instantMs >= ?1 AND instantMs < ?2", bucketStartMs, bucketEndMs).list(); + List rows = this.getEntityManager() + .createQuery("FROM KubernetesMetricEntity WHERE instantMs >= :start AND instantMs < :end", KubernetesMetricEntity.class) + .setParameter("start", bucketStartMs) + .setParameter("end", bucketEndMs) + .getResultList(); if (rows.stream().allMatch(row -> row.compacted)) return 0; @@ -196,7 +250,11 @@ public int compactBucket(long bucketStartMs, long stepMs) folded.add(row); }); - delete("instantMs >= ?1 AND instantMs < ?2", bucketStartMs, bucketEndMs); + getEntityManager() + .createNativeQuery("DELETE FROM server_metrics WHERE instant_ms >= ?1 AND instant_ms < ?2") + .setParameter(1, bucketStartMs) + .setParameter(2, bucketEndMs) + .executeUpdate(); getEntityManager().clear(); folded.forEach(this::persist); diff --git a/src/main/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepository.java b/src/main/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepository.java index 509b281..aa05872 100644 --- a/src/main/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepository.java @@ -1,9 +1,10 @@ package tech.illuin.wombat.engine.impact.llm; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; import jakarta.persistence.Query; import jakarta.transaction.Transactional; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import tech.illuin.wombat.persistence.compaction.BucketCompactor; import tech.illuin.wombat.core.activity.commons.Country; import tech.illuin.wombat.core.activity.commons.TimeRange; @@ -25,15 +26,22 @@ import static tech.illuin.wombat.core.activity.commons.TimeRange.toEpochMs; @ApplicationScoped -public class LLMModelMetricRepository implements PanacheRepositoryBase, LLMMetricResolver, BucketCompactor +public class LLMModelMetricRepository extends Repository implements LLMMetricResolver, BucketCompactor { private final JsonPathDialect dialect; + @Inject public LLMModelMetricRepository(JsonPathDialect dialect) { + super(LLMMetricEntity.class); this.dialect = dialect; } + public LLMModelMetricRepository() + { + this(null); + } + @Transactional public void save(LLMMetricEntity entity) { @@ -46,6 +54,44 @@ public void save(Collection entities) this.persist(entities); } + @Transactional + public void deleteByAssetId(String assetId) + { + this.getEntityManager() + .createNativeQuery("DELETE FROM model_metrics WHERE asset_id = ?1") + .setParameter(1, assetId) + .executeUpdate(); + } + + @Transactional + public void deleteByAssetIds(List assetIds) + { + if (assetIds.isEmpty()) + return; + this.getEntityManager() + .createQuery("DELETE FROM LLMMetricEntity WHERE assetId IN :ids") + .setParameter("ids", assetIds) + .executeUpdate(); + } + + @Transactional + public List listByAssetId(String assetId) + { + return this.getEntityManager() + .createQuery("FROM LLMMetricEntity WHERE assetId = :assetId", LLMMetricEntity.class) + .setParameter("assetId", assetId) + .getResultList(); + } + + @Transactional + public long countByAssetId(String assetId) + { + return ((Number) this.getEntityManager() + .createQuery("SELECT COUNT(m) FROM LLMMetricEntity m WHERE m.assetId = :assetId") + .setParameter("assetId", assetId) + .getSingleResult()).longValue(); + } + @Override @Transactional public List uncompactedBuckets(long stepMs, long beforeMs) { @@ -63,7 +109,12 @@ public List uncompactedBuckets(long stepMs, long beforeMs) public int compactBucket(long bucketStartMs, long stepMs) { long bucketEndMs = bucketStartMs + stepMs; - List rows = find("instantMs >= ?1 AND instantMs < ?2", bucketStartMs, bucketEndMs).list(); + List rows = this.getEntityManager() + .createQuery("FROM LLMMetricEntity WHERE instantMs >= :start AND instantMs < :end", LLMMetricEntity.class) + .setParameter("start", bucketStartMs) + .setParameter("end", bucketEndMs) + .getResultList(); + if (rows.stream().allMatch(row -> row.compacted)) return 0; @@ -83,8 +134,12 @@ public int compactBucket(long bucketStartMs, long stepMs) folded.add(row); }); - delete("instantMs >= ?1 AND instantMs < ?2", bucketStartMs, bucketEndMs); - getEntityManager().clear(); + this.getEntityManager() + .createNativeQuery("DELETE FROM model_metrics WHERE instant_ms >= ?1 AND instant_ms < ?2") + .setParameter(1, bucketStartMs) + .setParameter(2, bucketEndMs) + .executeUpdate(); + this.getEntityManager().clear(); folded.forEach(this::persist); return folded.size(); @@ -116,7 +171,7 @@ public Map> serviceActivitiesPerBucket(Tim ORDER BY %5$s """.formatted(serviceIdCol, providerCol, modelCol, locationCol, bucket); - Query query = getEntityManager().createNativeQuery(sql); + Query query = this.getEntityManager().createNativeQuery(sql); query.setParameter("start", startMs); query.setParameter("end", endMs); query.setParameter("assetId", assetId); diff --git a/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretStore.java b/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretStore.java index ec94a38..ff7706d 100644 --- a/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretStore.java +++ b/src/main/java/tech/illuin/wombat/engine/secret/database/DatabaseSecretStore.java @@ -63,7 +63,10 @@ public void putSecret(String key, String value) public boolean deleteSecret(String key) { validateKey(key); - return this.secrets.deleteById(key); + SecretEntity entity = this.secrets.findById(key); + if (entity != null) + this.secrets.delete(entity); + return entity != null; } @Override @Transactional 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 fae81ae..21ea68b 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 @@ -1,6 +1,5 @@ package tech.illuin.wombat.engine.secret.database.persistence; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -15,7 +14,7 @@ @Entity @Table(name = "secrets") -public class SecretEntity extends PanacheEntityBase +public class SecretEntity { @Id @Column(name = "secret_key", nullable = false, columnDefinition = "TEXT") diff --git a/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretRepository.java b/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretRepository.java index 61cbc2b..84c72f0 100644 --- a/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretRepository.java +++ b/src/main/java/tech/illuin/wombat/engine/secret/database/persistence/SecretRepository.java @@ -1,15 +1,20 @@ package tech.illuin.wombat.engine.secret.database.persistence; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; import jakarta.persistence.Query; import tech.illuin.wombat.core.secret.SecretMetadata; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; @ApplicationScoped -public class SecretRepository implements PanacheRepositoryBase +public class SecretRepository extends Repository { + public SecretRepository() + { + super(SecretEntity.class); + } + public List listMetadata() { return getEntityManager().createQuery( @@ -51,6 +56,9 @@ public int updateWrappedDekIfRevisionMatches(String key, long revision, String k public long countNeedingRewrap(String activeKekId) { - return count("kekId <> ?1", activeKekId); + Query query = getEntityManager().createQuery( + "SELECT COUNT(s) FROM SecretEntity s WHERE s.kekId <> :activeKekId"); + query.setParameter("activeKekId", activeKekId); + return ((Number) query.getSingleResult()).longValue(); } } diff --git a/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java b/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java index 8fe6b37..1f012bd 100644 --- a/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java +++ b/src/main/java/tech/illuin/wombat/feature/FeatureConfigSourceFactory.java @@ -10,6 +10,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.OptionalInt; + +import static tech.illuin.wombat.commons.ConfigSourceFactories.BACKEND_MODE; +import static tech.illuin.wombat.commons.ConfigSourceFactories.FEATURE_FLAG; /** Sets the {@link Feature.Keys} from the node mode, so endpoints are gated before the application starts. */ @StaticInitSafe @@ -35,7 +39,13 @@ public Iterable getConfigSources(ConfigSourceContext context) return List.of(new PropertiesConfigSource( properties, FeatureConfigSourceFactory.class.getSimpleName(), - Integer.MAX_VALUE + FEATURE_FLAG.priority() )); } + + @Override + public OptionalInt getPriority() + { + return OptionalInt.of(FEATURE_FLAG.priority()); + } } diff --git a/src/main/java/tech/illuin/wombat/persistence/BackendMode.java b/src/main/java/tech/illuin/wombat/persistence/BackendMode.java index a9465ce..a2f6a93 100644 --- a/src/main/java/tech/illuin/wombat/persistence/BackendMode.java +++ b/src/main/java/tech/illuin/wombat/persistence/BackendMode.java @@ -1,23 +1,46 @@ package tech.illuin.wombat.persistence; +import tech.illuin.wombat.persistence.PersistenceBackendProperties.PostgreSQLProperties; +import tech.illuin.wombat.persistence.PersistenceBackendProperties.SQLiteProperties; + +import java.util.Map; + public enum BackendMode { - sqlite + sqlite(Map.of( + "persistence.backend.sqlite.jdbc-url", "quarkus.datasource.sqlite.jdbc.url" + )) { @Override - public PersistenceBackendProperties.SQLiteProperties getSection(PersistenceBackendProperties parent) + public SQLiteProperties getSection(PersistenceBackendProperties parent) { return parent.sqlite().orElseThrow(() -> new IllegalArgumentException("sqlite properties required when mode=sqlite")); } }, - postgresql + postgresql(Map.of( + "persistence.backend.postgresql.jdbc-url", "quarkus.datasource.postgresql.jdbc.url", + "persistence.backend.postgresql.username", "quarkus.datasource.postgresql.username", + "persistence.backend.postgresql.password", "quarkus.datasource.postgresql.password" + )) { @Override - public PersistenceBackendProperties.PostgreSQLProperties getSection(PersistenceBackendProperties parent) + public PostgreSQLProperties getSection(PersistenceBackendProperties parent) { return parent.postgresql().orElseThrow(() -> new IllegalArgumentException("postgresql properties required when mode=postgresql")); } }; + private final Map configMap; + + BackendMode(Map configMap) + { + this.configMap = configMap; + } + public abstract T getSection(PersistenceBackendProperties parent); + + public Map configMap() + { + return this.configMap; + } } diff --git a/src/main/java/tech/illuin/wombat/persistence/PersistenceBackendConfigSourceFactory.java b/src/main/java/tech/illuin/wombat/persistence/PersistenceBackendConfigSourceFactory.java index 30716c6..ba3003c 100644 --- a/src/main/java/tech/illuin/wombat/persistence/PersistenceBackendConfigSourceFactory.java +++ b/src/main/java/tech/illuin/wombat/persistence/PersistenceBackendConfigSourceFactory.java @@ -8,64 +8,67 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; +import java.util.*; + +import static tech.illuin.wombat.commons.ConfigSourceFactories.BACKEND_MODE; @StaticInitSafe public class PersistenceBackendConfigSourceFactory implements ConfigSourceFactory { + public static final String PERSISTENCE_BACKEND_MODE_KEY = "persistence.backend.mode"; public static final String ACTIVE_BACKEND_CONFIG_KEY = "_internal.persistence.backend"; private static final Logger logger = LoggerFactory.getLogger(PersistenceBackendConfigSourceFactory.class); @Override public Iterable getConfigSources(ConfigSourceContext context) { - String modeStr = context.getValue("persistence.backend.mode").getValue(); - BackendMode mode = modeStr == null ? BackendMode.sqlite : parse(modeStr); + String modeStr = context.getValue(PERSISTENCE_BACKEND_MODE_KEY).getValue(); + BackendMode activeMode = modeStr == null ? BackendMode.sqlite : parse(modeStr); Map properties = new HashMap<>(); - properties.put(ACTIVE_BACKEND_CONFIG_KEY, mode.name().toLowerCase(Locale.ROOT)); - - switch (mode) - { - case sqlite: - properties.put("quarkus.datasource.db-kind", "sqlite"); - String sqliteUrl = context.getValue("persistence.backend.sqlite.jdbc-url").getValue(); - if (sqliteUrl != null) - properties.put("quarkus.datasource.jdbc.url", sqliteUrl); - properties.put("quarkus.flyway.locations", "classpath:db/migration/sqlite"); - break; + properties.put(ACTIVE_BACKEND_CONFIG_KEY, activeMode.name()); - case postgresql: - properties.put("quarkus.datasource.db-kind", "postgresql"); - String pgUrl = context.getValue("persistence.backend.postgresql.jdbc-url").getValue(); - if (pgUrl != null) - properties.put("quarkus.datasource.jdbc.url", pgUrl); - String pgUser = context.getValue("persistence.backend.postgresql.username").getValue(); - if (pgUser != null) - properties.put("quarkus.datasource.username", pgUser); - String pgPass = context.getValue("persistence.backend.postgresql.password").getValue(); - if (pgPass != null) - properties.put("quarkus.datasource.password", pgPass); - properties.put("quarkus.flyway.locations", "classpath:db/migration/postgresql"); - break; + for (BackendMode mode : BackendMode.values()) + toggleProperties(properties, mode, activeMode == mode); + mapProperties(context, properties, activeMode); - default: - throw new IllegalArgumentException("Unknown backend mode: " + mode); - } - - logger.info("Persistence backend set to {} (priority {})", mode, Integer.MAX_VALUE - 1000); + logger.info("Persistence backend established: {}", activeMode); return List.of(new PropertiesConfigSource( properties, PersistenceBackendConfigSourceFactory.class.getSimpleName(), - Integer.MAX_VALUE - 1000 + BACKEND_MODE.priority() )); } + private static void toggleProperties(Map properties, BackendMode mode, boolean enabled) + { + String state = Boolean.toString(enabled); + properties.put("quarkus.datasource." + mode.name() + ".active", state); + properties.put("quarkus.hibernate-orm." + mode.name() + ".active", state); + properties.put("quarkus.hibernate-orm." + mode.name() + ".datasource", mode.name()); + properties.put("quarkus.hibernate-orm." + mode.name() + ".packages", "tech.illuin.wombat"); + properties.put("quarkus.hibernate-orm." + mode.name() + ".schema-management.strategy", "none"); + properties.put("quarkus.flyway." + mode.name() + ".active", state); + properties.put("quarkus.flyway." + mode.name() + ".migrate-at-start", "false"); + } + + private static void mapProperties(ConfigSourceContext context, Map properties, BackendMode mode) + { + mode.configMap().forEach((key, value) -> { + String ctxValue = context.getValue(key).getValue(); + if (ctxValue != null) + properties.put(value, ctxValue); + }); + } + private static BackendMode parse(String mode) { return BackendMode.valueOf(mode.trim().replace('-', '_').toLowerCase(Locale.ROOT)); } + + @Override + public OptionalInt getPriority() + { + return OptionalInt.of(BACKEND_MODE.priority()); + } } diff --git a/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/ActiveEntityManagerProducer.java b/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/ActiveEntityManagerProducer.java new file mode 100644 index 0000000..8f99d7b --- /dev/null +++ b/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/ActiveEntityManagerProducer.java @@ -0,0 +1,36 @@ +package tech.illuin.wombat.persistence.backend.api.repository; + +import io.quarkus.hibernate.orm.PersistenceUnit; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.enterprise.inject.Instance; +import jakarta.enterprise.inject.Produces; +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import org.eclipse.microprofile.config.inject.ConfigProperty; +import tech.illuin.wombat.persistence.BackendMode; + +import static tech.illuin.wombat.persistence.PersistenceBackendConfigSourceFactory.ACTIVE_BACKEND_CONFIG_KEY; + +@ApplicationScoped +public class ActiveEntityManagerProducer +{ + @Inject @PersistenceUnit("sqlite") + Instance sqliteEm; + + @Inject @PersistenceUnit("postgresql") + Instance postgresqlEm; + + @ConfigProperty(name = ACTIVE_BACKEND_CONFIG_KEY) + String activeBackend; + + @Produces + public EntityManager produceActiveEntityManager() + { + BackendMode mode = BackendMode.valueOf(this.activeBackend); + + return switch (mode) { + case sqlite -> sqliteEm.get(); + case postgresql -> postgresqlEm.get(); + }; + } +} diff --git a/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/Repository.java b/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/Repository.java new file mode 100644 index 0000000..6c3fa7d --- /dev/null +++ b/src/main/java/tech/illuin/wombat/persistence/backend/api/repository/Repository.java @@ -0,0 +1,94 @@ +package tech.illuin.wombat.persistence.backend.api.repository; + +import jakarta.inject.Inject; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; + +import java.util.List; +import java.util.Optional; + +public abstract class Repository +{ + @Inject + protected EntityManager entityManager; + + private final Class entityClass; + + protected Repository(Class entityClass) + { + this.entityClass = entityClass; + } + + protected EntityManager getEntityManager() + { + return this.entityManager; + } + + public boolean isPersistent(Entity entity) + { + return this.entityManager.contains(entity); + } + + @Transactional + public void persist(Entity entity) + { + this.entityManager.persist(entity); + } + + @Transactional + public void persist(Iterable entities) + { + for (Entity entity : entities) + this.entityManager.persist(entity); + } + + @Transactional + public Entity findById(Id id) + { + return this.entityManager.find(this.entityClass, id); + } + + @Transactional + public Optional findByIdOptional(Id id) + { + return Optional.ofNullable(this.findById(id)); + } + + @Transactional + public List listAll() + { + return this.entityManager + .createQuery("FROM " + this.entityClass.getSimpleName(), this.entityClass) + .getResultList(); + } + + @Transactional + public void delete(Entity entity) + { + Entity managed = this.entityManager.contains(entity) ? entity : this.entityManager.merge(entity); + this.entityManager.remove(managed); + } + + @Transactional + public void deleteById(Id id) + { + String idAttribute = this.entityManager.getMetamodel() + .entity(this.entityClass) + .getId(Object.class) + .getName(); + + //noinspection SqlSourceToSinkFlow + this.entityManager + .createQuery("DELETE FROM " + this.entityClass.getSimpleName() + " WHERE " + idAttribute + " = :id") + .setParameter("id", id) + .executeUpdate(); + } + + @Transactional + public void deleteAll() + { + this.entityManager + .createQuery("DELETE FROM " + this.entityClass.getSimpleName()) + .executeUpdate(); + } +} diff --git a/src/main/java/tech/illuin/wombat/persistence/backend/postgres/PostgresBackendConfig.java b/src/main/java/tech/illuin/wombat/persistence/backend/postgres/PostgresBackendConfig.java index 1947ae7..d65d739 100644 --- a/src/main/java/tech/illuin/wombat/persistence/backend/postgres/PostgresBackendConfig.java +++ b/src/main/java/tech/illuin/wombat/persistence/backend/postgres/PostgresBackendConfig.java @@ -2,6 +2,9 @@ import io.agroal.api.AgroalDataSource; import io.micrometer.core.instrument.MeterRegistry; +import io.quarkus.agroal.DataSource; +import io.quarkus.arc.InjectableInstance; +import io.quarkus.flyway.FlywayDataSource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Singleton; @@ -27,8 +30,8 @@ public class PostgresBackendConfig @Produces @Singleton public PersistenceBackend providePostgresBackend( PersistenceBackendProperties backendProps, - Instance dataSources, - Instance flyway, + @DataSource("postgresql") InjectableInstance dataSources, + @FlywayDataSource("postgresql") InjectableInstance flyway, Instance registry, MetricStoreContainer databaseStores ) { diff --git a/src/main/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackendConfig.java b/src/main/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackendConfig.java index 62be549..92b7593 100644 --- a/src/main/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackendConfig.java +++ b/src/main/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackendConfig.java @@ -2,6 +2,9 @@ import io.agroal.api.AgroalDataSource; import io.micrometer.core.instrument.MeterRegistry; +import io.quarkus.agroal.DataSource; +import io.quarkus.arc.InjectableInstance; +import io.quarkus.flyway.FlywayDataSource; import jakarta.enterprise.context.ApplicationScoped; import jakarta.enterprise.inject.Instance; import jakarta.inject.Singleton; @@ -32,8 +35,8 @@ public class SQLiteBackendConfig @Produces @Singleton public PersistenceBackend provideSQLiteBackend( PersistenceBackendProperties backendProps, - Instance dataSources, - Instance flyway, + @DataSource("sqlite") InjectableInstance dataSources, + @FlywayDataSource("sqlite") InjectableInstance flyway, Instance registry, MetricStoreContainer databaseStores ) { @@ -73,4 +76,5 @@ public PersistenceBackend provideSQLiteBackend( return PersistenceBackend.of(DBKIND_SQLITE, hooks, processes, databaseStores); } + } diff --git a/src/main/java/tech/illuin/wombat/persistence/model/MetricEntity.java b/src/main/java/tech/illuin/wombat/persistence/model/MetricEntity.java index d895fdd..811c856 100644 --- a/src/main/java/tech/illuin/wombat/persistence/model/MetricEntity.java +++ b/src/main/java/tech/illuin/wombat/persistence/model/MetricEntity.java @@ -1,12 +1,11 @@ package tech.illuin.wombat.persistence.model; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.MappedSuperclass; import tech.illuin.wombat.core.asset.AssetIdentity; @MappedSuperclass -public abstract class MetricEntity extends PanacheEntityBase +public abstract class MetricEntity { @Column(name = "asset_id", nullable = false) public String assetId; 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 0af1a6f..c8145a3 100644 --- a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java +++ b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyEntity.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.security.apikey; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Convert; import jakarta.persistence.Entity; @@ -19,7 +18,7 @@ /** A key belongs to the user who created it, and never grants more than its owner currently holds. */ @Entity @Table(name = "api_keys") -public class ApiKeyEntity extends PanacheEntityBase +public class ApiKeyEntity { @Id @Column(nullable = false) public String id; diff --git a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyRepository.java b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyRepository.java index 459ba2c..5a59bde 100644 --- a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyRepository.java +++ b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyRepository.java @@ -1,26 +1,41 @@ package tech.illuin.wombat.security.apikey; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; import java.util.Optional; @ApplicationScoped -public class ApiKeyRepository implements PanacheRepositoryBase +public class ApiKeyRepository extends Repository { + public ApiKeyRepository() + { + super(ApiKeyEntity.class); + } + public Optional findByHash(String keyHash) { - return this.find("keyHash", keyHash).firstResultOptional(); + List results = getEntityManager() + .createQuery("FROM ApiKeyEntity WHERE keyHash = :keyHash", ApiKeyEntity.class) + .setParameter("keyHash", keyHash) + .setMaxResults(1) + .getResultList(); + return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0)); } public List findAllNewestFirst() { - return this.list("order by createdAt desc"); + return getEntityManager() + .createQuery("FROM ApiKeyEntity ORDER BY createdAt DESC", ApiKeyEntity.class) + .getResultList(); } public List findByOwnerNewestFirst(String ownerId) { - return this.list("ownerId = ?1 order by createdAt desc", ownerId); + return getEntityManager() + .createQuery("FROM ApiKeyEntity WHERE ownerId = :ownerId ORDER BY createdAt DESC", ApiKeyEntity.class) + .setParameter("ownerId", ownerId) + .getResultList(); } } 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 cd1f799..505b5a0 100644 --- a/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java +++ b/src/main/java/tech/illuin/wombat/security/apikey/ApiKeyService.java @@ -84,7 +84,7 @@ public Issued create(Caller caller, String name, Collection permissions, String token = ApiKeyTokens.generate(); ApiKeyEntity key = this.newKey(owner, name, granted, expiresAt); key.keyHash = ApiKeyTokens.hash(token); - key.persist(); + this.keys.persist(key); return new Issued(key, token); } @@ -107,7 +107,8 @@ public List list(Caller caller, boolean all) List ownerIds = listed.stream().map(key -> key.ownerId).distinct().toList(); Map owners = ownerIds.isEmpty() ? Map.of() - : this.users.list("id in ?1", ownerIds).stream().collect(Collectors.toMap(user -> user.id, Function.identity())); + : this.users.findByIds(ownerIds) + .stream().collect(Collectors.toMap(user -> user.id, Function.identity())); return listed.stream() .map(key -> new Listed(key, displayName(owners.get(key.ownerId), key.ownerId))) 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 d90d2f0..248e2cb 100644 --- a/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java +++ b/src/main/java/tech/illuin/wombat/security/user/RoleGrantEntity.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.security.user; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Entity; import jakarta.persistence.Id; @@ -15,7 +14,7 @@ /** A Wombat role granted to a user by an admin, held on top of the roles mapped from the identity provider. */ @Entity @Table(name = "role_grants") -public class RoleGrantEntity extends PanacheEntityBase +public class RoleGrantEntity { @Id @Column(nullable = false) public String id; diff --git a/src/main/java/tech/illuin/wombat/security/user/RoleGrantRepository.java b/src/main/java/tech/illuin/wombat/security/user/RoleGrantRepository.java index d3ab7a7..f489404 100644 --- a/src/main/java/tech/illuin/wombat/security/user/RoleGrantRepository.java +++ b/src/main/java/tech/illuin/wombat/security/user/RoleGrantRepository.java @@ -1,23 +1,34 @@ package tech.illuin.wombat.security.user; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; import java.util.List; import java.util.Optional; @ApplicationScoped -public class RoleGrantRepository implements PanacheRepositoryBase +public class RoleGrantRepository extends Repository { + public RoleGrantRepository() + { + super(RoleGrantEntity.class); + } + public Optional findByUserAndRole(String userId, String role) { - return this.find("userId = ?1 and role = ?2", userId, role).firstResultOptional(); + List results = getEntityManager() + .createQuery("FROM RoleGrantEntity WHERE userId = :userId AND role = :role", RoleGrantEntity.class) + .setParameter("userId", userId) + .setParameter("role", role) + .setMaxResults(1) + .getResultList(); + return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0)); } /** Every grant with its user's identity: rows of {@code [issuer, subject, role]}. */ public List findAllWithIdentity() { - return this.getEntityManager() + return getEntityManager() .createQuery("select u.issuer, u.subject, g.role from RoleGrantEntity g, UserEntity u where u.id = g.userId", Object[].class) .getResultList(); } diff --git a/src/main/java/tech/illuin/wombat/security/user/RoleGrantService.java b/src/main/java/tech/illuin/wombat/security/user/RoleGrantService.java index 033b279..f51c396 100644 --- a/src/main/java/tech/illuin/wombat/security/user/RoleGrantService.java +++ b/src/main/java/tech/illuin/wombat/security/user/RoleGrantService.java @@ -98,7 +98,7 @@ public void grant(Caller admin, String userId, String roleValue) grant.userId = user.id; grant.role = role.value(); grant.grantedBy = this.userService.ensure(admin).id; - grant.persist(); + this.grants.persist(grant); logger.info("{} granted role {} to {}", admin.name(), role.value(), user.name); }); this.reload(); @@ -113,7 +113,7 @@ public void revoke(Caller admin, String userId, String roleValue) throw new ClientErrorException("You cannot remove your own admin role", Response.Status.CONFLICT); this.grants.findByUserAndRole(userId, role.value()).ifPresent(grant -> { - grant.delete(); + this.grants.delete(grant); logger.info("{} removed role {} from {}", admin.name(), role.value(), user.name); }); }); 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 4aad4b7..43bacc1 100644 --- a/src/main/java/tech/illuin/wombat/security/user/UserEntity.java +++ b/src/main/java/tech/illuin/wombat/security/user/UserEntity.java @@ -1,6 +1,5 @@ package tech.illuin.wombat.security.user; -import io.quarkus.hibernate.orm.panache.PanacheEntityBase; import jakarta.persistence.Column; import jakarta.persistence.Convert; import jakarta.persistence.Entity; @@ -23,7 +22,7 @@ */ @Entity @Table(name = "users") -public class UserEntity extends PanacheEntityBase +public class UserEntity { @Id @Column(nullable = false) public String id; diff --git a/src/main/java/tech/illuin/wombat/security/user/UserRepository.java b/src/main/java/tech/illuin/wombat/security/user/UserRepository.java index 1296da5..9513579 100644 --- a/src/main/java/tech/illuin/wombat/security/user/UserRepository.java +++ b/src/main/java/tech/illuin/wombat/security/user/UserRepository.java @@ -1,21 +1,43 @@ package tech.illuin.wombat.security.user; -import io.quarkus.hibernate.orm.panache.PanacheRepositoryBase; import jakarta.enterprise.context.ApplicationScoped; +import tech.illuin.wombat.persistence.backend.api.repository.Repository; +import java.util.Collection; import java.util.List; import java.util.Optional; @ApplicationScoped -public class UserRepository implements PanacheRepositoryBase +public class UserRepository extends Repository { + public UserRepository() + { + super(UserEntity.class); + } + public Optional findByIdentity(String issuer, String subject) { - return this.find("issuer = ?1 and subject = ?2", issuer, subject).firstResultOptional(); + List results = getEntityManager() + .createQuery("FROM UserEntity WHERE issuer = :issuer AND subject = :subject", UserEntity.class) + .setParameter("issuer", issuer) + .setParameter("subject", subject) + .setMaxResults(1) + .getResultList(); + return results.isEmpty() ? Optional.empty() : Optional.of(results.get(0)); } public List findAllByName() { - return this.list("order by lower(coalesce(name, subject))"); + return getEntityManager() + .createQuery("FROM UserEntity ORDER BY LOWER(COALESCE(name, subject))", UserEntity.class) + .getResultList(); + } + + public List findByIds(Collection ids) + { + return getEntityManager() + .createQuery("FROM UserEntity WHERE id IN :ids", UserEntity.class) + .setParameter("ids", ids) + .getResultList(); } } 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 02ae9b0..4ab3f6e 100644 --- a/src/main/java/tech/illuin/wombat/security/user/UserService.java +++ b/src/main/java/tech/illuin/wombat/security/user/UserService.java @@ -32,8 +32,8 @@ public UserEntity record(Caller caller) user.email = caller.email(); user.roles = caller.roles().isEmpty() ? EnumSet.noneOf(Role.class) : EnumSet.copyOf(caller.roles()); user.lastSeenAt = now(); - if (!user.isPersistent()) - user.persist(); + if (!this.users.isPersistent(user)) + this.users.persist(user); return user; } @@ -45,12 +45,12 @@ public UserEntity record(Caller caller) public UserEntity ensure(Caller caller) { UserEntity user = this.findOrNew(caller); - if (!user.isPersistent()) + if (!this.users.isPersistent(user)) { user.name = caller.name(); user.email = caller.email(); user.roles = caller.roles().isEmpty() ? EnumSet.noneOf(Role.class) : EnumSet.copyOf(caller.roles()); - user.persist(); + this.users.persist(user); } return user; } diff --git a/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory b/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory index b4dbb6f..f712b8b 100644 --- a/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory +++ b/src/main/resources/META-INF/services/io.smallrye.config.ConfigSourceFactory @@ -1,2 +1,3 @@ tech.illuin.wombat.commons.NodeModeConfigSourceFactory tech.illuin.wombat.feature.FeatureConfigSourceFactory +tech.illuin.wombat.persistence.PersistenceBackendConfigSourceFactory diff --git a/src/main/resources/application.yaml b/src/main/resources/application.yaml index 2a67b34..3114fa0 100644 --- a/src/main/resources/application.yaml +++ b/src/main/resources/application.yaml @@ -49,19 +49,20 @@ quarkus: swagger-ui: path: /api/swagger always-include: true - - # Database configuration is handled dynamically by PersistenceBackendConfigSourceFactory - # based on persistence.backend.mode. The values below are build-time defaults only - # and are overridden at runtime with priority Integer.MAX_VALUE - 1000. + # Named datasources for runtime backend switching. They are explicitly declared so Quarkus compiles the correct JDBC drivers and dialects. + # At runtime, PersistenceBackendConfigSourceFactory picks the backend based on persistence.backend.mode ; only the active backend is then instantiated. datasource: - db-kind: sqlite - jdbc: - url: "jdbc:sqlite::memory:" - hibernate-orm: - schema-management: - strategy: none + sqlite: + active: false + db-kind: sqlite + postgresql: + active: false + db-kind: postgresql flyway: - locations: classpath:db/migration/sqlite + sqlite: + locations: classpath:db/migration/sqlite + postgresql: + locations: classpath:db/migration/postgresql scheduler: enabled: true kubernetes-client: @@ -136,9 +137,9 @@ wombat: path: "extensions" ## Secret Resolution Configuration - # Write mode defaults to DISABLED; DATABASE is selected at startup and requires a restart to change. - # Supply KEKs through external configuration (e.g. environment-variable - # interpolation); each value must be Base64 for a 32-byte AES key. Never commit actual KEK material. + # Write mode defaults to "disabled". + # Supply KEKs through external configuration (e.g. environment-variable interpolation); each value must be Base64 for a 32-byte AES key. + # Never commit actual KEK material. #secret: # write-mode: database # directory: diff --git a/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java b/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java index 5477631..110daa6 100644 --- a/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java +++ b/src/test/java/tech/illuin/wombat/distributed/DistributedSetupTest.java @@ -141,8 +141,8 @@ void workers_pushTheirWindowsToTheAggregator_whichSavesThemAtTheWorkersInstant() AssetIdentity westLlm = AssetIdentity.of("llm", "west", "LLM", LLM_TYPE); List assetIds = List.of("east.cluster", "east.llm", "west.cluster", "west.llm"); QuarkusTransaction.requiringNew().run(() -> { - this.kubernetesMetrics.delete("assetId in ?1", assetIds); - this.llmMetrics.delete("assetId in ?1", assetIds); + this.kubernetesMetrics.deleteByAssetIds(assetIds); + this.llmMetrics.deleteByAssetIds(assetIds); }); /* Several source heartbeats within one window on each worker. */ @@ -289,7 +289,7 @@ private static LLMPrometheusAsset prometheus(String environment, String id, Stri private void assertSaved(AssetIdentity asset, String type, long instantMs, double cpu, double ram) { - List rows = this.kubernetesMetrics.list("assetId", asset.id()); + List rows = this.kubernetesMetrics.listByAssetId(asset.id()); assertEquals(1, rows.size(), asset.id()); KubernetesMetricEntity row = rows.getFirst(); assertEquals(asset, row.identity()); @@ -302,7 +302,7 @@ private void assertSaved(AssetIdentity asset, String type, long instantMs, doubl private void assertSaved(AssetIdentity asset, String type, long instantMs, long outputTokens) { - List rows = this.llmMetrics.list("assetId", asset.id()); + List rows = this.llmMetrics.listByAssetId(asset.id()); assertEquals(1, rows.size(), asset.id()); LLMMetricEntity row = rows.getFirst(); assertEquals(asset, row.identity()); diff --git a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerDisabledModuleTest.java b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerDisabledModuleTest.java index dd46f28..6ec7ef8 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerDisabledModuleTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerDisabledModuleTest.java @@ -30,8 +30,8 @@ class MetricControllerDisabledModuleTest void setUp() { QuarkusTransaction.requiringNew().run(() -> { - this.kubernetes.delete("assetId", "east.pushed-cluster"); - this.llm.delete("assetId", "east.pushed-llm"); + this.kubernetes.deleteByAssetId("east.pushed-cluster"); + this.llm.deleteByAssetId("east.pushed-llm"); }); } @@ -55,7 +55,7 @@ void push_skipsTheMetricsOfADisabledModule_reportsThemInTheStatus_andSavesTheOth .body("status.metadata.errors[0].reason", is("No active module for asset type tech.illuin.wombat-module.kubernetes-api")) .body("status.metadata.errors[0].count", is(2)); - assertEquals(0, this.kubernetes.count("assetId", "east.pushed-cluster")); - assertEquals(1, this.llm.count("assetId", "east.pushed-llm")); + assertEquals(0, this.kubernetes.countByAssetId("east.pushed-cluster")); + assertEquals(1, this.llm.countByAssetId("east.pushed-llm")); } } diff --git a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java index ca70f25..11ad63e 100644 --- a/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java +++ b/src/test/java/tech/illuin/wombat/endpoint/MetricControllerTest.java @@ -33,7 +33,7 @@ class MetricControllerTest @BeforeEach void setUp() { - QuarkusTransaction.requiringNew().run(() -> this.llm.delete("assetId in ?1", List.of("east.pushed-llm", "east.a"))); + QuarkusTransaction.requiringNew().run(() -> this.llm.deleteByAssetIds(List.of("east.pushed-llm", "east.a"))); } @Test @@ -61,7 +61,7 @@ void push_savesEverySample_atTheStartOfTheWorkersWindow() .body("status.message", is("Success")) .body("status.metadata.errors", nullValue()); - List rows = this.llm.list("assetId", "east.pushed-llm"); + List rows = this.llm.listByAssetId("east.pushed-llm"); assertEquals(2, rows.size()); assertTrue(rows.stream().allMatch(row -> row.instantMs == WORKER_INSTANT_MS)); assertEquals(30L, rows.stream().mapToLong(row -> row.outputTokens).sum()); @@ -86,8 +86,8 @@ void push_skipsAnUnknownAssetType_reportsItInTheStatus_andSavesTheOthers() .body("status.metadata.errors[0].reason", is("No active module for asset type unknown.type")) .body("status.metadata.errors[0].count", is(1)); - assertEquals(0, this.llm.count("assetId", "east.a")); - assertEquals(1, this.llm.count("assetId", "east.pushed-llm")); + assertEquals(0, this.llm.countByAssetId("east.a")); + assertEquals(1, this.llm.countByAssetId("east.pushed-llm")); } @Test 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 78baf6d..cdcfa4a 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/EnvironmentReconcilerTest.java @@ -88,7 +88,7 @@ void undeletesReturningAsset_withCreateHistory() void softDeletesAssetAbsentFromYaml_withDeleteHistory() { AssetEntity orphan = AssetEntity.from("e1", k8s("gone", Lifetime.ofYears(5))); - when(this.assets.list("deletedAt is null")).thenReturn(List.of(orphan)); + when(this.assets.findActive()).thenReturn(List.of(orphan)); this.reconcile(desired("e1", "Env 1")); // env kept, but no assets -> "gone" must be removed @@ -109,7 +109,7 @@ void softDeletesUnrecognizedAssetAbsentFromYaml_withDeleteHistory() orphan.type = "tech.illuin.unknown"; orphan.properties = unrecognized; - when(this.assets.list("deletedAt is null")).thenReturn(List.of(orphan)); + when(this.assets.findActive()).thenReturn(List.of(orphan)); this.reconcile(desired("e1", "Env 1")); @@ -207,7 +207,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.list("deletedAt is null")).thenReturn(List.of(local, mine, theirs)); + when(this.assets.findActive()).thenReturn(List.of(local, mine, theirs)); this.reconciler().reconcile("east", Map.of()); @@ -222,7 +222,7 @@ 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.list("deletedAt is null")).thenReturn(List.of(pushed)); + when(this.assets.findActive()).thenReturn(List.of(pushed)); when(this.environments.findActive()).thenReturn(List.of(pushedEnvironment)); this.reconcile(desired("e1", "Env 1")); @@ -251,7 +251,7 @@ void worker_disablesTheEnvironmentItEmptied_unlessTheYamlDeclaresIt() pushedEnvironment.id = "pushed-env"; EnvironmentEntity yamlEnvironment = new EnvironmentEntity(); yamlEnvironment.id = "e1"; - when(this.assets.list("deletedAt is null")).thenReturn(List.of(gone, alsoGone)); + 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"))) 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 index 12c39ba..04fe9db 100644 --- a/src/test/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepositoryTest.java +++ b/src/test/java/tech/illuin/wombat/engine/context/persistence/EnvironmentRepositoryTest.java @@ -28,7 +28,11 @@ class EnvironmentRepositoryTest @AfterEach void clean() { - QuarkusTransaction.requiringNew().run(() -> this.repository.delete("id in ?1", List.of("env-prod", "env-staging"))); + QuarkusTransaction.requiringNew().run(() -> { + for (EnvironmentEntity e : this.repository.listAll()) + if (List.of("env-prod", "env-staging").contains(e.id)) + this.repository.delete(e); + }); } @Test @@ -41,7 +45,7 @@ void persistSetsTimestampsAndRoundTrips() this.repository.persist(entity); }); - EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("env-prod")); + EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-prod").orElse(null)); assertNotNull(found); assertNotNull(found.uuid); assertEquals("Production", found.name); @@ -60,14 +64,14 @@ void updateBumpsUpdatedAtAndDisableIsRecorded() this.repository.persist(entity); }); - Instant createdAt = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("env-staging")).createdAt; + Instant createdAt = QuarkusTransaction.requiringNew().call(() -> this.repository.findByIdOptional("env-staging").orElse(null)).createdAt; QuarkusTransaction.requiringNew().run(() -> { - EnvironmentEntity entity = this.repository.findById("env-staging"); + EnvironmentEntity entity = this.repository.findByIdOptional("env-staging").orElse(null); entity.disabledAt = Instant.now(); }); - EnvironmentEntity found = QuarkusTransaction.requiringNew().call(() -> this.repository.findById("env-staging")); + 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/impact/llm/LLMModelMetricRepositoryTest.java b/src/test/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepositoryTest.java index fb5bac0..2a9b5d5 100644 --- a/src/test/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepositoryTest.java +++ b/src/test/java/tech/illuin/wombat/engine/impact/llm/LLMModelMetricRepositoryTest.java @@ -44,7 +44,7 @@ void save_persistsEntityWithLLMData() { repository.save(row(1000L, "p-llm", "mistral-large-latest", 42L)); - LLMMetricEntity persisted = repository.findAll().firstResult(); + LLMMetricEntity persisted = repository.listAll().get(0); assertEquals(new LLMData("mistral-large-latest", LLMProvider.mistralai, "mistral-large-latest", FRANCE, 42L, 1L), persisted.data); assertEquals(42L, persisted.outputTokens); assertEquals(1L, persisted.requestCount); @@ -134,7 +134,7 @@ void compactBucket_foldsTheWindowIntoOneRowPerModel() assertEquals(30L, servedTokens("p-llm")); assertEquals(5L, servedTokens("other")); - List all = repository.findAll().list(); + List all = repository.listAll(); assertEquals(2, all.size(), "the sampling rows should be gone"); assertTrue(all.stream().allMatch(row -> row.compacted)); assertTrue(all.stream().allMatch(row -> row.instantMs == 0L)); @@ -162,7 +162,7 @@ void compactBucket_foldsDifferentModelsIntoSeparateRows() int rows = repository.compactBucket(0L, HOUR_MS); assertEquals(2, rows); - List all = repository.findAll().list(); + List all = repository.listAll(); assertEquals(2, all.size()); LLMMetricEntity mistral = all.stream().filter(r -> "mistral".equals(r.data.model())).findFirst().orElseThrow(); @@ -188,7 +188,7 @@ void compactBucket_mergesASampleThatArrivesAfterTheWindowWasFolded() repository.save(sampled(2000L, "p-llm", "m", 15L, 1L)); assertEquals(1, repository.compactBucket(0L, HOUR_MS)); - List folded = repository.findAll().list(); + List folded = repository.listAll(); assertEquals(1, folded.size(), "one row for the hour, not two"); LLMMetricEntity entity = folded.getFirst(); assertEquals(45L, entity.outputTokens); @@ -206,7 +206,7 @@ void compactBucket_leavesTheOtherWindowsAlone() repository.compactBucket(0L, HOUR_MS); - List all = repository.findAll().list(); + List all = repository.listAll(); assertEquals(2, all.size()); LLMMetricEntity firstHour = all.stream().filter(r -> r.instantMs == 0L).findFirst().orElseThrow(); @@ -228,7 +228,7 @@ void compactBucket_isIdempotent() assertEquals(0, repository.compactBucket(0L, HOUR_MS)); assertEquals(10L, servedTokens("p-llm")); - assertEquals(1, repository.findAll().list().size()); + assertEquals(1, repository.listAll().size()); } @Test diff --git a/src/test/java/tech/illuin/wombat/engine/secret/database/crypto/RestoredSecretStartupTest.java b/src/test/java/tech/illuin/wombat/engine/secret/database/crypto/RestoredSecretStartupTest.java index efbda92..824071c 100644 --- a/src/test/java/tech/illuin/wombat/engine/secret/database/crypto/RestoredSecretStartupTest.java +++ b/src/test/java/tech/illuin/wombat/engine/secret/database/crypto/RestoredSecretStartupTest.java @@ -63,8 +63,7 @@ public static class RestoredDatabaseResource implements QuarkusTestResourceLifec @Override public Map start() { - try - { + try { this.directory = Files.createTempDirectory(Path.of("target"), "secret-restore-"); this.backup = this.directory.resolve("backup.db"); this.target = this.directory.resolve("restored.db").toAbsolutePath(); @@ -83,12 +82,10 @@ public Map start() } return Map.ofEntries( - Map.entry("persistence.backend.sqlite.jdbc-url", "jdbc:sqlite:" + this.target), - Map.entry("quarkus.datasource.jdbc.url", "jdbc:sqlite:" + this.target), - Map.entry("quarkus.flyway.clean-at-start", "false"), - Map.entry("quarkus.flyway.migrate-at-start", "false"), Map.entry("quarkus.scheduler.enabled", "true"), Map.entry("wombat.monitor.environments-file", "src/test/resources/monitored-restored-secret.yaml"), + Map.entry("persistence.backend.mode", "sqlite"), + Map.entry("persistence.backend.sqlite.jdbc-url", "jdbc:sqlite:" + this.target), Map.entry("persistence.backend.sqlite.backup.enabled", "true"), Map.entry("persistence.backend.sqlite.backup.restore-on-startup", "true"), Map.entry("persistence.backend.sqlite.backup.cleanup.enabled", "false"), @@ -98,13 +95,12 @@ public Map start() Map.entry("persistence.backend.sqlite.backup.s3.key-prefix", "restored/"), Map.entry("persistence.backend.sqlite.backup.s3.access-key", this.localstack.getAccessKey()), Map.entry("persistence.backend.sqlite.backup.s3.secret-key", this.localstack.getSecretKey()), - Map.entry("wombat.secret.write-mode", "DATABASE"), + Map.entry("wombat.secret.write-mode", "database"), Map.entry("wombat.secret.database.active-kek-id", "test"), Map.entry("wombat.secret.database.kek.test", TEST_KEK) ); } - catch (Exception e) - { + catch (Exception e) { stop(); throw new IllegalStateException("Could not prepare restored secret startup test", e); } @@ -115,8 +111,7 @@ public void stop() { if (this.localstack != null) this.localstack.stop(); - try - { + try { if (this.target != null) { Files.deleteIfExists(Path.of(this.target + "-wal")); @@ -128,8 +123,7 @@ public void stop() if (this.directory != null) Files.deleteIfExists(this.directory); } - catch (Exception e) - { + catch (Exception e) { throw new IllegalStateException("Could not clean up restored secret startup test", e); } } diff --git a/src/test/java/tech/illuin/wombat/persistence/backend/push/PushBackendTest.java b/src/test/java/tech/illuin/wombat/persistence/backend/push/PushBackendTest.java index 615ccaa..49e9eb4 100644 --- a/src/test/java/tech/illuin/wombat/persistence/backend/push/PushBackendTest.java +++ b/src/test/java/tech/illuin/wombat/persistence/backend/push/PushBackendTest.java @@ -45,11 +45,11 @@ void pushedSamples_areSavedOnTheAggregator() PushMetricStore store = new PushMetricStore<>(client, "east", this.mapper); AssetIdentity asset = AssetIdentity.of("pushed-cluster", "remote", "Pushed Cluster", "tech.illuin.wombat-module.kubernetes-api"); AssetIdentity saved = AssetIdentity.of("east.pushed-cluster", "remote", "Pushed Cluster", "tech.illuin.wombat-module.kubernetes-api"); - QuarkusTransaction.requiringNew().run(() -> this.kubernetesMetrics.delete("assetId", saved.id())); + QuarkusTransaction.requiringNew().run(() -> this.kubernetesMetrics.deleteByAssetId(saved.id())); store.save(List.of(MetricSample.of(asset, 1_700_000_100_000L, 300_000L, new KubernetesData("api", "cluster", "ns", "pod", 250.0, 4096.0)))); - List rows = this.kubernetesMetrics.list("assetId", saved.id()); + List rows = this.kubernetesMetrics.listByAssetId(saved.id()); assertEquals(1, rows.size()); assertEquals(saved, rows.getFirst().identity()); assertEquals(1_700_000_100_000L, rows.getFirst().instantMs); diff --git a/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupProducerTest.java b/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupProducerTest.java index 15da672..21f625f 100644 --- a/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupProducerTest.java +++ b/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupProducerTest.java @@ -1,8 +1,10 @@ package tech.illuin.wombat.persistence.backend.sqlite; import io.agroal.api.AgroalDataSource; +import io.quarkus.agroal.DataSource; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; +import jakarta.inject.Named; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -40,7 +42,7 @@ class SQLiteBackupProducerTest private static LocalStackContainer localstack; - @Inject AgroalDataSource dataSource; + @Inject @DataSource("sqlite") AgroalDataSource dataSource; @BeforeAll static void startLocalStack() diff --git a/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupRestorerTest.java b/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupRestorerTest.java index a8d72d3..67c05c2 100644 --- a/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupRestorerTest.java +++ b/src/test/java/tech/illuin/wombat/persistence/backend/sqlite/SQLiteBackupRestorerTest.java @@ -1,6 +1,7 @@ package tech.illuin.wombat.persistence.backend.sqlite; import io.agroal.api.AgroalDataSource; +import io.quarkus.agroal.DataSource; import io.quarkus.test.junit.QuarkusTest; import jakarta.inject.Inject; import org.junit.jupiter.api.AfterAll; @@ -48,7 +49,7 @@ class SQLiteBackupRestorerTest private static LocalStackContainer localstack; - @Inject AgroalDataSource dataSource; + @Inject @DataSource("sqlite") AgroalDataSource dataSource; @BeforeAll static void startLocalStack() diff --git a/src/test/java/tech/illuin/wombat/persistence/compaction/MetricCompactorTest.java b/src/test/java/tech/illuin/wombat/persistence/compaction/MetricCompactorTest.java index 175152b..34e8c42 100644 --- a/src/test/java/tech/illuin/wombat/persistence/compaction/MetricCompactorTest.java +++ b/src/test/java/tech/illuin/wombat/persistence/compaction/MetricCompactorTest.java @@ -119,7 +119,7 @@ void compact_foldsModelRowsToo() assertEquals(1, report.modelRows()); assertEquals(30L, servedTokens()); - LLMMetricEntity compacted = llmRepository.findAll().firstResult(); + LLMMetricEntity compacted = llmRepository.listAll().get(0); assertEquals(30L, compacted.outputTokens); assertEquals(5L, compacted.requestCount); assertEquals(5L, compacted.data.requests()); diff --git a/src/test/resources/application.yaml b/src/test/resources/application.yaml index bd056dc..8810e68 100644 --- a/src/test/resources/application.yaml +++ b/src/test/resources/application.yaml @@ -4,16 +4,6 @@ quarkus: uri: "http://localhost:0/boavizta" ecologits-api-url: uri: "http://localhost:0/ecologits" - # Database configuration is handled dynamically by PersistenceBackendConfigSourceFactory - # based on persistence.backend.mode. The values below are build-time defaults only - # and are overridden at runtime with priority Integer.MAX_VALUE - 1000. - datasource: - db-kind: sqlite - hibernate-orm: - schema-management: - strategy: none - flyway: - locations: classpath:db/migration/sqlite scheduler: enabled: false devservices: @@ -36,7 +26,7 @@ persistence: backend: mode: sqlite sqlite: - jdbc-url: "jdbc:sqlite:target/wombat-test.db" + jdbc-url: "jdbc:sqlite::memory:" backup: enabled: false s3: