base version

This commit is contained in:
2026-05-15 00:09:01 +02:00
commit b3a856e397
96 changed files with 9833 additions and 0 deletions
@@ -0,0 +1,25 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* On a {@code @SubgraphType} field: specifies the Gremlin {@code as()} alias
* that this field is bound to when assembling from a {@code select()} result.
*
* <p>When omitted, the field name itself is used as the alias key.
*
* <pre>{@code
* @Alias("dept")
* Department department; // bound to .as("dept") in the Gremlin query
* }</pre>
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Alias {
/** Gremlin {@code as()} alias to bind from. */
String value();
}
@@ -0,0 +1,30 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a {@link com.binarygolem.clotho.repository.ClothoRepository} subclass as a
* Clotho-managed repository bean.
*
* <p>The {@code clotho-spring-boot-starter} scans for classes bearing this annotation
* and registers them as Spring beans, injecting the shared {@code ClothoSessionFactory}.
*
* <pre>{@code
* @ClothoRepository
* public class EmployeeRepo extends ClothoRepository<Employee> {
*
* public EmployeeRepo(ClothoSessionFactory factory) { super(factory); }
*
* public List<Employee> findByDept(String dept) {
* return execute(g().V().has("Employee", "dept", dept));
* }
* }
* }</pre>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ClothoRepository {
}
@@ -0,0 +1,29 @@
package com.binarygolem.clotho.annotation;
import com.binarygolem.clotho.model.TraversalDirection;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies the edge traversal direction for an {@link Include} + {@link Via} field.
*
* <p>When omitted, the direction defaults to {@link TraversalDirection#OUT} or the
* global default configured in {@code ClothoSessionFactory}.
*
* <pre>{@code
* @Include @Via("ASSIGNED_TO") @Direction(IN)
* List<Task> assignedTasks;
*
* @Include @Via("CONNECTED") @Direction(BOTH)
* List<Node> neighbors;
* }</pre>
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Direction {
TraversalDirection value() default TraversalDirection.OUT;
}
@@ -0,0 +1,23 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declares a {@link com.binarygolem.clotho.model.ClothoEdge} subclass as a
* Clotho-managed edge type. The annotated class is registered in the
* {@code TypeRegistry} under the given ArcadeDB edge type name.
*
* <p>Convention: define a {@code public static final String LABEL = "..."}
* constant on the edge class to allow call sites to reference the label without
* using a magic string literal.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EdgeType {
/** ArcadeDB edge type name — must match the schema exactly (case-sensitive). */
String value();
}
@@ -0,0 +1,19 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* On an {@code @EdgeType} class: marks the field holding the in-vertex (target)
* of the edge. The field type must be a {@code @VertexType} class.
*
* <p>Omitting this annotation entirely on an edge class enables
* <em>edge-only inclusion</em>: the edge and its properties are loaded but
* the target vertex is never fetched from the database.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InVertex {
}
@@ -0,0 +1,36 @@
package com.binarygolem.clotho.annotation;
import com.binarygolem.clotho.model.FetchType;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a field as part of this object's load boundary.
*
* <p>Must always be paired with {@link Via}. The field type determines what is loaded:
* <ul>
* <li>A {@code @VertexType} class or {@code List<@VertexType>}: the edge is traversed
* and the target vertex (and its own boundary) is loaded. Edge properties are
* not accessible.</li>
* <li>An {@code @EdgeType} class or {@code List<@EdgeType>}: the edge and its
* properties are loaded. The target vertex is loaded only if the edge class
* declares an {@link InVertex} field.</li>
* </ul>
*
* <p>Inclusion is recursive: if a loaded vertex also declares {@code @Include} fields,
* those are loaded as part of the same operation (cycle detection prevents infinite loops).
* The developer is responsible for designing boundaries that do not load unbounded
* portions of the graph.
*
* <p>Set {@link #fetchType()} to {@link FetchType#LAZY} to skip this field during
* {@code SubgraphLoader.populate()}. Lazy fields remain {@code null} / empty until the
* developer calls {@code session.loadField(vertex, "fieldName")} explicitly.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Include {
FetchType fetchType() default FetchType.EAGER;
}
@@ -0,0 +1,15 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* On an {@code @EdgeType} class: marks the field holding the out-vertex (source)
* of the edge. The field type must be a {@code @VertexType} class.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OutVertex {
}
@@ -0,0 +1,25 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Maps a field to an ArcadeDB vertex or edge property by name.
*
* <p>Optional when the Java field name exactly matches the ArcadeDB property name.
* Required when names differ.
*
* <pre>{@code
* @Property("startDate") LocalDate start; // names differ — annotation required
* LocalDate endDate; // names match — annotation optional
* }</pre>
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
/** ArcadeDB property name (case-sensitive). */
String value();
}
@@ -0,0 +1,21 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marks a field as the ArcadeDB record ID ({@link com.binarygolem.clotho.model.ARID}).
*
* <p>With the base-class approach ({@code ClothoVertex} / {@code ClothoEdge}),
* the {@code id} field inherited from {@code ClothoEntity} is used automatically
* and this annotation is typically not needed on subclass fields.
*
* <p>Use this annotation if you need a differently-named ID field or are
* building a type that does not extend the standard base classes.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RID {
}
@@ -0,0 +1,28 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declares a composite type assembled from a Gremlin {@code select()} traversal.
*
* <p>A {@code @SubgraphType} class:
* <ul>
* <li>Does NOT extend {@link com.binarygolem.clotho.model.ClothoVertex} or
* {@link com.binarygolem.clotho.model.ClothoEdge} — it holds them as fields.</li>
* <li>Has no ArcadeDB record ID of its own.</li>
* <li>Is assembled by {@code SubgraphTypeAssembler} from a {@code @Query} result
* whose Gremlin traversal uses {@code select()} with named aliases.</li>
* <li>Saving it via {@code session.save()} delegates to all contained
* {@link com.binarygolem.clotho.model.ClothoEntity} fields individually.</li>
* </ul>
*
* <p>Fields are bound by matching the field name (or {@code @Alias} value) to
* the corresponding key in the Gremlin {@code select()} map.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubgraphType {
}
@@ -0,0 +1,27 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Enables application-managed optimistic locking on a vertex or edge class.
*
* <p>Declare one {@code @Version Long version} field on a {@link
* com.binarygolem.clotho.model.ClothoVertex} or {@link
* com.binarygolem.clotho.model.ClothoEdge} subclass. Clotho manages the counter
* entirely: it is initialised to {@code 0} on create, read as a regular property
* on load, and atomically checked-and-incremented on every update. A version mismatch
* throws {@link com.binarygolem.clotho.exception.OptimisticLockException}.
*
* <p>The {@link #value()} attribute is the graph property name used to store the
* counter. It must be a regular user-defined property — ArcadeDB's internal system
* properties (those prefixed with {@code @}) are not accessible via the Gremlin
* WebSocket interface.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Version {
String value() default "_version";
}
@@ -0,0 +1,37 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Declares a {@link com.binarygolem.clotho.model.ClothoVertex} subclass as a
* Clotho-managed vertex type. The annotated class is registered in the
* {@code TypeRegistry} under the given ArcadeDB type name.
*
* <p>For ArcadeDB's multi-parent (diamond) inheritance, list additional parent
* type names in {@link #additionalParents()}. The Java class hierarchy covers
* the primary parent; the annotation covers the rest.
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface VertexType {
/** ArcadeDB vertex type name — must match the schema exactly (case-sensitive). */
String value();
/**
* Additional ArcadeDB parent type names beyond the Java class hierarchy.
* Use when ArcadeDB has multi-parent inheritance that Java cannot represent
* with a single {@code extends} clause.
*/
String[] additionalParents() default {};
/**
* Explicit ArcadeDB parent type name for cases where the Java class does
* not extend the corresponding Clotho parent class.
* Takes precedence over Java hierarchy inference when set.
*/
String parentLabel() default "";
}
@@ -0,0 +1,27 @@
package com.binarygolem.clotho.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies the ArcadeDB edge label to traverse for an {@link Include} field.
* Required whenever {@code @Include} is used.
*
* <p>To avoid magic string literals, prefer referencing the {@code LABEL} constant
* defined on the edge class:
* <pre>{@code
* @Include @Via(WorksAt.LABEL)
* List<WorksAt> workHistory;
* }</pre>
*
* @see Direction for controlling traversal direction (default: OUT)
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Via {
/** Edge label to traverse (case-sensitive). */
String value();
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.annotation;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,18 @@
package com.binarygolem.clotho.exception;
/**
* Thrown when Clotho detects a misconfiguration at startup or at the point
* where a misconfigured type is first used — e.g., a class annotated with
* {@code @VertexType} that does not extend {@code ClothoVertex}, or a field
* annotated with {@code @Include} that is missing {@code @Via}.
*/
public class ClothoConfigurationException extends ClothoException {
public ClothoConfigurationException(String message) {
super(message);
}
public ClothoConfigurationException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package com.binarygolem.clotho.exception;
/** Base unchecked exception for all Clotho runtime errors. */
public class ClothoException extends RuntimeException {
public ClothoException(String message) {
super(message);
}
public ClothoException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,23 @@
package com.binarygolem.clotho.exception;
import com.binarygolem.clotho.model.ARID;
import lombok.Getter;
/**
* Thrown when an update is rejected because the entity's {@code @Version} value no
* longer matches the graph's current version — i.e., another writer has modified
* the record since it was loaded.
*/
@Getter
public class OptimisticLockException extends ClothoException {
private final ARID id;
private final long expectedVersion;
public OptimisticLockException(ARID id, long expectedVersion) {
super("Optimistic lock failure for " + id + " at version " + expectedVersion
+ " — record was modified by another writer");
this.id = id;
this.expectedVersion = expectedVersion;
}
}
@@ -0,0 +1,22 @@
package com.binarygolem.clotho.exception;
/**
* Thrown when a Gremlin result carries a vertex or edge label that has no
* registered Clotho Java class, and the configured
* {@link com.binarygolem.clotho.model.UnknownTypeBehavior} is
* {@code STRICT}.
*/
public class UnknownTypeException extends ClothoException {
private final String label;
public UnknownTypeException(String label) {
super("No Clotho type registered for label: '" + label + "'");
this.label = label;
}
/** The unrecognised ArcadeDB type label. */
public String getLabel() {
return label;
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.exception;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,180 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Version;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.Field;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;
/**
* Maps TinkerPop {@link Vertex} and {@link Edge} instances to their most-specific
* registered Clotho Java class using the {@link TypeRegistry}.
*
* <p>Field metadata is read from {@link FieldMetadataCache} — reflection is performed
* once per class and reused on every subsequent mapping call.
*
* <p>Fields annotated with {@code @Property} are mapped by the annotation value.
* Fields with no framework annotation and a simple (scalar) type are mapped by
* field name. {@code @Version} fields are mapped using their declared property name
* (default {@code "_version"}). Fields annotated with {@code @Include},
* {@code @OutVertex}, or {@code @InVertex} are skipped — they are handled by
* {@code SubgraphLoader}.
*/
public final class ElementMapper {
private static final Logger log = Logger.getLogger(ElementMapper.class.getName());
private final TypeRegistry registry;
private final UnknownTypeBehavior unknownTypeBehavior;
public ElementMapper(TypeRegistry registry, UnknownTypeBehavior unknownTypeBehavior) {
this.registry = registry;
this.unknownTypeBehavior = unknownTypeBehavior;
}
public ClothoVertex mapVertex(Vertex vertex) {
Class<? extends ClothoVertex> targetClass =
registry.resolveVertex(vertex.label(), unknownTypeBehavior);
ClothoVertex instance = instantiate(targetClass);
populate(vertex, instance);
return instance;
}
public ClothoEdge mapEdge(Edge edge) {
Class<? extends ClothoEdge> targetClass =
registry.resolveEdge(edge.label(), unknownTypeBehavior);
ClothoEdge instance = instantiate(targetClass);
populate(edge, instance);
instance.setOutVertexId(ARID.of(edge.outVertex().id().toString()));
instance.setInVertexId(ARID.of(edge.inVertex().id().toString()));
return instance;
}
private static void populate(Element element, ClothoEntity instance) {
instance.setId(ARID.of(element.id().toString()));
FieldMetadataCache.ClassMetadata meta = FieldMetadataCache.get(instance.getClass());
Set<String> mappedKeys = new HashSet<>();
// Map @Property and auto-mapped scalar fields
for (Field field : meta.propertyFields()) {
String propName = meta.fieldToPropertyName().get(field.getName());
if (propName == null) continue;
Object raw = readProperty(element, propName);
if (raw == null) continue;
mappedKeys.add(propName);
setField(field, instance, coerce(raw, field.getType()));
}
// Map @Version field
Field versionField = meta.versionField();
if (versionField != null) {
String propName = versionField.getAnnotation(Version.class).value();
Object raw = readProperty(element, propName);
if (raw != null) {
mappedKeys.add(propName);
setField(versionField, instance, coerce(raw, versionField.getType()));
}
}
// Store any remaining unmapped properties as raw
element.properties().forEachRemaining(p -> {
if (!mappedKeys.contains(p.key())) {
instance.setRawProperty(p.key(), p.value());
}
});
}
// --- Coercion ---
@Nullable
static Object coerce(@Nullable Object value, Class<?> target) {
if (value == null) return null;
if (target.isInstance(value)) return value;
if (target == String.class) return value.toString();
if (value instanceof Number num) {
if (target == int.class || target == Integer.class) return num.intValue();
if (target == long.class || target == Long.class) return num.longValue();
if (target == double.class || target == Double.class) return num.doubleValue();
if (target == float.class || target == Float.class) return num.floatValue();
if (target == short.class || target == Short.class) return num.shortValue();
if (target == byte.class || target == Byte.class) return num.byteValue();
if (target.isEnum()) return ordinalToEnum(target, num.intValue());
if (target == LocalDateTime.class) return Instant.ofEpochMilli(num.longValue()).atZone(ZoneOffset.UTC).toLocalDateTime();
if (target == LocalDate.class) return Instant.ofEpochMilli(num.longValue()).atZone(ZoneOffset.UTC).toLocalDate();
if (target == Instant.class) return Instant.ofEpochMilli(num.longValue());
}
if (value instanceof String str) {
if (target.isEnum()) return nameToEnum(target, str);
if (target == boolean.class || target == Boolean.class) return Boolean.parseBoolean(str);
if (target == LocalDateTime.class) return LocalDateTime.parse(str);
if (target == LocalDate.class) return LocalDate.parse(str);
if (target == Instant.class) return Instant.parse(str);
}
log.warning(() -> "Cannot coerce " + value.getClass().getName()
+ " to " + target.getName() + " — returning value as-is");
return value;
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Object ordinalToEnum(Class<?> target, int ordinal) {
Object[] constants = target.getEnumConstants();
if (ordinal >= 0 && ordinal < constants.length) return constants[ordinal];
log.warning(() -> "Ordinal " + ordinal + " out of range for " + target.getName());
return constants[0];
}
@SuppressWarnings({"unchecked", "rawtypes"})
private static Object nameToEnum(Class<?> target, String name) {
return Enum.valueOf((Class<Enum>) target, name);
}
// --- Reflection helpers ---
@Nullable
private static Object readProperty(Element element, String key) {
var prop = element.property(key);
return prop.isPresent() ? prop.value() : null;
}
private static void setField(Field field, Object instance, @Nullable Object value) {
try {
field.setAccessible(true);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new ClothoConfigurationException(
"Cannot set field '" + field.getName() + "' on " + instance.getClass().getName(), e);
}
}
private static <T> T instantiate(Class<T> clazz) {
try {
var ctor = clazz.getDeclaredConstructor();
ctor.setAccessible(true);
return ctor.newInstance();
} catch (Exception e) {
throw new ClothoConfigurationException(
clazz.getName() + " must have a no-arg constructor for Clotho to instantiate it", e);
}
}
}
@@ -0,0 +1,132 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Include;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.RID;
import com.binarygolem.clotho.annotation.Version;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.FetchType;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Per-class reflection cache for Clotho field metadata.
*
* <p>Reflection is performed once per class and the result stored in a
* {@link ConcurrentHashMap}. All subsequent accesses return the cached
* {@link ClassMetadata} without touching the reflection API.
*
* <p>Call {@link #get(Class)} to retrieve (or compute) the metadata for any class.
*/
public final class FieldMetadataCache {
/**
* Cached metadata for a single Java class.
*
* @param allIncludeFields every {@code @Include} field (eager + lazy), in declaration order
* @param eagerIncludeFields only {@code @Include(fetchType = EAGER)} fields
* @param propertyFields fields that map to graph properties ({@code @Property} or
* auto-mapped scalars); excludes {@code @Include}, {@code @OutVertex},
* {@code @InVertex}, {@code @RID}, {@code @Version}, static, synthetic
* @param edgeVertexFields {@code @OutVertex} and {@code @InVertex} fields (on edge classes)
* @param versionField the {@code @Version}-annotated field, or {@code null}
* @param fieldToPropertyName map from Java field name to graph property name, for all property
* fields plus the version field
*/
public record ClassMetadata(
List<Field> allIncludeFields,
List<Field> eagerIncludeFields,
List<Field> propertyFields,
List<Field> edgeVertexFields,
@Nullable Field versionField,
Map<String, String> fieldToPropertyName
) {}
private static final ConcurrentHashMap<Class<?>, ClassMetadata> cache = new ConcurrentHashMap<>();
public static ClassMetadata get(Class<?> clazz) {
return cache.computeIfAbsent(clazz, FieldMetadataCache::compute);
}
private static ClassMetadata compute(Class<?> clazz) {
List<Field> allIncludes = new ArrayList<>();
List<Field> eagerIncludes = new ArrayList<>();
List<Field> properties = new ArrayList<>();
List<Field> edgeVertices = new ArrayList<>();
Field versionField = null;
Map<String, String> fieldToPropertyName = new LinkedHashMap<>();
Class<?> cursor = clazz;
while (cursor != null && cursor != ClothoEntity.class && cursor != Object.class) {
for (Field f : cursor.getDeclaredFields()) {
if (Modifier.isStatic(f.getModifiers()) || f.isSynthetic()) continue;
if (f.isAnnotationPresent(Include.class)) {
allIncludes.add(f);
if (f.getAnnotation(Include.class).fetchType() == FetchType.EAGER) {
eagerIncludes.add(f);
}
continue;
}
if (f.isAnnotationPresent(OutVertex.class) || f.isAnnotationPresent(InVertex.class)) {
edgeVertices.add(f);
continue;
}
if (f.isAnnotationPresent(RID.class)) continue;
if (f.isAnnotationPresent(Version.class)) {
versionField = f;
String propName = f.getAnnotation(Version.class).value();
fieldToPropertyName.put(f.getName(), propName);
continue;
}
Property propAnnotation = f.getAnnotation(Property.class);
if (propAnnotation != null) {
properties.add(f);
fieldToPropertyName.put(f.getName(), propAnnotation.value());
} else if (isMappableType(f.getType())) {
properties.add(f);
fieldToPropertyName.put(f.getName(), f.getName());
}
}
cursor = cursor.getSuperclass();
}
// Walk parent of ClothoEdge too (ClothoEdge extends ClothoEntity; we stop at ClothoEntity
// but edgeVertexFields live on the concrete edge class, already covered above).
return new ClassMetadata(
Collections.unmodifiableList(allIncludes),
Collections.unmodifiableList(eagerIncludes),
Collections.unmodifiableList(properties),
Collections.unmodifiableList(edgeVertices),
versionField,
Collections.unmodifiableMap(fieldToPropertyName)
);
}
static boolean isMappableType(Class<?> type) {
return type.isPrimitive()
|| type == String.class
|| Number.class.isAssignableFrom(type)
|| type == Boolean.class
|| type == Character.class
|| type.isEnum()
|| java.time.temporal.Temporal.class.isAssignableFrom(type)
|| type == java.util.UUID.class;
}
private FieldMetadataCache() {}
}
@@ -0,0 +1,304 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Direction;
import com.binarygolem.clotho.annotation.Include;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Via;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.EntityState;
import com.binarygolem.clotho.model.TraversalDirection;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Populates {@code @Include} fields on a {@link ClothoVertex} by executing a single
* Gremlin {@code project()} traversal that fetches all eagerly-declared includes
* atomically. This eliminates N+1 queries per boundary and prevents the race
* conditions that arise from sequential round-trips.
*
* <p>For nested boundaries (an included vertex that itself has {@code @Include} fields)
* each vertex is loaded with its own single-project query — one query per vertex,
* not one per field.
*
* <p>Fields declared with {@link com.binarygolem.clotho.model.FetchType#LAZY} are
* skipped during {@link #populate(ClothoVertex)}. Use
* {@link #populateSingleField(ClothoVertex, Field)} to load them on demand.
*
* <p>Cycle detection is performed via a visited-ARID set passed through the recursion.
*/
public final class SubgraphLoader {
private final GraphTraversalSource g;
private final ElementMapper mapper;
private final TraversalDirection defaultDirection;
public SubgraphLoader(GraphTraversalSource g, ElementMapper mapper,
TraversalDirection defaultDirection) {
this.g = g;
this.mapper = mapper;
this.defaultDirection = defaultDirection;
}
// --- Public API ---
/** Populates all EAGER {@code @Include} fields on {@code vertex} and transitively included objects. */
public void populate(ClothoVertex vertex) {
populate(vertex, new HashSet<>());
}
/**
* Populates a single {@code @Include} field on demand (eager or lazy).
* Used by {@link com.binarygolem.clotho.session.ClothoSession#loadField}.
*/
public void populateSingleField(ClothoVertex vertex, Field field) {
populateSingleField(vertex, field, new HashSet<>());
}
/**
* Batch-populates EAGER {@code @Include} fields for a list of vertices.
* Vertices are grouped by class; for each class one batch traversal per
* {@code @Include} field covers all vertex IDs at once.
* This is significantly more efficient than calling {@link #populate} per vertex
* when loading large result sets from {@code findAll()} or {@code execute()}.
*/
public void populateAll(List<? extends ClothoVertex> vertices) {
if (vertices.isEmpty()) return;
Map<Class<?>, List<ClothoVertex>> byClass = new LinkedHashMap<>();
for (ClothoVertex v : vertices) {
byClass.computeIfAbsent(v.getClass(), k -> new ArrayList<>()).add(v);
}
for (Map.Entry<Class<?>, List<ClothoVertex>> entry : byClass.entrySet()) {
populateAllOfClass(entry.getValue());
}
}
// --- Single-vertex population ---
private void populate(ClothoVertex vertex, Set<ARID> visited) {
ARID id = vertex.getId();
if (id == null) return;
if (!visited.add(id)) return;
List<Field> eagerFields = FieldMetadataCache.get(vertex.getClass()).eagerIncludeFields();
if (eagerFields.isEmpty()) return;
Map<String, Object> projected = projectVertex(id.asString(), eagerFields);
if (projected == null) return;
for (Field field : eagerFields) {
applyProjectedField(vertex, field, projected.get(field.getName()), visited);
}
}
// --- Single-field population ---
private void populateSingleField(ClothoVertex vertex, Field field, Set<ARID> visited) {
ARID id = vertex.getId();
if (id == null) return;
Map<String, Object> projected = projectVertex(id.asString(), List.of(field));
if (projected == null) return;
applyProjectedField(vertex, field, projected.get(field.getName()), visited);
}
// --- Batch population ---
@SuppressWarnings("unchecked")
private void populateAllOfClass(List<ClothoVertex> vertices) {
List<Field> eagerFields = FieldMetadataCache.get(vertices.get(0).getClass()).eagerIncludeFields();
if (eagerFields.isEmpty()) return;
Map<String, ClothoVertex> byId = new LinkedHashMap<>();
for (ClothoVertex v : vertices) {
if (v.getId() != null) byId.put(v.getId().asString(), v);
}
if (byId.isEmpty()) return;
Object[] ids = byId.keySet().toArray();
Set<ARID> visited = new HashSet<>();
for (Field field : eagerFields) {
// One batch query per @Include field: group by vertex ID, fold results per vertex
Map<Object, Object> batchResult = (Map<Object, Object>) g.V(ids)
.group()
.by(T.id)
.by(buildByStep(field))
.next();
for (Map.Entry<Object, Object> entry : batchResult.entrySet()) {
String rawId = entry.getKey().toString();
ClothoVertex vertex = byId.get(rawId);
if (vertex == null) continue;
applyProjectedField(vertex, field, entry.getValue(), visited);
}
}
}
// --- Projection ---
@SuppressWarnings("unchecked")
private @Nullable Map<String, Object> projectVertex(String vertexId, List<Field> fields) {
if (fields.isEmpty()) return Map.of();
String[] keys = fields.stream().map(Field::getName).toArray(String[]::new);
var traversal = g.V(vertexId).project(keys[0], Arrays.copyOfRange(keys, 1, keys.length));
for (Field f : fields) {
traversal = traversal.by(buildByStep(f));
}
return (Map<String, Object>) traversal.tryNext().orElse(null);
}
/**
* Builds the Gremlin {@code by()} step for a single {@code @Include} field.
*
* <p>For edge fields the projection includes the edge AND both adjacent full vertices
* ({@code outV()}/{@code inV()} inside {@code project()} return vertices with all
* their properties). This eliminates the separate {@code g.V(id)} call that
* detached-edge traversals previously required.
*/
private GraphTraversal<?, ?> buildByStep(Field field) {
Via via = field.getAnnotation(Via.class);
if (via == null) {
throw new ClothoConfigurationException(
"@Include field '" + field.getName() + "' on "
+ field.getDeclaringClass().getName() + " is missing @Via");
}
String label = via.value();
TraversalDirection direction = resolveDirection(field);
Class<?> elementType = resolveElementType(field);
if (ClothoEdge.class.isAssignableFrom(elementType)) {
return switch (direction) {
case OUT -> __.outE(label).project("edge", "outV", "inV")
.by(__.identity()).by(__.outV()).by(__.inV()).fold();
case IN -> __.inE(label).project("edge", "outV", "inV")
.by(__.identity()).by(__.outV()).by(__.inV()).fold();
case BOTH -> __.bothE(label).project("edge", "outV", "inV")
.by(__.identity()).by(__.outV()).by(__.inV()).fold();
};
} else {
return switch (direction) {
case OUT -> __.out(label).fold();
case IN -> __.in(label).fold();
case BOTH -> __.both(label).fold();
};
}
}
// --- Applying projected results to entity fields ---
@SuppressWarnings("unchecked")
private void applyProjectedField(ClothoVertex root, Field field,
@Nullable Object projected, Set<ARID> visited) {
List<?> items = projected instanceof List<?> l ? l : List.of();
Class<?> elementType = resolveElementType(field);
if (ClothoEdge.class.isAssignableFrom(elementType)) {
List<ClothoEdge> edges = new ArrayList<>();
for (Object item : items) {
edges.add(buildEdgeFromProjection((Map<String, Object>) item, root, visited));
}
setField(field, root, isList(field) ? edges : (edges.isEmpty() ? null : edges.get(0)));
} else {
List<ClothoVertex> loadedVertices = new ArrayList<>();
for (Object item : items) {
ClothoVertex mapped = mapper.mapVertex((Vertex) item);
populate(mapped, visited);
loadedVertices.add(mapped);
}
setField(field, root, isList(field) ? loadedVertices
: (loadedVertices.isEmpty() ? null : loadedVertices.get(0)));
}
}
/**
* Builds a {@link ClothoEdge} from a projection entry
* {@code {"edge": Edge, "outV": Vertex, "inV": Vertex}}.
* Both adjacent vertices are full (not detached) — they come from
* {@code outV()}/{@code inV()} inside the projection step.
*/
private ClothoEdge buildEdgeFromProjection(Map<String, Object> entry,
ClothoVertex root, Set<ARID> visited) {
Edge rawEdge = (Edge) entry.get("edge");
Vertex outVRaw = (Vertex) entry.get("outV");
Vertex inVRaw = (Vertex) entry.get("inV");
ClothoEdge edge = mapper.mapEdge(rawEdge);
edge.setState(EntityState.MANAGED);
edge.clearDirtyFields();
ARID rootId = root.getId();
for (Field evField : FieldMetadataCache.get(edge.getClass()).edgeVertexFields()) {
if (evField.isAnnotationPresent(OutVertex.class)) {
setField(evField, edge, sameOrMap(outVRaw, root, rootId, visited));
} else if (evField.isAnnotationPresent(InVertex.class)) {
setField(evField, edge, sameOrMap(inVRaw, root, rootId, visited));
}
}
return edge;
}
/** Returns {@code root} when the projected vertex is the same instance (by ARID), otherwise maps it. */
private ClothoVertex sameOrMap(Vertex raw, ClothoVertex root,
@Nullable ARID rootId, Set<ARID> visited) {
ARID rawId = ARID.of(raw.id().toString());
if (rawId.equals(rootId)) return root;
ClothoVertex mapped = mapper.mapVertex(raw);
populate(mapped, visited);
return mapped;
}
// --- Field type helpers ---
private TraversalDirection resolveDirection(Field field) {
Direction annotation = field.getAnnotation(Direction.class);
return annotation != null ? annotation.value() : defaultDirection;
}
private static boolean isList(Field field) {
return List.class.isAssignableFrom(field.getType());
}
private static Class<?> resolveElementType(Field field) {
if (!isList(field)) return field.getType();
Type generic = field.getGenericType();
if (generic instanceof ParameterizedType pt) {
Type arg = pt.getActualTypeArguments()[0];
if (arg instanceof Class<?> c) return c;
}
throw new ClothoConfigurationException(
"Cannot determine element type of List field '" + field.getName() + "'");
}
static void setField(Field field, Object instance, @Nullable Object value) {
try {
field.setAccessible(true);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new ClothoConfigurationException(
"Cannot set field '" + field.getName() + "' on "
+ instance.getClass().getName(), e);
}
}
}
@@ -0,0 +1,512 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.exception.OptimisticLockException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.EntityState;
import com.binarygolem.clotho.model.TraversalDirection;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jspecify.annotations.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Persists {@link ClothoVertex}, {@link ClothoEdge}, and {@code @SubgraphType} objects
* to the graph database via Gremlin.
*
* <p>Persistence semantics:
* <ul>
* <li>{@link EntityState#NEW} or ARID {@code null} → create; returned ID is written back.</li>
* <li>{@link EntityState#MANAGED} with dirty fields → update; only dirty fields are written.</li>
* <li>{@link EntityState#MANAGED} with no dirty fields → skip (nothing changed).</li>
* <li>{@code @Version} present → version filter added to update; mismatch throws
* {@link OptimisticLockException}.</li>
* <li>Cascade: after persisting a vertex, all {@code @Include} fields are persisted
* recursively. An identity set prevents double-writes in the same call.</li>
* <li>{@code @SubgraphType}: every {@link ClothoEntity} field is persisted.</li>
* </ul>
*
* <p>Vertices and edges are treated identically — both participate in EntityState
* lifecycle, dirty tracking, and {@code @Version} optimistic locking.
*/
public final class SubgraphPersistor {
private final GraphTraversalSource g;
public SubgraphPersistor(GraphTraversalSource g) {
this.g = g;
}
// --- Public API ---
/** Persists {@code vertex} and cascades through its {@code @Include} boundary. */
public void persist(ClothoVertex vertex) {
persistVertex(vertex, identitySet());
}
/** Persists {@code edge} and its {@code @OutVertex}/{@code @InVertex} fields. */
public void persist(ClothoEdge edge) {
persistEdge(edge, identitySet());
}
/**
* Persists all {@link ClothoEntity} fields (and lists thereof) on a {@code @SubgraphType}.
*
* @throws ClothoConfigurationException if {@code subgraphType} lacks the annotation
*/
public void persist(Object subgraphType) {
if (!subgraphType.getClass().isAnnotationPresent(SubgraphType.class)) {
throw new ClothoConfigurationException(
subgraphType.getClass().getName() + " is not annotated with @SubgraphType");
}
Set<ClothoEntity> visited = identitySet();
for (ClothoEntity entity : collectEntityFields(subgraphType)) {
if (entity instanceof ClothoVertex v) persistVertex(v, visited);
else if (entity instanceof ClothoEdge e) persistEdge(e, visited);
}
}
/**
* Persists all dirty MANAGED entities as two Gremlin round-trips that together provide
* all-or-nothing semantics for {@code @Version} conflicts:
*
* <ol>
* <li><b>Version pre-flight</b> (one request): for every entity that carries a
* {@code @Version} field, verify the expected version is still current. If any
* version has changed, throw {@link OptimisticLockException} immediately — no
* property has been written yet.</li>
* <li><b>Batch update</b> (one request): write every dirty property across all
* entities in a single {@code inject(0).union(...).iterate()} traversal. No
* version filters inside — the pre-flight already guaranteed consistency.</li>
* </ol>
*
* <p>The two-step approach means a narrow TOCTOU window exists between the check and
* the write, but within that window a conflict would simply overwrite with the stale
* value (the same risk as any non-transactional update). Eliminating the window
* entirely requires native ArcadeDB transaction support, which is not available over
* the Gremlin WebSocket interface.
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public void persistAllDirty(Collection<ClothoVertex> dirtyVertices,
Collection<ClothoEdge> dirtyEdges) {
// --- 1. Version pre-flight ---
// Collect version expectations for all dirty @Version entities, then verify them in
// one request. If any version is stale the exception is thrown here — before a single
// property is written — giving true all-or-nothing semantics for version conflicts.
List<VersionedExpectation> versionChecks = new ArrayList<>();
for (ClothoVertex v : dirtyVertices) collectVersionExpectation(v, versionChecks);
for (ClothoEdge e : dirtyEdges) collectVersionExpectation(e, versionChecks);
if (!versionChecks.isEmpty()) {
long matched = (long) unionOf(g.inject(0),
versionChecks.stream().map(VersionedExpectation::freshBranch).toList())
.count().next();
if (matched < versionChecks.size()) {
// At least one version is stale. Re-run with fresh branches (traversals are
// stateful and consumed after execution) to identify the specific conflict.
Set<String> present = new HashSet<>(
(List<String>) (List<?>) unionOf(g.inject(0),
versionChecks.stream().map(VersionedExpectation::freshBranch).toList())
.toList()
);
VersionedExpectation conflict = versionChecks.stream()
.filter(c -> !present.contains(c.id().asString()))
.findFirst().orElseThrow();
throw new OptimisticLockException(conflict.id(), conflict.expectedVersion());
}
}
// --- 2. Batch update (no version filters — pre-flight already passed) ---
// Build a lookup map so buildUpdateBranch can append the version+1 write for each entity.
Map<ARID, VersionedExpectation> versionMap = new HashMap<>();
for (VersionedExpectation ve : versionChecks) versionMap.put(ve.id(), ve);
List<GraphTraversal<?, ?>> updateBranches = new ArrayList<>();
for (ClothoVertex v : dirtyVertices) buildUpdateBranch(v, true, updateBranches, versionMap);
for (ClothoEdge e : dirtyEdges) buildUpdateBranch(e, false, updateBranches, versionMap);
if (!updateBranches.isEmpty()) {
unionOf(g.inject(0), updateBranches).iterate();
}
for (ClothoVertex v : dirtyVertices) { bumpVersionField(v, versionMap); v.clearDirtyFields(); }
for (ClothoEdge e : dirtyEdges) { bumpVersionField(e, versionMap); e.clearDirtyFields(); }
}
/**
* Holds the data needed to verify one entity's expected {@code @Version} value.
* {@link #freshBranch()} produces a new anonymous traversal each time — required
* because Gremlin traversal objects are stateful and consumed after execution.
*/
private record VersionedExpectation(ARID id, long expectedVersion,
String versionProp, boolean isVertex) {
@SuppressWarnings({"unchecked", "rawtypes"})
GraphTraversal<?, ?> freshBranch() {
String idStr = id.asString();
return (GraphTraversal<?, ?>)
(isVertex ? __.V(idStr) : __.E(idStr)).has(versionProp, expectedVersion).constant(idStr);
}
}
/** Wraps raw-type {@code union()} call to avoid unchecked-warning noise at every call site. */
@SuppressWarnings({"unchecked", "rawtypes"})
private static GraphTraversal<?, ?> unionOf(GraphTraversal<?, ?> root,
List<? extends GraphTraversal<?, ?>> branches) {
return root.union(branches.toArray(GraphTraversal[]::new));
}
/** Adds a {@link VersionedExpectation} for {@code entity} if it carries a {@code @Version} field. */
private static void collectVersionExpectation(ClothoEntity entity, List<VersionedExpectation> checks) {
if (entity.getDirtyFields().isEmpty()) return;
Field vf = FieldMetadataCache.get(entity.getClass()).versionField();
if (vf == null) return;
Long ver = (Long) readField(vf, entity);
if (ver == null) return;
String vProp = vf.getAnnotation(com.binarygolem.clotho.annotation.Version.class).value();
checks.add(new VersionedExpectation(entity.getId(), ver, vProp, entity instanceof ClothoVertex));
}
/** Builds one anonymous update branch: writes dirty @Property fields and increments @Version. */
@SuppressWarnings({"unchecked", "rawtypes"})
private void buildUpdateBranch(ClothoEntity entity, boolean isVertex,
List<GraphTraversal<?, ?>> branches,
Map<ARID, VersionedExpectation> versionMap) {
Set<String> dirty = entity.getDirtyFields();
if (dirty.isEmpty()) return;
Map<String, String> fieldToProperty = FieldMetadataCache.get(entity.getClass()).fieldToPropertyName();
List<PropertyEntry> dirtyEntries = collectAllPropertyEntries(entity).stream()
.filter(pe -> dirty.contains(reverseMap(fieldToProperty, pe.name())))
.toList();
VersionedExpectation ve = versionMap.get(entity.getId());
if (dirtyEntries.isEmpty() && ve == null) return;
String idStr = entity.getId().asString();
GraphTraversal t = isVertex ? __.V(idStr) : __.E(idStr);
for (PropertyEntry pe : dirtyEntries) {
if (pe.value() != null) t = t.property(pe.name(), pe.value());
}
if (ve != null) {
t = t.property(ve.versionProp(), ve.expectedVersion() + 1);
}
branches.add(t);
}
// --- Vertex persistence ---
private void persistVertex(ClothoVertex vertex, Set<ClothoEntity> visited) {
if (!visited.add(vertex)) return;
if (vertex.getId() == null) {
createVertex(vertex);
vertex.setState(EntityState.MANAGED);
} else if (vertex.getState() == EntityState.MANAGED) {
Set<String> dirty = vertex.getDirtyFields();
if (!dirty.isEmpty()) {
updateEntity(vertex, dirty, g.V(vertex.getId().asString()));
}
} else {
// ID is set but entity was not loaded through the session — full property write.
writeAllProperties(vertex, g.V(vertex.getId().asString()));
vertex.setState(EntityState.MANAGED);
}
cascadeIncludes(vertex, visited);
}
private void createVertex(ClothoVertex entity) {
var traversal = g.addV(entity.getLabel());
for (PropertyEntry pv : collectAllPropertyEntries(entity)) {
if (pv.value() != null) traversal = traversal.property(pv.name(), pv.value());
}
Field vf = FieldMetadataCache.get(entity.getClass()).versionField();
if (vf != null) {
traversal = traversal.property(
vf.getAnnotation(com.binarygolem.clotho.annotation.Version.class).value(), 0L);
}
Vertex created = traversal.next();
entity.setId(ARID.of(created.id().toString()));
if (vf != null) setField(vf, entity, 0L);
entity.clearDirtyFields();
}
// --- Edge persistence ---
private void persistEdge(ClothoEdge edge, Set<ClothoEntity> visited) {
if (!visited.add(edge)) return;
if (edge.getId() == null) {
createEdge(edge, visited);
edge.setState(EntityState.MANAGED);
} else if (edge.getState() == EntityState.MANAGED) {
Set<String> dirty = edge.getDirtyFields();
if (!dirty.isEmpty()) {
updateEntity(edge, dirty, g.E(edge.getId().asString()));
}
} else {
// ID is set but entity was not loaded through the session — full property write.
writeAllProperties(edge, g.E(edge.getId().asString()));
edge.setState(EntityState.MANAGED);
}
// Cascade to @OutVertex / @InVertex loaded entities
for (Field field : FieldMetadataCache.get(edge.getClass()).edgeVertexFields()) {
Object value = readField(field, edge);
if (value instanceof ClothoVertex v) persistVertex(v, visited);
}
}
private void createEdge(ClothoEdge entity, Set<ClothoEntity> visited) {
ARID outId = resolveVertexId(entity, OutVertex.class, entity.getOutVertexId(), visited);
ARID inId = resolveVertexId(entity, InVertex.class, entity.getInVertexId(), visited);
if (outId == null || inId == null) {
throw new ClothoConfigurationException(
"Cannot create edge '" + entity.getLabel()
+ "': outVertexId and inVertexId must be resolvable");
}
var traversal = g.addE(entity.getLabel())
.from(__.V(outId.asString()))
.to(__.V(inId.asString()));
for (PropertyEntry pv : collectAllPropertyEntries(entity)) {
if (pv.value() != null) traversal = traversal.property(pv.name(), pv.value());
}
Field vf = FieldMetadataCache.get(entity.getClass()).versionField();
if (vf != null) {
traversal = traversal.property(
vf.getAnnotation(com.binarygolem.clotho.annotation.Version.class).value(), 0L);
}
Edge created = traversal.next();
entity.setId(ARID.of(created.id().toString()));
if (vf != null) setField(vf, entity, 0L);
entity.clearDirtyFields();
}
// --- Full property write (entity has ID but was not loaded through session) ---
private void writeAllProperties(ClothoEntity entity, GraphTraversal<?, ?> start) {
var t = start;
for (PropertyEntry e : collectAllPropertyEntries(entity)) {
if (e.value() != null) t = t.property(e.name(), e.value());
}
t.iterate();
entity.clearDirtyFields();
}
// --- Shared update with dirty-filter and OCC ---
/**
* Updates only the dirty fields of {@code entity}, optionally guarded by {@code @Version}.
* If a {@code @Version} field is present, the update is filtered by the expected version;
* a mismatch throws {@link OptimisticLockException}. On success the version is
* atomically incremented in the same traversal and the in-memory field is updated.
*/
private void updateEntity(ClothoEntity entity, Set<String> dirtyFieldNames,
GraphTraversal<?, ?> start) {
Map<String, String> fieldToProperty = FieldMetadataCache.get(entity.getClass()).fieldToPropertyName();
List<PropertyEntry> dirtyEntries = collectAllPropertyEntries(entity).stream()
.filter(e -> dirtyFieldNames.contains(reverseMap(fieldToProperty, e.name())))
.toList();
Field versionField = FieldMetadataCache.get(entity.getClass()).versionField();
if (versionField != null) {
Long version = (Long) readField(versionField, entity);
if (version != null) {
String vProp = versionField.getAnnotation(
com.binarygolem.clotho.annotation.Version.class).value();
var t = start.has(vProp, version);
for (PropertyEntry e : dirtyEntries) {
if (e.value() != null) t = t.property(e.name(), e.value());
}
t = t.property(vProp, version + 1);
long matched = t.count().next();
if (matched == 0) throw new OptimisticLockException(entity.getId(), version);
setField(versionField, entity, version + 1);
entity.clearDirtyFields();
return;
}
}
var t = start;
for (PropertyEntry e : dirtyEntries) {
if (e.value() != null) t = t.property(e.name(), e.value());
}
if (!dirtyEntries.isEmpty()) t.iterate();
entity.clearDirtyFields();
}
/**
* Given a property name, find the field name that maps to it.
* Used to correlate dirty field names (Java field names) against PropertyEntry names (graph property names).
*/
private static String reverseMap(Map<String, String> fieldToProperty, String propertyName) {
for (Map.Entry<String, String> entry : fieldToProperty.entrySet()) {
if (entry.getValue().equals(propertyName)) return entry.getKey();
}
return propertyName;
}
// --- Cascade ---
private void cascadeIncludes(ClothoVertex root, Set<ClothoEntity> visited) {
for (Field field : FieldMetadataCache.get(root.getClass()).allIncludeFields()) {
Object value = readField(field, root);
if (value == null) continue;
TraversalDirection direction = resolveDirection(field);
if (value instanceof ClothoVertex v) {
persistVertex(v, visited);
} else if (value instanceof ClothoEdge e) {
wireRootIntoEdge(e, root, direction);
persistEdge(e, visited);
} else if (value instanceof List<?> list) {
for (Object item : list) {
if (item instanceof ClothoVertex v) persistVertex(v, visited);
else if (item instanceof ClothoEdge e) {
wireRootIntoEdge(e, root, direction);
persistEdge(e, visited);
}
}
}
}
}
private static void wireRootIntoEdge(ClothoEdge edge, ClothoVertex root,
TraversalDirection direction) {
ARID rootId = root.getId();
if (rootId == null) return;
switch (direction) {
case OUT -> { if (edge.getOutVertexId() == null) edge.setOutVertexId(rootId); }
case IN -> { if (edge.getInVertexId() == null) edge.setInVertexId(rootId); }
case BOTH -> {}
}
}
private static TraversalDirection resolveDirection(Field field) {
com.binarygolem.clotho.annotation.Direction annotation =
field.getAnnotation(com.binarygolem.clotho.annotation.Direction.class);
return annotation != null ? annotation.value() : TraversalDirection.OUT;
}
// --- Vertex ID resolution for edge creation ---
@Nullable
private ARID resolveVertexId(ClothoEdge edge,
Class<? extends Annotation> sideAnnotation,
@Nullable ARID stored,
Set<ClothoEntity> visited) {
if (stored != null) return stored;
for (Field field : FieldMetadataCache.get(edge.getClass()).edgeVertexFields()) {
if (!field.isAnnotationPresent(sideAnnotation)) continue;
Object value = readField(field, edge);
if (value instanceof ClothoVertex v) {
if (v.getId() == null) persistVertex(v, visited);
return v.getId();
}
}
return null;
}
// --- Property introspection ---
private record PropertyEntry(String name, @Nullable Object value) {}
private static List<PropertyEntry> collectAllPropertyEntries(ClothoEntity entity) {
List<PropertyEntry> result = new ArrayList<>();
for (Field field : FieldMetadataCache.get(entity.getClass()).propertyFields()) {
String propName = FieldMetadataCache.get(entity.getClass())
.fieldToPropertyName().get(field.getName());
if (propName == null) continue;
result.add(new PropertyEntry(propName, readField(field, entity)));
}
return result;
}
// --- SubgraphType entity collection ---
private static List<ClothoEntity> collectEntityFields(Object instance) {
List<ClothoEntity> result = new ArrayList<>();
Class<?> cursor = instance.getClass();
while (cursor != null && cursor != Object.class) {
for (Field field : cursor.getDeclaredFields()) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || field.isSynthetic()) continue;
Object value = readField(field, instance);
if (value instanceof ClothoEntity entity) {
result.add(entity);
} else if (value instanceof List<?> list) {
for (Object item : list) {
if (item instanceof ClothoEntity entity) result.add(entity);
}
}
}
cursor = cursor.getSuperclass();
}
return result;
}
// --- Reflection helpers ---
@Nullable
private static Object readField(Field field, Object instance) {
try {
field.setAccessible(true);
return field.get(instance);
} catch (IllegalAccessException e) {
throw new ClothoException("Cannot read field '" + field.getName()
+ "' on " + instance.getClass().getName(), e);
}
}
private static void setField(Field field, Object instance, Object value) {
try {
field.setAccessible(true);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new ClothoException("Cannot set field '" + field.getName()
+ "' on " + instance.getClass().getName(), e);
}
}
private static void bumpVersionField(ClothoEntity entity,
Map<ARID, VersionedExpectation> versionMap) {
VersionedExpectation ve = versionMap.get(entity.getId());
if (ve == null) return;
Field vf = FieldMetadataCache.get(entity.getClass()).versionField();
if (vf == null) return;
setField(vf, entity, ve.expectedVersion() + 1);
}
private static Set<ClothoEntity> identitySet() {
return Collections.newSetFromMap(new IdentityHashMap<>());
}
}
@@ -0,0 +1,142 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Alias;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ClothoVertex;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Assembles a {@code @SubgraphType} instance from a Gremlin {@code select()} result map.
*
* <p>Each field on the subgraph type is matched to a map key by field name, or by the
* value of an {@link Alias} annotation when present. Vertex values are mapped via
* {@link ElementMapper} and their boundaries eagerly populated via {@link SubgraphLoader}.
*/
public final class SubgraphTypeAssembler {
private final ElementMapper mapper;
private final SubgraphLoader loader;
public SubgraphTypeAssembler(ElementMapper mapper, SubgraphLoader loader) {
this.mapper = mapper;
this.loader = loader;
}
/**
* Assembles an instance of {@code type} from {@code selectResult}.
*
* @throws ClothoConfigurationException if {@code type} is not annotated with {@code @SubgraphType}
*/
public <T> T assemble(Class<T> type, Map<String, Object> selectResult) {
if (!type.isAnnotationPresent(SubgraphType.class)) {
throw new ClothoConfigurationException(
type.getName() + " is not annotated with @SubgraphType");
}
T instance = instantiate(type);
for (Field field : collectFields(type)) {
String key = resolveKey(field);
Object raw = selectResult.get(key);
if (raw == null) continue;
Object mapped = mapValue(raw, field);
setField(field, instance, mapped);
}
return instance;
}
private @Nullable Object mapValue(Object raw, Field field) {
if (raw instanceof Vertex v) {
ClothoVertex mapped = mapper.mapVertex(v);
loader.populate(mapped);
return mapped;
}
if (raw instanceof Edge e) {
return mapper.mapEdge(e);
}
if (raw instanceof List<?> list) {
Class<?> elementType = getListElementType(field);
return list.stream()
.map(item -> mapSingleValue(item, elementType))
.toList();
}
return raw;
}
private @Nullable Object mapSingleValue(Object raw, Class<?> elementType) {
if (raw instanceof Vertex v) {
ClothoVertex mapped = mapper.mapVertex(v);
loader.populate(mapped);
return mapped;
}
if (raw instanceof Edge e) {
return mapper.mapEdge(e);
}
return raw;
}
// --- Helpers ---
private static String resolveKey(Field field) {
Alias alias = field.getAnnotation(Alias.class);
return alias != null ? alias.value() : field.getName();
}
private static List<Field> collectFields(Class<?> clazz) {
List<Field> result = new ArrayList<>();
Class<?> cursor = clazz;
while (cursor != null && cursor != Object.class) {
for (Field f : cursor.getDeclaredFields()) {
int mod = f.getModifiers();
if (!Modifier.isStatic(mod) && !f.isSynthetic()) result.add(f);
}
cursor = cursor.getSuperclass();
}
return result;
}
private static Class<?> getListElementType(Field field) {
Type generic = field.getGenericType();
if (generic instanceof ParameterizedType pt) {
Type arg = pt.getActualTypeArguments()[0];
if (arg instanceof Class<?> c) return c;
}
throw new ClothoConfigurationException(
"Cannot determine element type of List field '" + field.getName() + "'");
}
private static <T> T instantiate(Class<T> clazz) {
try {
var ctor = clazz.getDeclaredConstructor();
ctor.setAccessible(true);
return ctor.newInstance();
} catch (Exception e) {
throw new ClothoConfigurationException(
clazz.getName() + " must have a no-arg constructor for Clotho to instantiate it", e);
}
}
private static void setField(Field field, Object instance, @Nullable Object value) {
try {
field.setAccessible(true);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new ClothoConfigurationException(
"Cannot set field '" + field.getName() + "' on "
+ instance.getClass().getName(), e);
}
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.mapping;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,21 @@
package com.binarygolem.clotho.model;
/**
* Typed wrapper for an ArcadeDB record ID (e.g. {@code #10:0}).
* Null ARID means the element has not yet been persisted.
*/
public record ARID(String value) {
public static ARID of(String value) {
return new ARID(value);
}
public String asString() {
return value;
}
@Override
public String toString() {
return value;
}
}
@@ -0,0 +1,26 @@
package com.binarygolem.clotho.model;
import lombok.Getter;
import lombok.Setter;
import org.jspecify.annotations.Nullable;
/**
* Base class for all Clotho-managed edge types.
* Annotate concrete subclasses with {@code @EdgeType}.
*
* <p>Carries the ARIDs of the out-vertex and in-vertex so that edges are
* always independently addressable, even when the adjacent vertices are
* not loaded.
*/
public abstract class ClothoEdge extends ClothoEntity {
/** ARID of the vertex at the tail (source) of this edge. */
@Getter
@Setter
private @Nullable ARID outVertexId;
/** ARID of the vertex at the head (target) of this edge. */
@Getter
@Setter
private @Nullable ARID inVertexId;
}
@@ -0,0 +1,120 @@
package com.binarygolem.clotho.model;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import lombok.Getter;
import lombok.Setter;
import org.jspecify.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
// NOPMD — EntityState is in the same package; explicit import needed by the compiler
/**
* Base class for all Clotho-managed graph elements.
* Carries identity ({@link ARID}), label, lifecycle state, dirty-field tracking,
* and raw property access.
*
* <p>All {@code @VertexType} classes extend {@link ClothoVertex};
* all {@code @EdgeType} classes extend {@link ClothoEdge}.
*
* <h3>Dirty tracking</h3>
* Subclasses must call {@link #notifyFieldChanged(String)} from every manual setter
* on tracked fields ({@code @Property}, {@code @Include}, {@code @OutVertex},
* {@code @InVertex}). Do NOT use Lombok {@code @Setter} on those fields — write
* the setter by hand. Notification is a no-op when the entity is not
* {@link EntityState#MANAGED}, so calls during construction or hydration are safe.
*/
public abstract class ClothoEntity {
/** ArcadeDB record ID. Null until the element is persisted. */
@Getter
@Setter
private @Nullable ARID id;
@Getter
private EntityState state = EntityState.NEW;
private final Set<String> dirtyFields = new LinkedHashSet<>();
private final Map<String, @Nullable Object> rawProperties = new LinkedHashMap<>();
// --- Lifecycle (framework-internal: called from session and mapping layer) ---
public void setState(EntityState state) {
this.state = state;
}
public Set<String> getDirtyFields() {
return Collections.unmodifiableSet(dirtyFields);
}
public void clearDirtyFields() {
dirtyFields.clear();
}
// --- Dirty notification (public: called from entity subclass setters) ---
/**
* Record that a tracked field has changed. Call this from every manual setter:
*
* <pre>{@code
* public void setName(String name) {
* this.name = name;
* notifyFieldChanged("name");
* }
* }</pre>
*
* No-op when the entity is not {@link EntityState#MANAGED} (construction, hydration).
*/
public void notifyFieldChanged(String fieldName) {
if (state == EntityState.MANAGED) {
dirtyFields.add(fieldName);
}
}
// --- Label ---
/**
* Returns the ArcadeDB type name declared on this class via
* {@code @VertexType} or {@code @EdgeType}.
*
* @throws ClothoConfigurationException if neither annotation is present
*/
public String getLabel() {
Class<?> cls = getClass();
VertexType vt = cls.getAnnotation(VertexType.class);
if (vt != null) return vt.value();
EdgeType et = cls.getAnnotation(EdgeType.class);
if (et != null) return et.value();
throw new ClothoConfigurationException(
cls.getName() + " is not annotated with @VertexType or @EdgeType");
}
public boolean hasLabel(String label) {
return getLabel().equals(label);
}
// --- Raw properties ---
/**
* Returns the raw value of a graph property not mapped to a typed field.
* Returns {@code null} if the property is absent.
*/
public @Nullable Object getProperty(String key) {
return rawProperties.get(key);
}
/**
* For Clotho framework use only — called by {@code ElementMapper} when
* mapping a Gremlin element to this instance. Not part of the public API.
*/
public void setRawProperty(String key, @Nullable Object value) {
rawProperties.put(key, value);
}
}
@@ -0,0 +1,13 @@
package com.binarygolem.clotho.model;
/**
* Base class for all Clotho-managed vertex types.
* Annotate concrete subclasses with {@code @VertexType}.
*
* <p>An instance represents either a single vertex (properties only)
* or a composite subgraph rooted at that vertex when {@code @Include}
* fields are declared.
*/
public abstract class ClothoVertex extends ClothoEntity {
// Vertex-specific behaviour added in later phases.
}
@@ -0,0 +1,17 @@
package com.binarygolem.clotho.model;
/**
* Lifecycle state of a {@link ClothoEntity}.
*
* <ul>
* <li>{@link #NEW} — constructed in Java, never persisted to the graph.</li>
* <li>{@link #MANAGED} — loaded from the graph or successfully saved at least once.
* Dirty-field tracking is active in this state.</li>
* <li>{@link #DETACHED} — removed from the graph via {@code session.delete()}.</li>
* </ul>
*/
public enum EntityState {
NEW,
MANAGED,
DETACHED
}
@@ -0,0 +1,17 @@
package com.binarygolem.clotho.model;
/**
* Controls when an {@code @Include} field is populated.
*
* <ul>
* <li>{@link #EAGER} — populated immediately as part of {@code SubgraphLoader.populate()}.
* This is the default.</li>
* <li>{@link #LAZY} — skipped during {@code populate()}; remains {@code null} / empty
* until the developer calls {@code session.loadField(vertex, "fieldName")}
* explicitly.</li>
* </ul>
*/
public enum FetchType {
EAGER,
LAZY
}
@@ -0,0 +1,8 @@
package com.binarygolem.clotho.model;
/**
* Concrete ClothoEdge used when {@code UnknownTypeBehavior.GENERIC} is active
* and no registered type matches the edge label. Carries only raw properties.
*/
public final class GenericEdge extends ClothoEdge {
}
@@ -0,0 +1,8 @@
package com.binarygolem.clotho.model;
/**
* Concrete ClothoVertex used when {@code UnknownTypeBehavior.GENERIC} is active
* and no registered type matches the vertex label. Carries only raw properties.
*/
public final class GenericVertex extends ClothoVertex {
}
@@ -0,0 +1,11 @@
package com.binarygolem.clotho.model;
/** Edge traversal direction for {@code @Via} / {@code @Direction} declarations. */
public enum TraversalDirection {
/** Follow outgoing edges (default). */
OUT,
/** Follow incoming edges. */
IN,
/** Follow edges in both directions. */
BOTH
}
@@ -0,0 +1,26 @@
package com.binarygolem.clotho.model;
/**
* Controls what happens when a Gremlin result carries a vertex or edge label
* that has no registered Clotho Java class.
*/
public enum UnknownTypeBehavior {
/**
* Throw {@link com.binarygolem.clotho.exception.UnknownTypeException}.
* Recommended default — fail loudly rather than silently losing data.
*/
STRICT,
/**
* Instantiate the closest registered ancestor in the Java type hierarchy.
* Subtype-specific fields will be null; common ancestor fields are populated.
*/
NEAREST_ANCESTOR,
/**
* Wrap the element in a plain {@link ClothoVertex} or {@link ClothoEdge}
* with only raw property access available via {@code getProperty()}.
*/
GENERIC
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.model;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,239 @@
package com.binarygolem.clotho.registry;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.exception.UnknownTypeException;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.GenericEdge;
import com.binarygolem.clotho.model.GenericVertex;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ScanResult;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Holds the label-to-class mapping for all registered {@code @VertexType} and
* {@code @EdgeType} classes. Built once at startup; immutable after construction.
*
* <p>Use {@link #builder()} for manual registration or {@link #scan(String...)}
* for automatic classpath scanning.
*/
public final class TypeRegistry {
private final Map<String, Class<? extends ClothoVertex>> vertexTypes;
private final Map<String, Class<? extends ClothoEdge>> edgeTypes;
// label → declared ArcadeDB parent labels, derived from registered annotations
private final Map<String, Set<String>> parentLabels;
private TypeRegistry(
Map<String, Class<? extends ClothoVertex>> vertexTypes,
Map<String, Class<? extends ClothoEdge>> edgeTypes,
Map<String, Set<String>> parentLabels) {
this.vertexTypes = Collections.unmodifiableMap(vertexTypes);
this.edgeTypes = Collections.unmodifiableMap(edgeTypes);
this.parentLabels = Collections.unmodifiableMap(parentLabels);
}
// --- Lookup ---
public Optional<Class<? extends ClothoVertex>> findVertex(String label) {
return Optional.ofNullable(vertexTypes.get(label));
}
public Optional<Class<? extends ClothoEdge>> findEdge(String label) {
return Optional.ofNullable(edgeTypes.get(label));
}
/**
* Resolves a vertex label to a class, applying {@code behavior} when the
* label is not registered.
*
* <p>{@code NEAREST_ANCESTOR} traverses the parent-label chain built from
* registered annotations. For labels whose parentage is entirely unknown
* (no registered class declares them as a parent), it falls back to
* {@link GenericVertex}.
*/
public Class<? extends ClothoVertex> resolveVertex(String label, UnknownTypeBehavior behavior) {
Class<? extends ClothoVertex> found = vertexTypes.get(label);
if (found != null) return found;
return switch (behavior) {
case STRICT -> throw new UnknownTypeException(label);
case NEAREST_ANCESTOR -> findNearestVertexAncestor(label).orElse(GenericVertex.class);
case GENERIC -> GenericVertex.class;
};
}
/**
* Resolves an edge label to a class, applying {@code behavior} when the
* label is not registered.
*/
public Class<? extends ClothoEdge> resolveEdge(String label, UnknownTypeBehavior behavior) {
Class<? extends ClothoEdge> found = edgeTypes.get(label);
if (found != null) return found;
return switch (behavior) {
case STRICT -> throw new UnknownTypeException(label);
case NEAREST_ANCESTOR -> findNearestEdgeAncestor(label).orElse(GenericEdge.class);
case GENERIC -> GenericEdge.class;
};
}
private Optional<Class<? extends ClothoVertex>> findNearestVertexAncestor(String label) {
for (String parent : parentLabels.getOrDefault(label, Set.of())) {
Class<? extends ClothoVertex> registered = vertexTypes.get(parent);
if (registered != null) return Optional.of(registered);
Optional<Class<? extends ClothoVertex>> ancestor = findNearestVertexAncestor(parent);
if (ancestor.isPresent()) return ancestor;
}
return Optional.empty();
}
private Optional<Class<? extends ClothoEdge>> findNearestEdgeAncestor(String label) {
for (String parent : parentLabels.getOrDefault(label, Set.of())) {
Class<? extends ClothoEdge> registered = edgeTypes.get(parent);
if (registered != null) return Optional.of(registered);
Optional<Class<? extends ClothoEdge>> ancestor = findNearestEdgeAncestor(parent);
if (ancestor.isPresent()) return ancestor;
}
return Optional.empty();
}
// --- Introspection ---
public Set<String> vertexLabels() {
return vertexTypes.keySet();
}
public Set<String> edgeLabels() {
return edgeTypes.keySet();
}
// --- Factory ---
public static Builder builder() {
return new Builder();
}
/**
* Scans the given packages for {@code @VertexType} and {@code @EdgeType}
* classes and registers them.
*
* @throws ClothoConfigurationException if a class is annotated but does not
* extend the correct base type, or if
* two classes share the same label
*/
public static TypeRegistry scan(String... packages) {
Builder builder = builder();
try (ScanResult result = new ClassGraph()
.enableClassInfo()
.enableAnnotationInfo()
.acceptPackages(packages)
.scan()) {
for (ClassInfo info : result.getClassesWithAnnotation(VertexType.class)) {
Class<?> clazz = info.loadClass();
if (!ClothoVertex.class.isAssignableFrom(clazz)) {
throw new ClothoConfigurationException(
clazz.getName() + " is annotated @VertexType but does not extend ClothoVertex");
}
@SuppressWarnings("unchecked")
Class<? extends ClothoVertex> vertexClass = (Class<? extends ClothoVertex>) clazz;
builder.registerVertex(vertexClass);
}
for (ClassInfo info : result.getClassesWithAnnotation(EdgeType.class)) {
Class<?> clazz = info.loadClass();
if (!ClothoEdge.class.isAssignableFrom(clazz)) {
throw new ClothoConfigurationException(
clazz.getName() + " is annotated @EdgeType but does not extend ClothoEdge");
}
@SuppressWarnings("unchecked")
Class<? extends ClothoEdge> edgeClass = (Class<? extends ClothoEdge>) clazz;
builder.registerEdge(edgeClass);
}
}
return builder.build();
}
// --- Builder ---
public static final class Builder {
private final Map<String, Class<? extends ClothoVertex>> vertexTypes = new LinkedHashMap<>();
private final Map<String, Class<? extends ClothoEdge>> edgeTypes = new LinkedHashMap<>();
private final Map<String, Set<String>> parentLabels = new LinkedHashMap<>();
public Builder registerVertex(Class<? extends ClothoVertex> clazz) {
VertexType annotation = clazz.getAnnotation(VertexType.class);
if (annotation == null) {
throw new ClothoConfigurationException(
clazz.getName() + " is not annotated with @VertexType");
}
String label = annotation.value();
Class<? extends ClothoVertex> existing = vertexTypes.put(label, clazz);
if (existing != null && !existing.equals(clazz)) {
throw new ClothoConfigurationException(
"Duplicate vertex label '" + label + "': "
+ existing.getName() + " and " + clazz.getName());
}
recordVertexParents(label, clazz, annotation);
return this;
}
public Builder registerEdge(Class<? extends ClothoEdge> clazz) {
EdgeType annotation = clazz.getAnnotation(EdgeType.class);
if (annotation == null) {
throw new ClothoConfigurationException(
clazz.getName() + " is not annotated with @EdgeType");
}
String label = annotation.value();
Class<? extends ClothoEdge> existing = edgeTypes.put(label, clazz);
if (existing != null && !existing.equals(clazz)) {
throw new ClothoConfigurationException(
"Duplicate edge label '" + label + "': "
+ existing.getName() + " and " + clazz.getName());
}
return this;
}
private void recordVertexParents(String label, Class<? extends ClothoVertex> clazz,
VertexType annotation) {
Set<String> parents = new LinkedHashSet<>();
String explicit = annotation.parentLabel();
if (!explicit.isEmpty()) {
// parentLabel overrides Java hierarchy
parents.add(explicit);
} else {
// Infer primary parent from Java superclass if it's also a @VertexType
Class<?> superclass = clazz.getSuperclass();
if (superclass != null) {
VertexType superAnnotation = superclass.getAnnotation(VertexType.class);
if (superAnnotation != null) {
parents.add(superAnnotation.value());
}
}
}
// additionalParents covers ArcadeDB multi-inheritance beyond the Java chain
parents.addAll(Arrays.asList(annotation.additionalParents()));
if (!parents.isEmpty()) {
parentLabels.put(label, Collections.unmodifiableSet(parents));
}
}
public TypeRegistry build() {
return new TypeRegistry(vertexTypes, edgeTypes, parentLabels);
}
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.registry;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,379 @@
package com.binarygolem.clotho.repository;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.mapping.ElementMapper;
import com.binarygolem.clotho.mapping.SubgraphLoader;
import com.binarygolem.clotho.mapping.SubgraphPersistor;
import com.binarygolem.clotho.mapping.SubgraphTypeAssembler;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
/**
* Abstract base class for Clotho repositories.
*
* <p>Subclass this to define query methods for a specific {@link ClothoEntity} type.
* Call {@link #g()} to obtain the live {@link GraphTraversalSource} and build TinkerPop
* Java DSL traversals, then pass them to {@link #execute}, {@link #executeSubgraph}, or
* {@link #executeRaw}. No Gremlin strings; no annotation proxies.
*
* <pre>{@code
* @ClothoRepository
* public class EmployeeRepo extends ClothoRepository<Employee> {
*
* public EmployeeRepo(ClothoSessionFactory factory) { super(factory); }
*
* public List<Employee> findByDept(String dept) {
* return execute(g().V().has("Employee", "dept", dept));
* }
*
* public List<Employee> findSenior() {
* return findAll(t -> t.has("level", "SENIOR"));
* }
*
* public long countByDept(String dept) {
* return this.<Long>executeRaw(
* g().V().hasLabel("Employee").has("dept", dept).count()
* ).get(0);
* }
* }
* }</pre>
*
* <p>The type parameter {@code T} is inferred from the generic superclass declaration.
* Use the two-argument constructor when the entity class cannot be inferred (e.g. when
* a second level of generic inheritance is involved).
*
* <p>Repositories are stateless (thread-safe) after construction. A single instance
* per application is typical; Spring Boot users obtain them as beans via
* {@code ClothoAutoConfiguration}.
*/
public abstract class ClothoRepository<T extends ClothoEntity> {
protected final Class<T> entityClass;
private final GraphTraversalSource g;
private final ElementMapper mapper;
private final SubgraphLoader loader;
private final SubgraphPersistor persistor;
private final SubgraphTypeAssembler assembler;
/**
* Primary constructor. Infers the entity class {@code T} from the generic superclass
* declaration ({@code class EmployeeRepo extends ClothoRepository<Employee>}).
*
* @throws ClothoConfigurationException if the generic type cannot be inferred
*/
@SuppressWarnings("unchecked")
protected ClothoRepository(ClothoSessionFactory factory) {
this.g = factory.traversal();
this.mapper = factory.mapper();
this.loader = factory.loader();
this.persistor = factory.persistor();
this.assembler = factory.assembler();
try {
ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<T>) pt.getActualTypeArguments()[0];
} catch (ClassCastException | ArrayIndexOutOfBoundsException e) {
throw new ClothoConfigurationException(
getClass().getName()
+ " cannot infer entity type from generic superclass."
+ " Use ClothoRepository(factory, Class<T>) instead.", e);
}
}
/**
* Fallback constructor for cases where the generic entity type cannot be inferred
* automatically (e.g. multi-level generic inheritance).
*/
protected ClothoRepository(ClothoSessionFactory factory, Class<T> entityClass) {
this.g = factory.traversal();
this.mapper = factory.mapper();
this.loader = factory.loader();
this.persistor = factory.persistor();
this.assembler = factory.assembler();
this.entityClass = entityClass;
}
// --- Traversal access ---
/**
* Returns the live {@link GraphTraversalSource}.
* Use this to build traversals inside repository methods:
* <pre>{@code return execute(g().V().has("Employee", "dept", dept)); }</pre>
*/
protected GraphTraversalSource g() {
return g;
}
/**
* Returns the base traversal for all entities of this repository's type.
* Vertex repositories return {@code g().V().hasLabel(label)};
* edge repositories return {@code g().E().hasLabel(label)}.
*/
protected GraphTraversal<?, ?> allEntities() {
String label = getLabel();
if (ClothoVertex.class.isAssignableFrom(entityClass)) {
return g().V().hasLabel(label);
}
return g().E().hasLabel(label);
}
// --- Execute ---
/**
* Executes a traversal that produces vertices or edges, maps each result to its
* most-specific registered Clotho type, and (for vertices) batch-populates all
* {@code @Include} boundaries in a single set of Gremlin traversals.
*/
@SuppressWarnings("unchecked")
public List<T> execute(GraphTraversal<?, ?> traversal) {
List<?> raw = traversal.toList();
if (ClothoVertex.class.isAssignableFrom(entityClass)) {
List<ClothoVertex> vertices = raw.stream()
.filter(Vertex.class::isInstance)
.map(item -> mapper.mapVertex((Vertex) item))
.toList();
loader.populateAll(vertices);
return (List<T>) vertices;
}
return raw.stream().map(item -> {
if (item instanceof Vertex v) return (T) mapper.mapVertex(v);
if (item instanceof Edge e) return (T) mapper.mapEdge(e);
throw new ClothoException(
"execute() expected Vertex or Edge results but got: "
+ item.getClass().getName());
}).toList();
}
/**
* Applies {@code filter} to {@code base} then executes the result.
*
* <pre>{@code
* // Caller passes a filter that extends the base traversal:
* findAll(t -> t.has("level", "SENIOR").has("dept", dept))
* }</pre>
*/
public List<T> execute(GraphTraversal<?, ?> base, UnaryOperator<GraphTraversal<?, ?>> filter) {
return execute(filter.apply(base));
}
/**
* Like {@link #execute(GraphTraversal)} but integrates with the session's identity map.
* Vertices already cached by the session are returned as-is (same Java instance, tracked).
* New vertices are populated and registered as MANAGED.
*
* <p>This guarantees that for any ARID there is exactly one Java instance per session —
* mutations on returned objects are always tracked and auto-saved on close.
*/
@SuppressWarnings("unchecked")
public List<T> execute(ClothoSession session, GraphTraversal<?, ?> traversal) {
List<?> raw = traversal.toList();
if (ClothoVertex.class.isAssignableFrom(entityClass)) {
List<ClothoVertex> result = new ArrayList<>();
List<ClothoVertex> toPopulate = new ArrayList<>();
for (Object item : raw) {
if (!(item instanceof Vertex v)) continue;
ClothoVertex mapped = mapper.mapVertex(v);
ARID id = mapped.getId();
@Nullable ClothoVertex cached = id != null ? session.getCached(id) : null;
if (cached != null) {
result.add(cached);
} else {
result.add(mapped);
toPopulate.add(mapped);
}
}
loader.populateAll(toPopulate);
toPopulate.forEach(session::register);
return (List<T>) result;
}
return raw.stream().map(item -> {
if (item instanceof Vertex v) return (T) mapper.mapVertex(v);
if (item instanceof Edge e) return (T) mapper.mapEdge(e);
throw new ClothoException(
"execute() expected Vertex or Edge results but got: "
+ item.getClass().getName());
}).toList();
}
/**
* Convenience overload — applies {@code filter} first, then delegates to
* {@link #execute(ClothoSession, GraphTraversal)}.
*/
public List<T> execute(ClothoSession session, GraphTraversal<?, ?> base,
UnaryOperator<GraphTraversal<?, ?>> filter) {
return execute(session, filter.apply(base));
}
/**
* Executes a {@code select()}-producing traversal and assembles each row into an
* instance of {@code subgraphType} via {@link SubgraphTypeAssembler}.
*
* <pre>{@code
* executeSubgraph(EmployeeProfile.class,
* g().V().has("Employee","id",id).as("employee")
* .out("MANAGED_BY").as("manager")
* .select("employee","manager"))
* }</pre>
*/
@SuppressWarnings("unchecked")
public <S> List<S> executeSubgraph(Class<S> subgraphType, GraphTraversal<?, ?> traversal) {
return traversal.toList().stream()
.map(item -> {
if (item instanceof Map<?, ?> m) {
return assembler.assemble(subgraphType, (Map<String, Object>) m);
}
throw new ClothoException(
"executeSubgraph() expected Map results but got: "
+ item.getClass().getName());
})
.toList();
}
/**
* Executes a traversal and returns the raw results without any Clotho mapping.
* Use for scalar results such as counts, property values, or aggregations.
*
* <pre>{@code
* long total = this.<Long>executeRaw(g().V().hasLabel("Employee").count()).get(0);
* }</pre>
*/
@SuppressWarnings("unchecked")
public <R> List<R> executeRaw(GraphTraversal<?, ?> traversal) {
return (List<R>) traversal.toList();
}
// --- Built-in operations ---
/** Returns all entities of this repository's type, with boundaries populated. */
public List<T> findAll() {
return execute(allEntities());
}
/**
* Returns all entities matching the given filter, applied to the base
* {@link #allEntities()} traversal.
*/
public List<T> findAll(UnaryOperator<GraphTraversal<?, ?>> filter) {
return execute(allEntities(), filter);
}
/**
* Returns the entity with the given ARID, or {@code null} if not found.
* For vertices the {@code @Include} boundary is eagerly populated.
*/
@SuppressWarnings("unchecked")
public @Nullable T findById(ARID id) {
if (ClothoVertex.class.isAssignableFrom(entityClass)) {
return g().V(id.asString()).tryNext()
.map(v -> {
ClothoVertex vertex = mapper.mapVertex(v);
loader.populate(vertex);
return (T) vertex;
})
.orElse(null);
}
return g().E(id.asString()).tryNext()
.map(e -> (T) mapper.mapEdge(e))
.orElse(null);
}
/** Returns the total count of entities of this repository's type. */
public long count() {
return (long) allEntities().count().next();
}
/**
* Returns the count of entities matching the given filter, applied to
* the base {@link #allEntities()} traversal.
*/
public long count(UnaryOperator<GraphTraversal<?, ?>> filter) {
return (long) filter.apply(allEntities()).count().next();
}
/** Returns a page of entities sorted in traversal order. */
public List<T> findWithPagination(long offset, long limit) {
return execute(allEntities().range(offset, offset + limit));
}
/** Returns a filtered page of entities. */
public List<T> findWithPagination(UnaryOperator<GraphTraversal<?, ?>> filter,
long offset, long limit) {
return execute(filter.apply(allEntities()).range(offset, offset + limit));
}
// --- Persistence ---
/**
* Persists the entity (create if ARID is null; update otherwise).
* For vertices, cascades through {@code @Include} boundaries.
*/
public void save(T entity) {
if (entity instanceof ClothoVertex v) {
persistor.persist(v);
} else if (entity instanceof ClothoEdge e) {
persistor.persist(e);
}
}
/**
* Removes the entity from the graph.
*
* @throws ClothoException if the entity has no ARID
*/
public void delete(T entity) {
ARID id = entity.getId();
if (id == null) {
throw new ClothoException(
"Cannot delete unpersisted entity: " + entity.getClass().getName());
}
delete(id);
}
/** Removes the entity with the given ARID from the graph. */
public void delete(ARID id) {
if (ClothoVertex.class.isAssignableFrom(entityClass)) {
g().V(id.asString()).drop().iterate();
} else {
g().E(id.asString()).drop().iterate();
}
}
// --- Introspection ---
public Class<T> getEntityClass() {
return entityClass;
}
private String getLabel() {
VertexType vt = entityClass.getAnnotation(VertexType.class);
if (vt != null) return vt.value();
EdgeType et = entityClass.getAnnotation(EdgeType.class);
if (et != null) return et.value();
throw new ClothoConfigurationException(
entityClass.getName() + " has no @VertexType or @EdgeType annotation");
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.repository;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,357 @@
package com.binarygolem.clotho.session;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.mapping.ElementMapper;
import com.binarygolem.clotho.mapping.FieldMetadataCache;
import com.binarygolem.clotho.mapping.SubgraphLoader;
import com.binarygolem.clotho.mapping.SubgraphPersistor;
import com.binarygolem.clotho.mapping.SubgraphTypeAssembler;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoEntity;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.EntityState;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.jspecify.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A unit of work against the graph. Provides load/save/delete operations and
* maintains a per-session identity map so that the same vertex or edge ARID
* always resolves to the same Java instance within the session.
*
* <p>Obtain sessions from {@link ClothoSessionFactory#openSession()} or
* {@link ClothoSessionFactory#openTransactionalSession()}.
*
* <p>Non-transactional sessions: {@link #close()} auto-saves dirty managed entities,
* clears the identity map, and unbinds the thread-local {@link SessionContext}.
*
* <p>Transactional sessions: all graph operations execute within a single ArcadeDB
* transaction. {@link #close()} auto-saves then commits; any exception during auto-save
* triggers a rollback. Call {@link #rollback()} explicitly to abort without saving.
*
* <p>When {@link ClothoSessionFactory#openSession()} is called while a session is already
* bound to the current thread (e.g., inside a {@code @Transactional} method), it returns
* the existing session with a borrow count incremented. {@link #close()} on a borrowed
* session is a no-op until all borrows are returned.
*
* <p>Sessions are NOT thread-safe. Use one session per thread / virtual thread.
*/
public class ClothoSession implements AutoCloseable {
private final GraphTraversalSource g;
private final ElementMapper mapper;
private final SubgraphLoader loader;
private final SubgraphPersistor persistor;
private final SubgraphTypeAssembler assembler;
private final boolean transactional;
private final boolean txSupported;
/** Decremented on each close(); real close only fires when it reaches 0. */
private int openCount = 1;
private final Map<ARID, ClothoVertex> vertexCache = new LinkedHashMap<>();
private final Map<ARID, ClothoEdge> edgeCache = new LinkedHashMap<>();
ClothoSession(GraphTraversalSource g, ElementMapper mapper,
SubgraphLoader loader, SubgraphPersistor persistor,
SubgraphTypeAssembler assembler,
boolean transactional, boolean txSupported) {
this.g = g;
this.mapper = mapper;
this.loader = loader;
this.persistor = persistor;
this.assembler = assembler;
this.transactional = transactional;
this.txSupported = txSupported;
SessionContext.bind(this);
}
// --- Load ---
/**
* Loads the vertex with the given ID and eagerly populates its {@code @Include}
* boundary. Returns the session-cached instance if already loaded.
*
* @throws ClothoException if no vertex with the given ID exists in the graph
* @throws ClassCastException if the loaded vertex type is not assignable to {@code type}
*/
public <T extends ClothoVertex> T load(Class<T> type, ARID id) {
@Nullable ClothoVertex cached = vertexCache.get(id);
if (cached != null) {
return type.cast(cached);
}
ClothoVertex vertex = g.V(id.asString()).tryNext()
.map(mapper::mapVertex)
.orElseThrow(() -> new ClothoException("No vertex found with id: " + id));
loader.populate(vertex);
markManaged(vertex);
vertexCache.put(vertex.getId(), vertex);
return type.cast(vertex);
}
/**
* Loads the edge with the given ID. Returns the session-cached instance if already loaded.
*
* @throws ClothoException if no edge with the given ID exists in the graph
* @throws ClassCastException if the loaded edge type is not assignable to {@code type}
*/
public <T extends ClothoEdge> T loadEdge(Class<T> type, ARID id) {
@Nullable ClothoEdge cached = edgeCache.get(id);
if (cached != null) {
return type.cast(cached);
}
ClothoEdge edge = g.E(id.asString()).tryNext()
.map(mapper::mapEdge)
.orElseThrow(() -> new ClothoException("No edge found with id: " + id));
markManaged(edge);
edgeCache.put(edge.getId(), edge);
return type.cast(edge);
}
// --- Save ---
/**
* Persists a vertex and cascades through its {@code @Include} boundary.
* Creates the vertex if its ARID is null; for managed vertices only dirty fields
* are written. Adds the vertex to the session identity map.
*/
public void save(ClothoVertex vertex) {
persistor.persist(vertex);
markManaged(vertex);
ARID id = vertex.getId();
if (id != null) {
vertexCache.put(id, vertex);
}
}
/**
* Persists an edge. Creates it if its ARID is null; for managed edges only dirty
* fields are written.
*/
public void save(ClothoEdge edge) {
persistor.persist(edge);
markManaged(edge);
ARID id = edge.getId();
if (id != null) {
edgeCache.put(id, edge);
}
}
/**
* Persists all {@link ClothoEntity} fields of a {@code @SubgraphType} instance.
* The subgraph type itself has no ARID and is not cached.
*/
public void save(Object subgraphType) {
persistor.persist(subgraphType);
}
// --- Delete ---
/**
* Removes the entity from the graph and evicts it from the session identity map.
*
* @throws ClothoException if the entity has no ARID (was never persisted)
*/
public void delete(ClothoEntity entity) {
ARID id = entity.getId();
if (id == null) {
throw new ClothoException(
"Cannot delete unpersisted entity: " + entity.getClass().getName());
}
if (entity instanceof ClothoVertex) {
g.V(id.asString()).drop().iterate();
vertexCache.remove(id);
} else if (entity instanceof ClothoEdge) {
g.E(id.asString()).drop().iterate();
edgeCache.remove(id);
}
entity.setState(EntityState.DETACHED);
}
// --- Lazy field loading ---
/**
* Populates a single {@code @Include} field on demand — intended for fields
* declared with {@link com.binarygolem.clotho.model.FetchType#LAZY} but usable
* on any {@code @Include} field to force a refresh.
*
* @throws ClothoConfigurationException if no {@code @Include} field with the given
* name exists on the vertex's class
*/
public void loadField(ClothoVertex vertex, String fieldName) {
Field field = FieldMetadataCache.get(vertex.getClass()).allIncludeFields().stream()
.filter(f -> f.getName().equals(fieldName))
.findFirst()
.orElseThrow(() -> new ClothoConfigurationException(
"No @Include field '" + fieldName + "' on "
+ vertex.getClass().getName()));
loader.populateSingleField(vertex, field);
}
// --- Assemble ---
/**
* Assembles a {@code @SubgraphType} from a Gremlin {@code select()} result map.
*/
public <T> T assemble(Class<T> type, Map<String, Object> selectResult) {
return assembler.assemble(type, selectResult);
}
// --- Advanced ---
/**
* Returns the underlying {@link GraphTraversalSource} for use by repositories
* and advanced callers who need direct traversal access.
* For transactional sessions this is the transaction-bound source.
*/
public GraphTraversalSource traversal() {
return g;
}
/** Returns {@code true} if this session was opened with transaction support. */
public boolean isTransactional() {
return transactional;
}
/**
* Evicts all loaded objects from the session identity map without touching the database.
* Forces a fresh graph fetch on the next {@link #load} call for any previously-loaded ID.
* Does NOT flush dirty fields — call {@link #save} explicitly before clearing if needed.
*/
public void clearCache() {
vertexCache.clear();
edgeCache.clear();
}
/**
* Rolls back the current transaction (if transactional), discards all pending changes,
* clears the identity map, and unbinds this session from the current thread.
* Safe to call on non-transactional sessions — pending changes are simply discarded.
*/
public void rollback() {
openCount = 0;
if (transactional && txSupported) {
try { g.tx().rollback(); } catch (Exception ignored) {}
}
clearCache();
SessionContext.unbind();
}
/**
* Auto-saves dirty managed entities, optionally commits the transaction, then
* clears the identity map and unbinds this session from the current thread.
*
* <p>When this session is borrowed (obtained via {@link ClothoSessionFactory#openSession()}
* while another session is already active), close() is a no-op until all borrows
* are returned — the outermost owner does the real flush and commit.
*
* <p>If auto-save throws and this session is transactional, a rollback is attempted
* before re-throwing.
*/
@Override
public void close() {
if (--openCount > 0) return;
try {
autoSave();
if (transactional && txSupported) g.tx().commit();
} catch (RuntimeException e) {
if (transactional && txSupported) {
try { g.tx().rollback(); } catch (Exception ignored) {}
}
throw e;
} finally {
clearCache();
SessionContext.unbind();
}
}
// --- Registration ---
/**
* Returns the cached vertex for {@code id} if one exists in this session's identity
* map, or {@code null} if it has not been loaded yet.
*/
public @Nullable ClothoVertex getCached(ARID id) {
return vertexCache.get(id);
}
/**
* Registers an already-hydrated vertex (and all entities reachable through its
* {@code @Include} boundary) into this session's identity map as MANAGED.
* After this call, dirty-field tracking and auto-save-on-close apply to the
* vertex and every edge/adjacent vertex loaded with it.
*
* <p>Entities already cached by this session are skipped, so calling register()
* on a graph with shared references is safe and cycle-free.
*/
public void register(ClothoVertex vertex) {
if (vertex.getId() == null || vertexCache.containsKey(vertex.getId())) return;
markManaged(vertex);
vertexCache.put(vertex.getId(), vertex);
for (Field field : FieldMetadataCache.get(vertex.getClass()).allIncludeFields()) {
Object value = readField(field, vertex);
if (value instanceof List<?> list) {
for (Object item : list) {
if (item instanceof ClothoEdge e) registerEdge(e);
else if (item instanceof ClothoVertex v) register(v);
}
} else if (value instanceof ClothoEdge e) registerEdge(e);
else if (value instanceof ClothoVertex v) register(v);
}
}
private void registerEdge(ClothoEdge edge) {
if (edge.getId() == null || edgeCache.containsKey(edge.getId())) return;
markManaged(edge);
edgeCache.put(edge.getId(), edge);
for (Field field : FieldMetadataCache.get(edge.getClass()).edgeVertexFields()) {
Object value = readField(field, edge);
if (value instanceof ClothoVertex v) register(v);
}
}
private static @Nullable Object readField(Field field, Object target) {
try {
field.setAccessible(true);
return field.get(target);
} catch (IllegalAccessException e) {
return null;
}
}
// --- Internal ---
/** Increments the borrow count so the next close() call is a no-op. */
void borrow() {
openCount++;
}
private void autoSave() {
List<ClothoVertex> dirtyVertices = vertexCache.values().stream()
.filter(v -> v.getState() == EntityState.MANAGED && !v.getDirtyFields().isEmpty())
.toList();
List<ClothoEdge> dirtyEdges = edgeCache.values().stream()
.filter(e -> e.getState() == EntityState.MANAGED && !e.getDirtyFields().isEmpty())
.toList();
persistor.persistAllDirty(dirtyVertices, dirtyEdges);
}
private static void markManaged(ClothoEntity entity) {
entity.setState(EntityState.MANAGED);
entity.clearDirtyFields();
}
}
@@ -0,0 +1,174 @@
package com.binarygolem.clotho.session;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.mapping.ElementMapper;
import com.binarygolem.clotho.mapping.SubgraphLoader;
import com.binarygolem.clotho.mapping.SubgraphPersistor;
import com.binarygolem.clotho.mapping.SubgraphTypeAssembler;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import java.util.Objects;
/**
* Creates {@link ClothoSession} instances and provides shared stateless components to
* {@link com.binarygolem.clotho.repository.ClothoRepository} subclasses.
*
* <p>Construct once at application startup via {@link #builder()}. Shared components
* (mapper, loader, persistor, assembler) are created once and reused across all sessions
* and repositories — they are all stateless after construction.
*
* <p>The factory does NOT manage the {@link GraphTraversalSource} lifecycle. The caller
* is responsible for closing the connection at shutdown. Spring Boot users obtain the
* factory as a bean via {@code ClothoAutoConfiguration}.
*/
public final class ClothoSessionFactory {
private final GraphTraversalSource g;
private final TypeRegistry registry;
private final UnknownTypeBehavior unknownTypeBehavior;
private final TraversalDirection defaultDirection;
// Stateless components shared by all sessions and repositories
private final ElementMapper mapper;
private final SubgraphLoader loader;
private final SubgraphPersistor persistor;
private final SubgraphTypeAssembler assembler;
/** False when the graph rejects g.tx() calls (e.g. OrientDB with orient-transactional=false). */
private final boolean graphSupportsTransactions;
private ClothoSessionFactory(GraphTraversalSource g, TypeRegistry registry,
UnknownTypeBehavior unknownTypeBehavior,
TraversalDirection defaultDirection) {
this.g = g;
this.registry = registry;
this.unknownTypeBehavior = unknownTypeBehavior;
this.defaultDirection = defaultDirection;
this.mapper = new ElementMapper(registry, unknownTypeBehavior);
this.loader = new SubgraphLoader(g, mapper, defaultDirection);
this.persistor = new SubgraphPersistor(g);
this.assembler = new SubgraphTypeAssembler(mapper, loader);
this.graphSupportsTransactions = probeTransactionSupport(g);
}
private static boolean probeTransactionSupport(GraphTraversalSource g) {
// Verify basic connectivity first — propagates loudly if the server is unreachable.
g.inject(0).toList();
// If the server is reachable, any tx failure means the graph doesn't support transactions.
try {
g.tx().commit();
return true;
} catch (Exception ignored) {
return false;
}
}
// --- Public API ---
/**
* Opens a session. If a session is already bound to the current thread (e.g. the caller
* is inside a {@code @Transactional} method), the existing session is borrowed and returned —
* its {@code close()} is a no-op until all borrows are returned.
*/
public ClothoSession openSession() {
ClothoSession existing = SessionContext.get();
if (existing != null) {
existing.borrow();
return existing;
}
return new ClothoSession(g, mapper, loader, persistor, assembler, false, false);
}
/**
* Opens a session with transactional intent. Marks the session so that
* {@link ClothoSession#close()} calls {@code g.tx().commit()} after the batch
* auto-save, and {@link ClothoSession#rollback()} calls {@code g.tx().rollback()}.
*
* <p>With ArcadeDB over the Gremlin WebSocket interface, {@code g.tx().begin()}
* returns a transaction-bound source but subsequent operations on it fail. For this
* reason the session uses the same base {@link GraphTraversalSource} as non-transactional
* sessions. The practical effect is that each Gremlin request is auto-committed by
* ArcadeDB immediately. The auto-save batch at {@code close()} is still a single
* request and therefore atomic as far as ArcadeDB is concerned.
*
* <p>The API is preserved so that {@link ClothoTransactionManager} wires correctly
* into Spring {@code @Transactional}, and borrow semantics (nested
* {@link #openSession()} calls returning the same session) still apply.
*
* <p>Prefer this via Spring's {@code @Transactional} and {@link ClothoTransactionManager}
* rather than calling it directly.
*/
public ClothoSession openTransactionalSession() {
return new ClothoSession(g, mapper, loader, persistor, assembler, true, graphSupportsTransactions);
}
/**
* Returns the session currently bound to this thread.
*
* @throws ClothoException if no session is bound — call only within a {@code @Transactional}
* method or an explicit {@code openSession()} block
*/
public ClothoSession getCurrentSession() {
ClothoSession session = SessionContext.get();
if (session == null) {
throw new ClothoException(
"No active Clotho session — call getCurrentSession() only within a @Transactional method");
}
return session;
}
/** Returns the underlying traversal source. */
public GraphTraversalSource traversal() {
return g;
}
// --- Component accessors: used by ClothoRepository ---
public ElementMapper mapper() { return mapper; }
public SubgraphLoader loader() { return loader; }
public SubgraphPersistor persistor() { return persistor; }
public SubgraphTypeAssembler assembler() { return assembler; }
// --- Builder ---
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private GraphTraversalSource g;
private TypeRegistry registry;
private UnknownTypeBehavior unknownTypeBehavior = UnknownTypeBehavior.STRICT;
private TraversalDirection defaultDirection = TraversalDirection.OUT;
public Builder g(GraphTraversalSource g) {
this.g = g;
return this;
}
public Builder registry(TypeRegistry registry) {
this.registry = registry;
return this;
}
public Builder unknownTypeBehavior(UnknownTypeBehavior unknownTypeBehavior) {
this.unknownTypeBehavior = unknownTypeBehavior;
return this;
}
public Builder defaultDirection(TraversalDirection defaultDirection) {
this.defaultDirection = defaultDirection;
return this;
}
public ClothoSessionFactory build() {
Objects.requireNonNull(g, "g (GraphTraversalSource) is required");
Objects.requireNonNull(registry, "registry (TypeRegistry) is required");
return new ClothoSessionFactory(g, registry, unknownTypeBehavior, defaultDirection);
}
}
}
@@ -0,0 +1,30 @@
package com.binarygolem.clotho.session;
import org.jspecify.annotations.Nullable;
/**
* Holds the {@link ClothoSession} bound to the current thread.
*
* <p>{@code bind} and {@code unbind} are package-private — only {@link ClothoSession}
* calls them. {@link #get()} is public so that {@link
* com.binarygolem.clotho.model.ClothoEntity#notifyFieldChanged} can reach the
* active session without holding a direct reference.
*/
public final class SessionContext {
private static final ThreadLocal<ClothoSession> current = new ThreadLocal<>();
static void bind(ClothoSession session) {
current.set(session);
}
static void unbind() {
current.remove();
}
public static @Nullable ClothoSession get() {
return current.get();
}
private SessionContext() {}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.session;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,6 @@
package com.binarygolem.clotho.fixture;
import com.binarygolem.clotho.annotation.VertexType;
@VertexType("Employee")
public class ScanEmployee extends ScanPerson {}
@@ -0,0 +1,7 @@
package com.binarygolem.clotho.fixture;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.model.ClothoVertex;
@VertexType("Person")
public class ScanPerson extends ClothoVertex {}
@@ -0,0 +1,7 @@
package com.binarygolem.clotho.fixture;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.model.ClothoEdge;
@EdgeType("WORKS_AT")
public class ScanWorksAt extends ClothoEdge {}
@@ -0,0 +1,213 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.Include;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.annotation.Via;
import com.binarygolem.clotho.exception.UnknownTypeException;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.GenericVertex;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ElementMapperTest {
// --- Fixture types ---
@VertexType("Employee")
static class Employee extends ClothoVertex {
@Property("name") String name;
@Property("dept") String department;
int age; // mapped by field name (simple type)
@Include @Via("HAS_ADDRESS")
Object address; // must be skipped
}
@VertexType("HourlyEmployee")
static class HourlyEmployee extends Employee {
@Property("hourlyRate") double hourlyRate;
}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {
@Property("role") String role;
}
enum Status { ACTIVE, INACTIVE }
@VertexType("Contract")
static class Contract extends ClothoVertex {
Status status;
long count;
}
// --- Setup ---
private Graph graph;
private TypeRegistry registry;
private ElementMapper mapper;
@BeforeEach
void setUp() {
graph = TinkerGraph.open();
registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.registerVertex(HourlyEmployee.class)
.registerVertex(Contract.class)
.registerEdge(WorksAt.class)
.build();
mapper = new ElementMapper(registry, UnknownTypeBehavior.STRICT);
}
// --- Vertex mapping ---
@Test
void mapsAnnotatedPropertyFields() {
Vertex v = graph.addVertex(T.label, "Employee", "name", "Alice", "dept", "Engineering");
Employee emp = (Employee) mapper.mapVertex(v);
assertEquals("Alice", emp.name);
assertEquals("Engineering", emp.department);
}
@Test
void mapsFieldByNameWhenNoPropertyAnnotation() {
Vertex v = graph.addVertex(T.label, "Employee", "name", "Bob", "age", 30);
Employee emp = (Employee) mapper.mapVertex(v);
assertEquals(30, emp.age);
}
@Test
void skipsIncludeAnnotatedFields() {
Vertex v = graph.addVertex(T.label, "Employee", "name", "Carol", "address", "ignored");
Employee emp = (Employee) mapper.mapVertex(v);
// address field must not be populated by the ElementMapper — SubgraphLoader does it
assertNull(emp.address);
// "address" should end up in raw properties since the field was skipped
assertEquals("ignored", emp.getProperty("address"));
}
@Test
void setsAridFromElementId() {
Vertex v = graph.addVertex(T.label, "Employee");
Employee emp = (Employee) mapper.mapVertex(v);
assertNotNull(emp.getId());
assertEquals(v.id().toString(), emp.getId().asString());
}
@Test
void storesUnmappedPropertiesAsRaw() {
Vertex v = graph.addVertex(T.label, "Employee", "name", "Dan", "unmapped", "extra");
Employee emp = (Employee) mapper.mapVertex(v);
assertEquals("extra", emp.getProperty("unmapped"));
}
@Test
void returnsMostSpecificSubtype() {
Vertex v = graph.addVertex(T.label, "HourlyEmployee", "name", "Eve", "hourlyRate", 25.5);
ClothoVertex result = mapper.mapVertex(v);
assertInstanceOf(HourlyEmployee.class, result);
assertEquals(25.5, ((HourlyEmployee) result).hourlyRate);
}
@Test
void mapsInheritedFields() {
Vertex v = graph.addVertex(T.label, "HourlyEmployee", "name", "Frank", "dept", "Sales", "hourlyRate", 20.0);
HourlyEmployee emp = (HourlyEmployee) mapper.mapVertex(v);
assertEquals("Frank", emp.name);
assertEquals("Sales", emp.department);
assertEquals(20.0, emp.hourlyRate);
}
// --- Type coercion ---
@Test
void coercesIntegerToLong() {
// TinkerGraph stores 42 as Integer; Contract.count is long
Vertex v = graph.addVertex(T.label, "Contract", "count", 42);
Contract c = (Contract) mapper.mapVertex(v);
assertEquals(42L, c.count);
}
@Test
void coercesStringToEnum() {
Vertex v = graph.addVertex(T.label, "Contract", "status", "ACTIVE");
Contract c = (Contract) mapper.mapVertex(v);
assertEquals(Status.ACTIVE, c.status);
}
// --- Edge mapping ---
@Test
void mapsEdgePropertiesAndVertexIds() {
Vertex out = graph.addVertex(T.label, "Employee");
Vertex in = graph.addVertex(T.label, "Company");
var edge = out.addEdge("WORKS_AT", in, "role", "Engineer");
WorksAt w = (WorksAt) mapper.mapEdge(edge);
assertEquals("Engineer", w.role);
assertNotNull(w.getOutVertexId());
assertNotNull(w.getInVertexId());
assertEquals(out.id().toString(), w.getOutVertexId().asString());
assertEquals(in.id().toString(), w.getInVertexId().asString());
}
@Test
void setsEdgeArid() {
Vertex out = graph.addVertex(T.label, "Employee");
Vertex in = graph.addVertex(T.label, "Company");
var edge = out.addEdge("WORKS_AT", in);
WorksAt w = (WorksAt) mapper.mapEdge(edge);
assertNotNull(w.getId());
}
// --- UnknownTypeBehavior ---
@Test
void strictThrowsForUnknownLabel() {
Vertex v = graph.addVertex(T.label, "Unknown");
assertThrows(UnknownTypeException.class, () -> mapper.mapVertex(v));
}
@Test
void genericReturnsGenericVertex() {
ElementMapper genericMapper = new ElementMapper(registry, UnknownTypeBehavior.GENERIC);
Vertex v = graph.addVertex(T.label, "Unknown", "key", "value");
ClothoVertex result = genericMapper.mapVertex(v);
assertInstanceOf(GenericVertex.class, result);
assertEquals("value", result.getProperty("key"));
}
}
@@ -0,0 +1,246 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Direction;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.Include;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.annotation.Via;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class SubgraphLoaderTest {
// --- Fixture types ---
@VertexType("Employee")
static class Employee extends ClothoVertex {
@Property("name") String name;
@Include @Via("HAS_ADDRESS")
Address address;
@Include @Via("TAGGED_WITH")
List<Tag> tags;
@Include @Via("MANAGED_BY") @Direction(TraversalDirection.IN)
List<Employee> reports;
}
@VertexType("Address")
static class Address extends ClothoVertex {
@Property("street") String street;
}
@VertexType("Tag")
static class Tag extends ClothoVertex {
@Property("value") String value;
}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {
@Property("role") String role;
@OutVertex Employee employee;
@InVertex Company company;
}
@VertexType("Bad")
static class BadVertex extends ClothoVertex {
@Include // missing @Via — triggers validation error in SubgraphLoader
Address address;
}
@VertexType("Company")
static class Company extends ClothoVertex {
@Property("name") String name;
@Include @Via("WORKS_AT") @Direction(TraversalDirection.IN)
List<WorksAt> staff;
}
// --- Setup ---
private Graph graph;
private GraphTraversalSource g;
private TypeRegistry registry;
private ElementMapper mapper;
private SubgraphLoader loader;
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.registerVertex(Address.class)
.registerVertex(Tag.class)
.registerVertex(Company.class)
.registerEdge(WorksAt.class)
.build();
mapper = new ElementMapper(registry, UnknownTypeBehavior.STRICT);
loader = new SubgraphLoader(g, mapper, TraversalDirection.OUT);
}
// --- Single vertex @Include field ---
@Test
void loadsSingleVertexIncludeField() {
Vertex empV = graph.addVertex(T.id, "emp-1", T.label, "Employee", "name", "Alice");
Vertex addrV = graph.addVertex(T.id, "addr-1", T.label, "Address", "street", "1 Main St");
empV.addEdge("HAS_ADDRESS", addrV);
Employee emp = (Employee) mapper.mapVertex(empV);
loader.populate(emp);
assertNotNull(emp.address);
assertEquals("1 Main St", emp.address.street);
}
@Test
void setsNullWhenNoEdgeExistsForSingleField() {
Vertex empV = graph.addVertex(T.id, "emp-2", T.label, "Employee", "name", "Bob");
Employee emp = (Employee) mapper.mapVertex(empV);
loader.populate(emp);
assertNull(emp.address);
}
// --- List vertex @Include field ---
@Test
void loadsListVertexIncludeField() {
Vertex empV = graph.addVertex(T.id, "emp-3", T.label, "Employee", "name", "Carol");
Vertex tag1 = graph.addVertex(T.id, "tag-1", T.label, "Tag", "value", "java");
Vertex tag2 = graph.addVertex(T.id, "tag-2", T.label, "Tag", "value", "graph");
empV.addEdge("TAGGED_WITH", tag1);
empV.addEdge("TAGGED_WITH", tag2);
Employee emp = (Employee) mapper.mapVertex(empV);
loader.populate(emp);
assertEquals(2, emp.tags.size());
assertTrue(emp.tags.stream().map(t -> t.value).toList().containsAll(List.of("java", "graph")));
}
@Test
void setsEmptyListWhenNoEdgesExist() {
Vertex empV = graph.addVertex(T.id, "emp-4", T.label, "Employee", "name", "Dan");
Employee emp = (Employee) mapper.mapVertex(empV);
loader.populate(emp);
assertNotNull(emp.tags);
assertTrue(emp.tags.isEmpty());
}
// --- Edge @Include field with @OutVertex / @InVertex ---
@Test
void loadsEdgeFieldWithAdjacentVertices() {
Vertex empV = graph.addVertex(T.id, "emp-5", T.label, "Employee", "name", "Eve");
Vertex coV = graph.addVertex(T.id, "co-1", T.label, "Company", "name", "Acme");
empV.addEdge("WORKS_AT", coV, "role", "Engineer");
Company company = (Company) mapper.mapVertex(coV);
loader.populate(company);
assertEquals(1, company.staff.size());
WorksAt edge = company.staff.get(0);
assertEquals("Engineer", edge.role);
assertNotNull(edge.employee);
assertEquals("Eve", edge.employee.name);
assertNotNull(edge.company);
assertEquals("Acme", edge.company.name);
}
// --- Direction ---
@Test
void loadsInDirectionField() {
Vertex manager = graph.addVertex(T.id, "mgr-1", T.label, "Employee", "name", "Grace");
Vertex report = graph.addVertex(T.id, "rep-1", T.label, "Employee", "name", "Hank");
report.addEdge("MANAGED_BY", manager);
Employee mgr = (Employee) mapper.mapVertex(manager);
loader.populate(mgr);
assertEquals(1, mgr.reports.size());
assertEquals("Hank", mgr.reports.get(0).name);
}
// --- Multi-hop ---
@Test
void loadsMultiHopBoundary() {
Vertex empV = graph.addVertex(T.id, "emp-6", T.label, "Employee", "name", "Ivy");
Vertex addrV = graph.addVertex(T.id, "addr-2", T.label, "Address", "street", "2 Oak Ave");
empV.addEdge("HAS_ADDRESS", addrV);
Vertex tag = graph.addVertex(T.id, "tag-3", T.label, "Tag", "value", "remote");
empV.addEdge("TAGGED_WITH", tag);
Employee emp = (Employee) mapper.mapVertex(empV);
loader.populate(emp);
assertNotNull(emp.address);
assertEquals("2 Oak Ave", emp.address.street);
assertEquals(1, emp.tags.size());
assertEquals("remote", emp.tags.get(0).value);
}
// --- Cycle detection ---
@Test
void doesNotLoopOnCyclicIncludes() {
// Employee A manages Employee B who manages Employee A
Vertex empA = graph.addVertex(T.id, "emp-a", T.label, "Employee", "name", "A");
Vertex empB = graph.addVertex(T.id, "emp-b", T.label, "Employee", "name", "B");
empB.addEdge("MANAGED_BY", empA); // B is managed by A
empA.addEdge("MANAGED_BY", empB); // A is managed by B (cycle)
Employee a = (Employee) mapper.mapVertex(empA);
assertDoesNotThrow(() -> loader.populate(a));
// A.reports contains B; B.reports contains A but stops there
assertEquals(1, a.reports.size());
assertEquals("B", a.reports.get(0).name);
// B.reports should be populated but A won't be recursed again
assertNotNull(a.reports.get(0).reports);
}
// --- Validation ---
@Test
void throwsWhenViaIsMissing() {
Vertex v = graph.addVertex(T.id, "bad-1", T.label, "Bad");
TypeRegistry reg = TypeRegistry.builder().registerVertex(BadVertex.class).build();
ElementMapper m = new ElementMapper(reg, UnknownTypeBehavior.STRICT);
SubgraphLoader sl = new SubgraphLoader(g, m, TraversalDirection.OUT);
BadVertex bad = (BadVertex) m.mapVertex(v);
assertThrows(ClothoConfigurationException.class, () -> sl.populate(bad));
}
}
@@ -0,0 +1,491 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.Include;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.annotation.Via;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.binarygolem.clotho.annotation.Version;
import com.binarygolem.clotho.exception.OptimisticLockException;
import com.binarygolem.clotho.model.EntityState;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class SubgraphPersistorTest {
// --- Fixture types ---
@VertexType("Employee")
static class Employee extends ClothoVertex {
@Property("name") String name;
@Include @Via("HAS_ADDRESS")
Address address;
@Include @Via("WORKS_AT")
List<WorksAt> workHistory;
}
@VertexType("Address")
static class Address extends ClothoVertex {
@Property("street") String street;
}
@VertexType("Company")
static class Company extends ClothoVertex {
@Property("name") String name;
}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {
@Property("role") String role;
@OutVertex Employee employee;
@InVertex Company company;
}
@SubgraphType
static class EmployeeProfile {
Employee employee;
Address address;
}
static class NotSubgraphType {}
@VertexType("VersionedItem")
static class VersionedItem extends ClothoVertex {
@Property("label") String label;
@Version Long version;
public void setLabel(String v) { this.label = v; notifyFieldChanged("label"); }
}
// --- Setup ---
private Graph graph;
private GraphTraversalSource g;
private SubgraphPersistor persistor;
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
persistor = new SubgraphPersistor(g);
}
// --- Vertex create ---
@Test
void createsNewVertexAndSetsArid() {
Employee emp = new Employee();
emp.name = "Alice";
persistor.persist(emp);
assertNotNull(emp.getId());
assertEquals(1L, g.V().hasLabel("Employee").has("name", "Alice").count().next());
}
@Test
void createsVertexWithoutProperties() {
Employee emp = new Employee();
persistor.persist(emp);
assertNotNull(emp.getId());
assertEquals(1L, g.V().hasLabel("Employee").count().next());
}
// --- Vertex update ---
@Test
void updatesExistingVertex() {
graph.addVertex(T.id, "emp-1", T.label, "Employee", "name", "OldName");
Employee emp = new Employee();
emp.setId(ARID.of("emp-1"));
emp.name = "NewName";
persistor.persist(emp);
String stored = (String) g.V("emp-1").values("name").next();
assertEquals("NewName", stored);
}
// --- Edge create ---
@Test
void createsNewEdgeUsingStoredVertexIds() {
graph.addVertex(T.id, "emp-1", T.label, "Employee", "name", "Bob");
graph.addVertex(T.id, "co-1", T.label, "Company", "name", "Acme");
WorksAt edge = new WorksAt();
edge.setOutVertexId(ARID.of("emp-1"));
edge.setInVertexId(ARID.of("co-1"));
edge.role = "Engineer";
persistor.persist(edge);
assertNotNull(edge.getId());
assertEquals(1L, g.E().hasLabel("WORKS_AT").has("role", "Engineer").count().next());
}
@Test
void createsNewEdgeUsingOutInVertexFields() {
// Vertices already exist; edge references them via @OutVertex/@InVertex fields
// (outVertexId/inVertexId are null — persisting should resolve them from the fields)
graph.addVertex(T.id, "emp-field-1", T.label, "Employee", "name", "Carol");
graph.addVertex(T.id, "co-field-1", T.label, "Company", "name", "Corp");
Employee emp = new Employee();
emp.setId(ARID.of("emp-field-1"));
Company co = new Company();
co.setId(ARID.of("co-field-1"));
WorksAt edge = new WorksAt();
edge.employee = emp; // @OutVertex — ARID resolved from here
edge.company = co; // @InVertex — ARID resolved from here
edge.role = "Manager";
persistor.persist(edge);
assertNotNull(edge.getId());
assertEquals(1L, g.E().hasLabel("WORKS_AT").has("role", "Manager").count().next());
}
// --- Edge update ---
@Test
void updatesExistingEdge() {
var empV = graph.addVertex(T.id, "emp-2", T.label, "Employee");
var coV = graph.addVertex(T.id, "co-2", T.label, "Company");
// Explicit String ID so the edge can be looked up by string ARID later
var e = empV.addEdge("WORKS_AT", coV, T.id, "e-update-1", "role", "OldRole");
String edgeId = e.id().toString();
WorksAt edge = new WorksAt();
edge.setId(ARID.of(edgeId));
edge.role = "NewRole";
persistor.persist(edge);
String stored = (String) g.E(edgeId).values("role").next();
assertEquals("NewRole", stored);
}
// --- Cascade through @Include ---
@Test
void cascadesPersistsIncludedVertex() {
Employee emp = new Employee();
emp.name = "Dan";
Address addr = new Address();
addr.street = "1 Main St";
emp.address = addr;
persistor.persist(emp);
assertNotNull(emp.getId());
assertNotNull(addr.getId());
assertEquals(1L, g.V().hasLabel("Address").has("street", "1 Main St").count().next());
}
@Test
void cascadesPersistsIncludedEdgeList() {
// Use an existing emp with a String ID so g.V(id) round-trips correctly in TinkerGraph.
// (Auto-generated TinkerGraph IDs are Long; String lookup fails. Production ArcadeDB uses String RIDs.)
graph.addVertex(T.id, "emp-cascade", T.label, "Employee", "name", "Eve");
graph.addVertex(T.id, "co-3", T.label, "Company", "name", "Initech");
Employee emp = new Employee();
emp.setId(ARID.of("emp-cascade"));
emp.name = "Eve";
WorksAt edge = new WorksAt();
edge.setInVertexId(ARID.of("co-3"));
edge.role = "Dev";
// outVertexId is null — wireRootIntoEdge should supply emp's ARID
emp.workHistory = List.of(edge);
persistor.persist(emp);
assertNotNull(edge.getId());
assertEquals(emp.getId(), edge.getOutVertexId());
assertEquals(1L, g.E().hasLabel("WORKS_AT").has("role", "Dev").count().next());
}
// --- Identity set prevents double-persist ---
@Test
void doesNotPersistSameObjectTwice() {
Address shared = new Address();
shared.street = "Shared St";
Employee emp1 = new Employee();
emp1.name = "Frank";
emp1.address = shared;
Employee emp2 = new Employee();
emp2.name = "Grace";
emp2.address = shared; // same object reference
persistor.persist(emp1);
// Now manually add emp2's address as the same shared object
// Simulate a second persist call sharing the same address
persistor.persist(emp2);
// shared address should appear exactly once in the graph
// (emp2's persist uses a new identity set so shared gets persisted again — that's OK)
// But within a single persist(emp1) call, the identity set is shared across the cascade
assertEquals(1L, g.V().hasLabel("Address").has("street", "Shared St").count().next()
+ g.V().hasLabel("Address").has("street", "Shared St").count().next() - 1);
}
@Test
void singlePersistCallDeduplicatesSharedObject() {
Address shared = new Address();
shared.street = "42 Loop Rd";
shared.setId(ARID.of("addr-x"));
graph.addVertex(T.id, "addr-x", T.label, "Address", "street", "42 Loop Rd");
Employee emp = new Employee();
emp.name = "Hank";
emp.address = shared;
// persist(emp) should visit shared once even if the cascade tried to reach it multiple times
// Here we just verify it doesn't throw and the ID is still set correctly
assertDoesNotThrow(() -> persistor.persist(emp));
}
// --- @SubgraphType ---
@Test
void persistsSubgraphTypeDelegatingToEntityFields() {
Employee emp = new Employee();
emp.name = "Ivy";
Address addr = new Address();
addr.street = "99 Graph Blvd";
EmployeeProfile profile = new EmployeeProfile();
profile.employee = emp;
profile.address = addr;
persistor.persist(profile);
assertNotNull(emp.getId());
assertNotNull(addr.getId());
assertEquals(1L, g.V().hasLabel("Employee").has("name", "Ivy").count().next());
assertEquals(1L, g.V().hasLabel("Address").has("street", "99 Graph Blvd").count().next());
}
@Test
void throwsWhenPersistingNonSubgraphType() {
assertThrows(ClothoConfigurationException.class,
() -> persistor.persist(new NotSubgraphType()));
}
// --- Missing vertex IDs for edge ---
@Test
void throwsWhenEdgeHasNoResolvableOutVertex() {
WorksAt edge = new WorksAt();
// No outVertexId, no @OutVertex field value, no @InVertex field value
assertThrows(ClothoConfigurationException.class, () -> persistor.persist(edge));
}
// --- persistAllDirty (batch update) ---
@Test
void persistAllDirty_updatesAllDirtyVerticesInSingleCall() {
graph.addVertex(T.id, "e-1", T.label, "Employee", "name", "Alice");
graph.addVertex(T.id, "e-2", T.label, "Employee", "name", "Bob");
Employee alice = new Employee();
alice.setId(ARID.of("e-1"));
alice.name = "Alice Updated";
alice.setState(EntityState.MANAGED);
alice.notifyFieldChanged("name");
Employee bob = new Employee();
bob.setId(ARID.of("e-2"));
bob.name = "Bob Updated";
bob.setState(EntityState.MANAGED);
bob.notifyFieldChanged("name");
persistor.persistAllDirty(List.of(alice, bob), List.of());
assertEquals("Alice Updated", g.V("e-1").values("name").next());
assertEquals("Bob Updated", g.V("e-2").values("name").next());
assertTrue(alice.getDirtyFields().isEmpty(), "dirty fields must be cleared after batch");
assertTrue(bob.getDirtyFields().isEmpty());
}
@Test
void persistAllDirty_updatesVertexAndEdgeTogether() {
var empV = graph.addVertex(T.id, "e-3", T.label, "Employee", "name", "Carol");
var coV = graph.addVertex(T.id, "c-1", T.label, "Company");
empV.addEdge("WORKS_AT", coV, T.id, "wa-1", "role", "Dev");
Employee carol = new Employee();
carol.setId(ARID.of("e-3"));
carol.name = "Carol Updated";
carol.setState(EntityState.MANAGED);
carol.notifyFieldChanged("name");
WorksAt edge = new WorksAt();
edge.setId(ARID.of("wa-1"));
edge.role = "Senior Dev";
edge.setState(EntityState.MANAGED);
edge.notifyFieldChanged("role");
persistor.persistAllDirty(List.of(carol), List.of(edge));
assertEquals("Carol Updated", g.V("e-3").values("name").next());
assertEquals("Senior Dev", g.E("wa-1").values("role").next());
}
@Test
void persistAllDirty_emptyInputIsNoOp() {
assertDoesNotThrow(() -> persistor.persistAllDirty(List.of(), List.of()));
}
@Test
void persistAllDirty_skipsEntitiesWithNoDirtyFields() {
graph.addVertex(T.id, "e-4", T.label, "Employee", "name", "Dave");
Employee dave = new Employee();
dave.setId(ARID.of("e-4"));
dave.name = "Should Not Change";
dave.setState(EntityState.MANAGED);
// No notifyFieldChanged() — getDirtyFields() is empty
persistor.persistAllDirty(List.of(dave), List.of());
assertEquals("Dave", g.V("e-4").values("name").next(), "unchanged name must not be overwritten");
}
// --- @Version OCC ---
@Test
void create_initializesVersionToZero() {
VersionedItem item = new VersionedItem();
item.label = "first";
persistor.persist(item);
assertNotNull(item.getId());
assertEquals(0L, item.version);
// Use label-based lookup — auto-assigned TinkerGraph IDs are Longs, not Strings
Long storedVersion = (Long) g.V().hasLabel("VersionedItem").values("_version").next();
assertEquals(0L, storedVersion);
}
@Test
void update_incrementsVersionAtomically() {
graph.addVertex(T.id, "vi-1", T.label, "VersionedItem", "label", "original", "_version", 0L);
VersionedItem item = new VersionedItem();
item.setId(ARID.of("vi-1"));
item.version = 0L;
item.setState(EntityState.MANAGED);
item.setLabel("updated");
persistor.persist(item);
assertEquals("updated", g.V("vi-1").values("label").next());
assertEquals(1L, g.V("vi-1").values("_version").next());
assertEquals(1L, item.version, "in-memory version must be bumped after successful update");
}
@Test
void update_throwsOptimisticLockExceptionOnVersionMismatch() {
// Graph has version 5 but entity was loaded with version 3
graph.addVertex(T.id, "vi-2", T.label, "VersionedItem", "label", "stale", "_version", 5L);
VersionedItem item = new VersionedItem();
item.setId(ARID.of("vi-2"));
item.version = 3L;
item.setState(EntityState.MANAGED);
item.setLabel("conflict");
assertThrows(OptimisticLockException.class, () -> persistor.persist(item));
// Original value must be unchanged in graph
assertEquals("stale", g.V("vi-2").values("label").next());
assertEquals(5L, g.V("vi-2").values("_version").next());
}
@Test
void persistAllDirty_throwsBeforeAnyWriteOnVersionConflict() {
graph.addVertex(T.id, "vi-3", T.label, "VersionedItem", "label", "A", "_version", 2L);
graph.addVertex(T.id, "vi-4", T.label, "VersionedItem", "label", "B", "_version", 0L);
VersionedItem a = new VersionedItem();
a.setId(ARID.of("vi-3"));
a.version = 1L; // stale — graph has 2
a.setState(EntityState.MANAGED);
a.setLabel("A-updated");
VersionedItem b = new VersionedItem();
b.setId(ARID.of("vi-4"));
b.version = 0L; // correct
b.setState(EntityState.MANAGED);
b.setLabel("B-updated");
assertThrows(OptimisticLockException.class,
() -> persistor.persistAllDirty(List.of(a, b), List.of()));
// Neither entity should have been written (pre-flight throws before any write)
assertEquals("A", g.V("vi-3").values("label").next(), "stale entity must not be written");
assertEquals("B", g.V("vi-4").values("label").next(), "clean entity must also not be written");
}
@Test
void persistAllDirty_incrementsVersionsOnSuccess() {
graph.addVertex(T.id, "vi-5", T.label, "VersionedItem", "label", "X", "_version", 1L);
graph.addVertex(T.id, "vi-6", T.label, "VersionedItem", "label", "Y", "_version", 3L);
VersionedItem x = new VersionedItem();
x.setId(ARID.of("vi-5"));
x.version = 1L;
x.setState(EntityState.MANAGED);
x.setLabel("X-updated");
VersionedItem y = new VersionedItem();
y.setId(ARID.of("vi-6"));
y.version = 3L;
y.setState(EntityState.MANAGED);
y.setLabel("Y-updated");
persistor.persistAllDirty(List.of(x, y), List.of());
assertEquals("X-updated", g.V("vi-5").values("label").next());
assertEquals(2L, g.V("vi-5").values("_version").next());
assertEquals(2L, x.version, "in-memory version must be bumped");
assertEquals("Y-updated", g.V("vi-6").values("label").next());
assertEquals(4L, g.V("vi-6").values("_version").next());
assertEquals(4L, y.version);
}
}
@@ -0,0 +1,160 @@
package com.binarygolem.clotho.mapping;
import com.binarygolem.clotho.annotation.Alias;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class SubgraphTypeAssemblerTest {
// --- Fixture types ---
static class NotASubgraphType {}
@VertexType("Employee")
static class Employee extends ClothoVertex {
@Property("name") String name;
}
@VertexType("Department")
static class Department extends ClothoVertex {
@Property("deptName") String deptName;
}
@SubgraphType
static class EmployeeProfile {
Employee employee;
@Alias("dept")
Department department;
List<Employee> colleagues;
}
// --- Setup ---
private Graph graph;
private GraphTraversalSource g;
private TypeRegistry registry;
private ElementMapper mapper;
private SubgraphLoader loader;
private SubgraphTypeAssembler assembler;
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.registerVertex(Department.class)
.build();
mapper = new ElementMapper(registry, UnknownTypeBehavior.STRICT);
loader = new SubgraphLoader(g, mapper, TraversalDirection.OUT);
assembler = new SubgraphTypeAssembler(mapper, loader);
}
// --- Field-name matching ---
@Test
void assemblsVertexByFieldName() {
Vertex empV = graph.addVertex(T.id, "emp-1", T.label, "Employee", "name", "Alice");
Map<String, Object> result = Map.of("employee", empV);
EmployeeProfile profile = assembler.assemble(EmployeeProfile.class, result);
assertNotNull(profile.employee);
assertEquals("Alice", profile.employee.name);
}
// --- @Alias override ---
@Test
void assemblsVertexByAlias() {
Vertex deptV = graph.addVertex(T.id, "dept-1", T.label, "Department", "deptName", "Engineering");
Map<String, Object> result = Map.of("dept", deptV);
EmployeeProfile profile = assembler.assemble(EmployeeProfile.class, result);
assertNotNull(profile.department);
assertEquals("Engineering", profile.department.deptName);
}
// --- Missing key ---
@Test
void leavesFieldNullWhenKeyAbsent() {
Vertex empV = graph.addVertex(T.id, "emp-2", T.label, "Employee", "name", "Bob");
Map<String, Object> result = Map.of("employee", empV);
// "dept" key absent
EmployeeProfile profile = assembler.assemble(EmployeeProfile.class, result);
assertNull(profile.department);
}
// --- List value ---
@Test
void assemblsListOfVertices() {
Vertex c1 = graph.addVertex(T.id, "c-1", T.label, "Employee", "name", "Carol");
Vertex c2 = graph.addVertex(T.id, "c-2", T.label, "Employee", "name", "Dan");
Map<String, Object> result = Map.of("colleagues", List.of(c1, c2));
EmployeeProfile profile = assembler.assemble(EmployeeProfile.class, result);
assertEquals(2, profile.colleagues.size());
assertTrue(profile.colleagues.stream().map(e -> e.name).toList()
.containsAll(List.of("Carol", "Dan")));
}
// --- Validation ---
@Test
void throwsWhenClassLacksSubgraphTypeAnnotation() {
assertThrows(ClothoConfigurationException.class,
() -> assembler.assemble(NotASubgraphType.class, Map.of()));
}
// --- Full round-trip ---
@Test
void assemblesAllFieldsFromSelectResult() {
Vertex empV = graph.addVertex(T.id, "emp-3", T.label, "Employee", "name", "Eve");
Vertex deptV = graph.addVertex(T.id, "dept-2", T.label, "Department", "deptName", "Research");
Vertex c1 = graph.addVertex(T.id, "c-3", T.label, "Employee", "name", "Frank");
Map<String, Object> result = Map.of(
"employee", empV,
"dept", deptV,
"colleagues", List.of(c1)
);
EmployeeProfile profile = assembler.assemble(EmployeeProfile.class, result);
assertEquals("Eve", profile.employee.name);
assertEquals("Research", profile.department.deptName);
assertEquals(1, profile.colleagues.size());
assertEquals("Frank", profile.colleagues.get(0).name);
}
}
@@ -0,0 +1,240 @@
package com.binarygolem.clotho.registry;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoConfigurationException;
import com.binarygolem.clotho.exception.UnknownTypeException;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.GenericEdge;
import com.binarygolem.clotho.model.GenericVertex;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class TypeRegistryTest {
// --- Sample types ---
@VertexType("Person")
static class Person extends ClothoVertex {}
@VertexType("Employee")
static class Employee extends Person {}
@VertexType("HourlyEmployee")
static class HourlyEmployee extends Employee {}
// parentLabel escape hatch: Java doesn't extend Employee but ArcadeDB does
@VertexType(value = "OffSiteEmployee", parentLabel = "Employee")
static class OffSiteEmployee extends ClothoVertex {}
// Diamond: in ArcadeDB ContractEmployee extends both Employee and Contractor
@VertexType("Contractor")
static class Contractor extends Person {}
@VertexType(value = "ContractEmployee", additionalParents = {"Contractor"})
static class ContractEmployee extends Employee {}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {}
// --- Basic registration and lookup ---
@Test
void registersVertexByLabel() {
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.build();
assertEquals(Employee.class, registry.findVertex("Employee").orElseThrow());
}
@Test
void registersEdgeByLabel() {
TypeRegistry registry = TypeRegistry.builder()
.registerEdge(WorksAt.class)
.build();
assertEquals(WorksAt.class, registry.findEdge("WORKS_AT").orElseThrow());
}
@Test
void returnsEmptyForUnknownLabel() {
TypeRegistry registry = TypeRegistry.builder().build();
assertTrue(registry.findVertex("Nobody").isEmpty());
assertTrue(registry.findEdge("NOBODY").isEmpty());
}
@Test
void exposesRegisteredLabels() {
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Person.class)
.registerVertex(Employee.class)
.registerEdge(WorksAt.class)
.build();
assertTrue(registry.vertexLabels().containsAll(java.util.Set.of("Person", "Employee")));
assertTrue(registry.edgeLabels().contains("WORKS_AT"));
}
// --- UnknownTypeBehavior ---
@Test
void strictThrowsOnUnknownVertex() {
TypeRegistry registry = TypeRegistry.builder().build();
assertThrows(UnknownTypeException.class,
() -> registry.resolveVertex("Ghost", UnknownTypeBehavior.STRICT));
}
@Test
void strictThrowsOnUnknownEdge() {
TypeRegistry registry = TypeRegistry.builder().build();
assertThrows(UnknownTypeException.class,
() -> registry.resolveEdge("GHOST", UnknownTypeBehavior.STRICT));
}
@Test
void genericReturnsGenericVertex() {
TypeRegistry registry = TypeRegistry.builder().build();
assertEquals(GenericVertex.class,
registry.resolveVertex("Unknown", UnknownTypeBehavior.GENERIC));
}
@Test
void genericReturnsGenericEdge() {
TypeRegistry registry = TypeRegistry.builder().build();
assertEquals(GenericEdge.class,
registry.resolveEdge("UNKNOWN", UnknownTypeBehavior.GENERIC));
}
// --- NEAREST_ANCESTOR via Java hierarchy ---
@Test
void nearestAncestorFindsDirectParent() {
// HourlyEmployee → Employee → Person; only Person and Employee registered
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Person.class)
.registerVertex(Employee.class)
.registerVertex(HourlyEmployee.class)
.build();
// HourlyEmployee IS registered, should return it directly
assertEquals(HourlyEmployee.class,
registry.resolveVertex("HourlyEmployee", UnknownTypeBehavior.NEAREST_ANCESTOR));
}
@Test
void nearestAncestorFindsAncestorForUnregisteredLabel() {
// Register Person and Employee but NOT HourlyEmployee.
// Simulate "HourlyEmployee" arriving from DB without a Java class.
// TypeRegistry can only resolve this if it knows the label's parents —
// which requires the label to be in the registered hierarchy.
// For a fully unknown label, NEAREST_ANCESTOR falls back to GenericVertex.
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Person.class)
.registerVertex(Employee.class)
.build();
assertEquals(GenericVertex.class,
registry.resolveVertex("HourlyEmployee", UnknownTypeBehavior.NEAREST_ANCESTOR));
}
// --- parentLabel escape hatch ---
@Test
void parentLabelOverridesJavaHierarchy() {
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.registerVertex(OffSiteEmployee.class) // Java: ClothoVertex, ArcadeDB: Employee
.build();
// OffSiteEmployee declares parentLabel = "Employee", so its ancestor is Employee
Class<? extends ClothoVertex> resolved =
registry.resolveVertex("OffSiteEmployee", UnknownTypeBehavior.NEAREST_ANCESTOR);
assertEquals(OffSiteEmployee.class, resolved);
}
// --- additionalParents (diamond inheritance) ---
@Test
void additionalParentsAreRecorded() {
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Person.class)
.registerVertex(Employee.class)
.registerVertex(Contractor.class)
.registerVertex(ContractEmployee.class)
.build();
// ContractEmployee is registered — resolves directly
assertEquals(ContractEmployee.class,
registry.resolveVertex("ContractEmployee", UnknownTypeBehavior.NEAREST_ANCESTOR));
}
// --- Validation ---
@Test
void duplicateLabelThrows() {
@VertexType("Employee")
class AnotherEmployee extends ClothoVertex {}
TypeRegistry.Builder builder = TypeRegistry.builder()
.registerVertex(Employee.class);
assertThrows(ClothoConfigurationException.class,
() -> builder.registerVertex(AnotherEmployee.class));
}
@Test
void missingAnnotationOnVertexThrows() {
class Unannotated extends ClothoVertex {}
assertThrows(ClothoConfigurationException.class,
() -> TypeRegistry.builder().registerVertex(Unannotated.class));
}
@Test
void missingAnnotationOnEdgeThrows() {
class Unannotated extends ClothoEdge {}
assertThrows(ClothoConfigurationException.class,
() -> TypeRegistry.builder().registerEdge(Unannotated.class));
}
@Test
void unknownTypeExceptionCarriesLabel() {
TypeRegistry registry = TypeRegistry.builder().build();
UnknownTypeException ex = assertThrows(UnknownTypeException.class,
() -> registry.resolveVertex("Missing", UnknownTypeBehavior.STRICT));
assertEquals("Missing", ex.getLabel());
}
// --- Classpath scan ---
@Test
void scanFindsAnnotatedClassesInPackage() {
TypeRegistry registry = TypeRegistry.scan("com.binarygolem.clotho.fixture");
assertTrue(registry.vertexLabels().contains("Person"));
assertTrue(registry.vertexLabels().contains("Employee"));
assertTrue(registry.edgeLabels().contains("WORKS_AT"));
}
@Test
void scanInfersJavaHierarchyFromFixtures() {
// ScanEmployee extends ScanPerson (@VertexType("Person")), so Employee's parent
// should be inferred as "Person" without any explicit parentLabel.
TypeRegistry registry = TypeRegistry.scan("com.binarygolem.clotho.fixture");
// Employee is registered directly, so it resolves to itself
assertEquals(com.binarygolem.clotho.fixture.ScanEmployee.class,
registry.resolveVertex("Employee", UnknownTypeBehavior.NEAREST_ANCESTOR));
}
}
@@ -0,0 +1,422 @@
package com.binarygolem.clotho.repository;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.EntityState;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class ClothoRepositoryTest {
// --- Fixture types ---
@VertexType("Employee")
static class Employee extends ClothoVertex {
@Property("name") String name;
@Property("dept") String dept;
void setName(String name) {
this.name = name;
notifyFieldChanged("name");
}
}
@VertexType("Company")
static class Company extends ClothoVertex {
@Property("name") String name;
}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {
@Property("role") String role;
@OutVertex Employee employee;
@InVertex Company company;
}
@SubgraphType
static class EmployeeCompanyPair {
Employee employee;
Company company;
}
// --- Concrete repository ---
static class EmployeeRepo extends ClothoRepository<Employee> {
EmployeeRepo(ClothoSessionFactory factory) { super(factory); }
List<Employee> findByDept(String dept) {
return execute(g().V().has("Employee", "dept", dept));
}
List<Employee> findSenior() {
return findAll(t -> t.has("dept", "Engineering"));
}
long countByDept(String dept) {
return this.<Long>executeRaw(
g().V().hasLabel("Employee").has("dept", dept).count()
).get(0);
}
List<EmployeeCompanyPair> loadPairs(String employeeId) {
return executeSubgraph(EmployeeCompanyPair.class,
g().V(employeeId).as("employee")
.out("WORKS_AT").as("company")
.select("employee", "company")
);
}
}
static class WorksAtRepo extends ClothoRepository<WorksAt> {
WorksAtRepo(ClothoSessionFactory factory) { super(factory); }
}
// --- Setup ---
private Graph graph;
private GraphTraversalSource g;
private ClothoSessionFactory factory;
private EmployeeRepo employeeRepo;
private WorksAtRepo edgeRepo;
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Employee.class)
.registerVertex(Company.class)
.registerEdge(WorksAt.class)
.build();
factory = ClothoSessionFactory.builder()
.g(g)
.registry(registry)
.unknownTypeBehavior(UnknownTypeBehavior.STRICT)
.defaultDirection(TraversalDirection.OUT)
.build();
employeeRepo = new EmployeeRepo(factory);
edgeRepo = new WorksAtRepo(factory);
}
// --- execute ---
@Test
void executeReturnsMatchingVertices() {
graph.addVertex(T.id, "e-1", T.label, "Employee", "name", "Alice", "dept", "Engineering");
graph.addVertex(T.id, "e-2", T.label, "Employee", "name", "Bob", "dept", "Marketing");
List<Employee> result = employeeRepo.findByDept("Engineering");
assertEquals(1, result.size());
assertEquals("Alice", result.get(0).name);
}
@Test
void executeWithFilterAppliesFilter() {
graph.addVertex(T.id, "e-3", T.label, "Employee", "name", "Carol", "dept", "Engineering");
graph.addVertex(T.id, "e-4", T.label, "Employee", "name", "Dave", "dept", "HR");
List<Employee> result = employeeRepo.findSenior();
assertEquals(1, result.size());
assertEquals("Carol", result.get(0).name);
}
@Test
void executeReturnsEmptyListWhenNoMatch() {
graph.addVertex(T.id, "e-5", T.label, "Employee", "name", "Eve", "dept", "Sales");
List<Employee> result = employeeRepo.findByDept("Nonexistent");
assertTrue(result.isEmpty());
}
// --- executeRaw ---
@Test
void executeRawReturnsScalarCount() {
graph.addVertex(T.id, "e-6", T.label, "Employee", "name", "Frank", "dept", "Engineering");
graph.addVertex(T.id, "e-7", T.label, "Employee", "name", "Grace", "dept", "Engineering");
graph.addVertex(T.id, "e-8", T.label, "Employee", "name", "Hank", "dept", "Marketing");
long count = employeeRepo.countByDept("Engineering");
assertEquals(2L, count);
}
// --- executeSubgraph ---
@Test
void executeSubgraphAssemblesSubgraphType() {
var empV = graph.addVertex(T.id, "e-9", T.label, "Employee", "name", "Ivy");
var coV = graph.addVertex(T.id, "c-1", T.label, "Company", "name", "Acme");
empV.addEdge("WORKS_AT", coV);
List<EmployeeCompanyPair> pairs = employeeRepo.loadPairs("e-9");
assertEquals(1, pairs.size());
assertEquals("Ivy", pairs.get(0).employee.name);
assertEquals("Acme", pairs.get(0).company.name);
}
// --- findAll ---
@Test
void findAllReturnsAllEntities() {
graph.addVertex(T.id, "e-10", T.label, "Employee", "name", "Jack");
graph.addVertex(T.id, "e-11", T.label, "Employee", "name", "Kate");
List<Employee> all = employeeRepo.findAll();
assertEquals(2, all.size());
}
@Test
void findAllWithFilterReturnsFiltered() {
graph.addVertex(T.id, "e-12", T.label, "Employee", "name", "Leo", "dept", "Engineering");
graph.addVertex(T.id, "e-13", T.label, "Employee", "name", "Mia", "dept", "Engineering");
graph.addVertex(T.id, "e-14", T.label, "Employee", "name", "Nick", "dept", "Marketing");
List<Employee> result = employeeRepo.findAll(t -> t.has("dept", "Engineering"));
assertEquals(2, result.size());
}
// --- findById ---
@Test
void findByIdReturnsEntity() {
graph.addVertex(T.id, "e-15", T.label, "Employee", "name", "Olivia");
Employee found = employeeRepo.findById(ARID.of("e-15"));
assertNotNull(found);
assertEquals("Olivia", found.name);
}
@Test
void findByIdReturnsNullWhenNotFound() {
assertNull(employeeRepo.findById(ARID.of("does-not-exist")));
}
// --- count ---
@Test
void countReturnsTotal() {
graph.addVertex(T.id, "e-16", T.label, "Employee", "name", "Pat");
graph.addVertex(T.id, "e-17", T.label, "Employee", "name", "Quinn");
assertEquals(2L, employeeRepo.count());
}
@Test
void countWithFilterReturnsFilteredTotal() {
graph.addVertex(T.id, "e-18", T.label, "Employee", "name", "Ray", "dept", "Engineering");
graph.addVertex(T.id, "e-19", T.label, "Employee", "name", "Sara", "dept", "HR");
long count = employeeRepo.count(t -> t.has("dept", "Engineering"));
assertEquals(1L, count);
}
// --- findWithPagination ---
@Test
void findWithPaginationReturnsPage() {
graph.addVertex(T.id, "e-20", T.label, "Employee", "name", "Tina");
graph.addVertex(T.id, "e-21", T.label, "Employee", "name", "Uma");
graph.addVertex(T.id, "e-22", T.label, "Employee", "name", "Vince");
List<Employee> page = employeeRepo.findWithPagination(0, 2);
assertEquals(2, page.size());
}
// --- save ---
@Test
void saveCreatesNewVertex() {
Employee emp = new Employee();
emp.name = "Wendy";
emp.dept = "Finance";
employeeRepo.save(emp);
assertNotNull(emp.getId());
assertEquals(1L, g.V().hasLabel("Employee").has("name", "Wendy").count().next());
}
@Test
void saveUpdatesExistingVertex() {
graph.addVertex(T.id, "e-23", T.label, "Employee", "name", "OldName");
Employee emp = new Employee();
emp.setId(ARID.of("e-23"));
emp.name = "NewName";
employeeRepo.save(emp);
assertEquals("NewName", g.V("e-23").values("name").next());
}
// --- delete ---
@Test
void deleteRemovesEntityFromGraph() {
graph.addVertex(T.id, "e-24", T.label, "Employee", "name", "Xavier");
Employee emp = new Employee();
emp.setId(ARID.of("e-24"));
employeeRepo.delete(emp);
assertEquals(0L, g.V("e-24").count().next());
}
@Test
void deleteByAridRemovesFromGraph() {
graph.addVertex(T.id, "e-25", T.label, "Employee", "name", "Yara");
employeeRepo.delete(ARID.of("e-25"));
assertEquals(0L, g.V("e-25").count().next());
}
@Test
void deleteThrowsWhenEntityHasNoId() {
Employee emp = new Employee();
assertThrows(ClothoException.class, () -> employeeRepo.delete(emp));
}
// --- entity class inference ---
@Test
void entityClassIsCorrectlyInferred() {
assertEquals(Employee.class, employeeRepo.getEntityClass());
}
@Test
void edgeRepositoryInfersEdgeClass() {
assertEquals(WorksAt.class, edgeRepo.getEntityClass());
}
// --- edge repository ---
@Test
void edgeRepositoryFindAll() {
var empV = graph.addVertex(T.id, "e-26", T.label, "Employee");
var coV = graph.addVertex(T.id, "c-2", T.label, "Company");
empV.addEdge("WORKS_AT", coV, T.id, "wa-1", "role", "Dev");
List<WorksAt> edges = edgeRepo.findAll();
assertEquals(1, edges.size());
assertEquals("Dev", edges.get(0).role);
}
// --- execute with session ---
@Test
void execute_withSession_returnsManaged() {
graph.addVertex(T.id, "e-30", T.label, "Employee", "name", "Zara", "dept", "Engineering");
try (ClothoSession session = factory.openSession()) {
List<Employee> results = employeeRepo.execute(session,
g.V().has("Employee", "name", "Zara"));
assertEquals(1, results.size());
assertEquals(EntityState.MANAGED, results.get(0).getState());
}
}
@Test
void execute_withSession_dirtyTrackingFires() {
graph.addVertex(T.id, "e-31", T.label, "Employee", "name", "Aaron", "dept", "Engineering");
try (ClothoSession session = factory.openSession()) {
List<Employee> results = employeeRepo.execute(session,
g.V().has("Employee", "name", "Aaron"));
Employee emp = results.get(0);
emp.setName("Aaron Updated");
assertFalse(emp.getDirtyFields().isEmpty());
assertTrue(emp.getDirtyFields().contains("name"));
}
}
@Test
void execute_withSession_registersAllResults() {
graph.addVertex(T.id, "e-32", T.label, "Employee", "name", "Beth", "dept", "HR");
graph.addVertex(T.id, "e-33", T.label, "Employee", "name", "Carl", "dept", "HR");
graph.addVertex(T.id, "e-34", T.label, "Employee", "name", "Dana", "dept", "IT");
try (ClothoSession session = factory.openSession()) {
List<Employee> hrStaff = employeeRepo.execute(session,
employeeRepo.g().V().has("Employee", "dept", "HR"));
assertEquals(2, hrStaff.size());
assertTrue(hrStaff.stream().allMatch(e -> e.getState() == EntityState.MANAGED));
}
}
@Test
void execute_withSession_returnsCachedInstanceForDuplicateVertex() {
graph.addVertex(T.id, "e-40", T.label, "Employee", "name", "Zoe", "dept", "Engineering");
try (ClothoSession session = factory.openSession()) {
Employee loaded = session.load(Employee.class, ARID.of("e-40"));
List<Employee> results = employeeRepo.execute(session,
g.V().has("Employee", "dept", "Engineering"));
assertEquals(1, results.size());
assertSame(loaded, results.get(0));
}
}
@Test
void execute_withSession_filterOverload_returnsManaged() {
graph.addVertex(T.id, "e-35", T.label, "Employee", "name", "Eve", "dept", "Finance");
graph.addVertex(T.id, "e-36", T.label, "Employee", "name", "Frank", "dept", "Engineering");
try (ClothoSession session = factory.openSession()) {
List<Employee> results = employeeRepo.execute(session,
employeeRepo.allEntities(), t -> t.has("dept", "Finance"));
assertEquals(1, results.size());
assertEquals(EntityState.MANAGED, results.get(0).getState());
assertEquals("Eve", results.get(0).name);
}
}
}
@@ -0,0 +1,74 @@
package com.binarygolem.clotho.session;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ClothoSessionFactoryTest {
@AfterEach
void tearDown() {
ClothoSession bound = SessionContext.get();
if (bound != null) bound.rollback();
}
@Test
void openSessionReturnsSession() {
ClothoSessionFactory factory = ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.build();
assertNotNull(factory.openSession());
}
@Test
void openSession_whenNoSessionBound_createsNewSession() {
ClothoSessionFactory factory = ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.build();
ClothoSession session = factory.openSession();
assertNotNull(session);
assertFalse(session.isTransactional());
}
@Test
void openSession_whenSessionAlreadyBound_returnsSameInstance() {
ClothoSessionFactory factory = ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.build();
ClothoSession a = factory.openSession();
ClothoSession b = factory.openSession();
assertSame(a, b, "openSession() must borrow the existing session when one is already bound");
b.close(); // decrement borrow count (a is still open)
}
@Test
void defaultsApplyWhenNotExplicitlySet() {
assertDoesNotThrow(() -> ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.build()
.openSession());
}
@Test
void explicitConfigIsAccepted() {
assertDoesNotThrow(() -> ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.unknownTypeBehavior(UnknownTypeBehavior.GENERIC)
.defaultDirection(TraversalDirection.IN)
.build()
.openSession());
}
}
@@ -0,0 +1,263 @@
package com.binarygolem.clotho.session;
import com.binarygolem.clotho.annotation.EdgeType;
import com.binarygolem.clotho.annotation.InVertex;
import com.binarygolem.clotho.annotation.OutVertex;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.SubgraphType;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoEdge;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class ClothoSessionTest {
// --- Fixture types ---
@VertexType("Person")
static class Person extends ClothoVertex {
@Property("name") String name;
}
@VertexType("Company")
static class Company extends ClothoVertex {
@Property("name") String name;
}
@EdgeType("WORKS_AT")
static class WorksAt extends ClothoEdge {
@Property("role") String role;
@OutVertex Person person;
@InVertex Company company;
}
@SubgraphType
static class PersonProfile {
Person person;
Company company;
}
// --- Setup ---
private Graph graph;
private GraphTraversalSource g;
private ClothoSession session;
@AfterEach
void tearDown() {
if (session != null && SessionContext.get() != null) {
session.rollback();
}
}
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_EDGE_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Person.class)
.registerVertex(Company.class)
.registerEdge(WorksAt.class)
.build();
session = ClothoSessionFactory.builder()
.g(g)
.registry(registry)
.unknownTypeBehavior(UnknownTypeBehavior.STRICT)
.defaultDirection(TraversalDirection.OUT)
.build()
.openSession();
}
// --- load ---
@Test
void loadsVertexById() {
graph.addVertex(T.id, "p-1", T.label, "Person", "name", "Alice");
Person person = session.load(Person.class, ARID.of("p-1"));
assertNotNull(person);
assertEquals("Alice", person.name);
assertEquals(ARID.of("p-1"), person.getId());
}
@Test
void returnsCachedInstanceOnSecondLoad() {
graph.addVertex(T.id, "p-2", T.label, "Person", "name", "Bob");
Person first = session.load(Person.class, ARID.of("p-2"));
Person second = session.load(Person.class, ARID.of("p-2"));
assertSame(first, second);
}
@Test
void throwsWhenVertexNotFound() {
assertThrows(ClothoException.class,
() -> session.load(Person.class, ARID.of("no-such-id")));
}
// --- save vertex ---
@Test
void savePersistsNewVertex() {
Person person = new Person();
person.name = "Carol";
session.save(person);
assertNotNull(person.getId());
assertEquals(1L, g.V().hasLabel("Person").has("name", "Carol").count().next());
}
@Test
void saveUpdatesExistingVertex() {
graph.addVertex(T.id, "p-3", T.label, "Person", "name", "OldName");
Person person = new Person();
person.setId(ARID.of("p-3"));
person.name = "NewName";
session.save(person);
assertEquals("NewName", g.V("p-3").values("name").next());
}
@Test
void saveVertexAddsToIdentityMap() {
Person person = new Person();
person.name = "Dan";
session.save(person);
// load() should return the same Java object from the identity map
Person fromCache = session.load(Person.class, person.getId());
assertSame(person, fromCache);
}
// --- save edge ---
@Test
void savePersistsNewEdge() {
graph.addVertex(T.id, "p-4", T.label, "Person");
graph.addVertex(T.id, "c-1", T.label, "Company");
WorksAt edge = new WorksAt();
edge.setOutVertexId(ARID.of("p-4"));
edge.setInVertexId(ARID.of("c-1"));
edge.role = "Engineer";
session.save(edge);
assertNotNull(edge.getId());
assertEquals(1L, g.E().hasLabel("WORKS_AT").has("role", "Engineer").count().next());
}
// --- save @SubgraphType ---
@Test
void saveDelegatesToSubgraphTypeFields() {
Person person = new Person();
person.name = "Eve";
Company company = new Company();
company.name = "Acme";
PersonProfile profile = new PersonProfile();
profile.person = person;
profile.company = company;
session.save(profile);
assertNotNull(person.getId());
assertNotNull(company.getId());
assertEquals(1L, g.V().hasLabel("Person").has("name", "Eve").count().next());
assertEquals(1L, g.V().hasLabel("Company").has("name", "Acme").count().next());
}
// --- delete ---
@Test
void deletesVertexFromGraph() {
graph.addVertex(T.id, "p-5", T.label, "Person", "name", "Frank");
Person person = session.load(Person.class, ARID.of("p-5"));
session.delete(person);
assertEquals(0L, g.V("p-5").count().next());
}
@Test
void deleteEvictsFromIdentityMap() {
graph.addVertex(T.id, "p-6", T.label, "Person", "name", "Grace");
Person person = session.load(Person.class, ARID.of("p-6"));
session.delete(person);
// Re-add the vertex with a different name; reload must hit the graph, not stale cache
graph.addVertex(T.id, "p-6", T.label, "Person", "name", "Grace2");
Person reloaded = session.load(Person.class, ARID.of("p-6"));
assertEquals("Grace2", reloaded.name);
}
@Test
void deleteThrowsWhenEntityHasNoId() {
Person person = new Person();
assertThrows(ClothoException.class, () -> session.delete(person));
}
// --- clearCache ---
@Test
void clearCacheForcesFreshLoad() {
graph.addVertex(T.id, "p-7", T.label, "Person", "name", "Hank");
Person first = session.load(Person.class, ARID.of("p-7"));
session.clearCache();
Person second = session.load(Person.class, ARID.of("p-7"));
assertNotSame(first, second);
assertEquals("Hank", second.name);
}
// --- assemble ---
@Test
void assemblesSubgraphTypeFromMap() {
var empV = graph.addVertex(T.id, "p-8", T.label, "Person", "name", "Ivy");
var coV = graph.addVertex(T.id, "c-2", T.label, "Company", "name", "Corp");
Map<String, Object> result = new HashMap<>();
result.put("person", empV);
result.put("company", coV);
PersonProfile profile = session.assemble(PersonProfile.class, result);
assertNotNull(profile.person);
assertEquals("Ivy", profile.person.name);
assertNotNull(profile.company);
assertEquals("Corp", profile.company.name);
}
}
@@ -0,0 +1,181 @@
package com.binarygolem.clotho.session;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.exception.ClothoException;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.model.ClothoVertex;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import com.binarygolem.clotho.registry.TypeRegistry;
import org.apache.commons.configuration2.BaseConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
class ClothoSessionTransactionTest {
@VertexType("Widget")
static class Widget extends ClothoVertex {
@Property("label") String label;
void setLabel(String label) {
this.label = label;
notifyFieldChanged("label");
}
}
private Graph graph;
private GraphTraversalSource g;
private ClothoSessionFactory factory;
private boolean graphSupportsTransactions;
@AfterEach
void tearDown() {
ClothoSession bound = SessionContext.get();
if (bound != null) bound.rollback();
}
@BeforeEach
void setUp() {
Configuration conf = new BaseConfiguration();
conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_VERTEX_ID_MANAGER, "ANY");
graph = TinkerGraph.open(conf);
g = graph.traversal();
TypeRegistry registry = TypeRegistry.builder()
.registerVertex(Widget.class)
.build();
factory = ClothoSessionFactory.builder()
.g(g)
.registry(registry)
.unknownTypeBehavior(UnknownTypeBehavior.STRICT)
.defaultDirection(TraversalDirection.OUT)
.build();
graphSupportsTransactions = graph.features().graph().supportsTransactions();
}
// --- isTransactional ---
@Test
void openSession_isNotTransactional() {
try (ClothoSession session = factory.openSession()) {
assertFalse(session.isTransactional());
}
}
@Test
void openTransactionalSession_isTransactional() {
assumeTrue(graphSupportsTransactions, "graph does not support transactions");
ClothoSession session = factory.openTransactionalSession();
assertTrue(session.isTransactional());
session.rollback();
}
// --- borrow / close ---
@Test
void openSession_whenSessionAlreadyBound_returnsSameInstance() {
try (ClothoSession outer = factory.openSession()) {
ClothoSession inner = factory.openSession();
assertSame(outer, inner);
inner.close(); // no-op: borrow count still > 0
assertNotNull(SessionContext.get(), "session must still be bound after borrowed close");
} // outer close: real flush
assertNull(SessionContext.get(), "session must be unbound after final close");
}
@Test
void borrowedSession_closeIsNoOpUntilAllBorrowsReturned() {
graph.addVertex(T.id, "w-1", T.label, "Widget", "label", "original");
try (ClothoSession outer = factory.openSession()) {
Widget w = outer.load(Widget.class, ARID.of("w-1"));
w.setLabel("modified");
ClothoSession borrowed = factory.openSession();
assertSame(outer, borrowed);
borrowed.close(); // borrow close — must NOT flush
// Dirty field must still be present (flush not yet triggered)
assertFalse(w.getDirtyFields().isEmpty());
}
// Real close: auto-save fires, persists "modified"
assertEquals("modified", g.V("w-1").values("label").next());
}
// --- rollback ---
@Test
void rollback_unbindsSession() {
ClothoSession session = factory.openSession();
assertNotNull(SessionContext.get());
session.rollback();
assertNull(SessionContext.get());
}
@Test
void rollback_preventsAutoSave() {
graph.addVertex(T.id, "w-2", T.label, "Widget", "label", "before");
ClothoSession session = factory.openSession();
Widget w = session.load(Widget.class, ARID.of("w-2"));
w.setLabel("after");
session.rollback(); // discard without saving
assertEquals("before", g.V("w-2").values("label").next());
}
// --- getCurrentSession ---
@Test
void getCurrentSession_throwsWhenNoSessionBound() {
assertNull(SessionContext.get(), "precondition: no session before test");
assertThrows(ClothoException.class, () -> factory.getCurrentSession());
}
@Test
void getCurrentSession_returnsBoundSession() {
try (ClothoSession session = factory.openSession()) {
assertSame(session, factory.getCurrentSession());
}
}
// --- transactional session ---
@Test
void transactionalSession_closeSavesChanges() {
assumeTrue(graphSupportsTransactions, "graph does not support transactions");
Widget w = new Widget();
w.setLabel("saved-tx");
ClothoSession session = factory.openTransactionalSession();
session.save(w);
session.close();
assertNotNull(w.getId());
assertEquals(1L, g.V().hasLabel("Widget").has("label", "saved-tx").count().next());
}
@Test
void transactionalSession_rollbackDiscardsSave() {
assumeTrue(graphSupportsTransactions, "graph does not support transactions");
Widget w = new Widget();
w.setLabel("not-saved");
ClothoSession session = factory.openTransactionalSession();
session.save(w);
session.rollback();
assertNull(SessionContext.get());
}
}