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