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
+39
View File
@@ -0,0 +1,39 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
.kotlin
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
+10
View File
@@ -0,0 +1,10 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Ignored default folder with query files
/queries/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/clotho-core/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/clotho-core/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/clotho-dev-app/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/clotho-dev-app/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/clotho-spring-boot-starter/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/clotho-spring-boot-starter/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="21" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+241
View File
@@ -0,0 +1,241 @@
# Clotho
A Java OGM (Object-Graph Mapper) for ArcadeDB, built on Apache TinkerPop/Gremlin.
Clotho is not a 1:1 node-to-object mapper. A "Clotho object" is a subgraph — a root vertex
plus a declared set of edges and adjacent vertices spanning any number of hops. Complex graph
traversals and analytics remain the developer's responsibility, written via `@Query` on
repository interfaces. Clotho handles bounded object loading and persistence.
---
## Module Structure
```
clotho/
clotho-core/ # Zero Spring dependency. All mapping logic.
clotho-spring-boot-starter/ # Autoconfigure, @Transactional bridge, Spring beans.
clotho-dev-app/ # Minimal Spring Boot app for development testing against
# a live ArcadeDB instance. Not a production artifact.
```
---
## Three Tiers of Graph-to-Java Mapping
### 1. Vertex Type
A single ArcadeDB vertex mapped to a Java class. Must extend `ClothoVertex`.
```java
@VertexType("Employee")
public class Employee extends ClothoVertex {
@Property("name") String name;
@Include @Via("HAS_ADDRESS")
Address address; // eagerly loaded as part of this object's boundary
}
```
### 2. Edge Type
A single ArcadeDB edge mapped to a Java class. Must extend `ClothoEdge`.
```java
@EdgeType("WORKS_AT")
public class WorksAt extends ClothoEdge {
@OutVertex Employee employee;
@InVertex Company company; // omit @InVertex for edge-only inclusion
LocalDate startDate;
}
```
### 3. Subgraph Type
A composite Java class assembled from multiple vertices and edges via a `@Query` traversal.
Has no ARID. Does NOT extend `ClothoVertex` or `ClothoEdge`.
`save()` delegates to all component `ClothoEntity` fields individually.
```java
@SubgraphType
public class EmployeeProfile {
Employee employee; // field name matches Gremlin as("employee")
Manager manager;
@Alias("dept") Department department;
}
```
---
## Technology Stack
| Concern | Library |
|---|---|
| Language | Java 21 |
| Build | Maven (multi-module) |
| Graph connection | Apache TinkerPop 3.x — `DriverRemoteConnection` over WebSocket |
| Null safety | JSpecify (`org.jspecify.annotations`) |
| Boilerplate reduction | Lombok |
| Testing | JUnit 5 |
| Spring integration | Spring Boot 3.x autoconfigure |
---
## Key Design Decisions
- **Schema-first**: Clotho assumes the ArcadeDB schema already exists. No DDL generation.
The developer manages the schema (e.g., using a Flyway-based migration tool).
- **Optional lazy loading**: `@Include` fields default to `FetchType.EAGER` (always loaded).
Declare `@Include(fetchType = FetchType.LAZY)` to skip a field during `populate()`. Lazy
fields remain `null`/empty until the developer calls `session.loadField(vertex, "fieldName")`
explicitly. No proxy or bytecode enhancement is used.
- **Single-query boundary loading**: All `@Include` fields for a vertex are fetched in a single
Gremlin `project()` traversal. This eliminates N+1 queries per object boundary and prevents
race conditions from sequential round-trips. For nested boundaries, each vertex gets its own
single-project query (one query per vertex, not one per field).
- **Dirty tracking**: `ClothoEntity` tracks which fields were mutated via `notifyFieldChanged()`
(called from manual setters). On save, `NEW` entities write all `@Property` fields; `MANAGED`
entities write only dirty fields and skip the update entirely if nothing changed.
`ClothoSession.close()` auto-saves all MANAGED entities (vertices and edges) that carry dirty fields.
- **Optimistic locking**: Declare `@Version Long version` on an entity field. Clotho reads
ArcadeDB's built-in `@version` property on load and includes a `.has("@version", version)`
filter on every update. A version mismatch throws `OptimisticLockException`. Both vertices
and edges support `@Version`.
- **Edges are first-class citizens**: `ClothoEdge` entities participate in the same
`EntityState` lifecycle, dirty tracking, `@Version` OCC, identity map caching, and
auto-save-on-close as `ClothoVertex` entities. Edges can be loaded by ID via
`session.load(EdgeType.class, id)`.
- **Result mapping**: Clotho always instantiates the most specific registered class matching
the vertex/edge label. Declared return types are upper bounds only.
- **Inheritance**: Java class hierarchy is the primary mechanism. `additionalParents` on
`@VertexType` handles ArcadeDB's multi-parent (diamond) inheritance where Java's single
inheritance is insufficient.
- **No automatic deletion**: Removing an element from an `@Include` collection does not
delete it from the graph. Call `session.delete()` explicitly.
See `docs/` for detailed specifications.
---
## Package Structure
```
com.binarygolem.clotho
.core
.model # ClothoEntity, ClothoVertex, ClothoEdge, ARID
.annotation # All annotations (@VertexType, @EdgeType, @SubgraphType, etc.)
.session # ClothoSession, ClothoSessionFactory
.registry # TypeRegistry
.mapping # ObjectMapper, SubgraphLoader, SubgraphPersistor, SubgraphTypeAssembler
.query # QueryExecutor, @Query proxy infrastructure
.exception # UnknownTypeException, ClothoException hierarchy
.spring
.config # ClothoAutoConfiguration
.tx # Transaction bridge
```
---
## Coding Conventions
### Nullability
Every parameter, return type, and field must carry `@NonNull` or `@Nullable` from JSpecify.
Default assumption is `@NonNull`; annotate only what can be null.
```java
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
```
### Lombok
Use Lombok where it reduces noise without obscuring intent:
- `@Getter` on domain classes
- `@Builder` on factory/config classes
- `@RequiredArgsConstructor` / `@AllArgsConstructor` on service classes
- `@Value` is NOT compatible with Clotho-managed domain objects (requires mutable fields)
**`@Setter` restriction on entity classes:** Do NOT use Lombok `@Setter` on any field
annotated with `@Property`, `@Include`, `@OutVertex`, `@InVertex`, or `@Version` on a
`ClothoVertex` or `ClothoEdge` subclass. Write a manual setter that calls
`notifyFieldChanged(fieldName)` so the session can track the change:
```java
// Correct
public void setName(String name) {
this.name = name;
notifyFieldChanged("name");
}
// Wrong — dirty tracking does not fire
@Setter String name;
```
Lombok `@Setter` remains allowed only for framework-managed fields (`id`, `outVertexId`,
`inVertexId`) because Clotho sets those itself and they are not part of dirty tracking.
### Comments
Write no comments unless the WHY is non-obvious. One line maximum.
Never write doc comments that restate what the method name already says.
### Naming
- ArcadeDB type names (labels) use the `@VertexType` / `@EdgeType` annotation value.
Class names need not match label names exactly.
- Edge label constants: define as `public static final String LABEL = "WORKS_AT"` on the
edge class to avoid magic strings at call sites.
---
## Development Setup
### Prerequisites
- Java 21
- Maven 3.9+
- A running ArcadeDB instance (for integration tests and `clotho-dev-app`)
### Build
```bash
mvn clean install
```
### Run `clotho-dev-app`
```bash
mvn -pl clotho-dev-app spring-boot:run
```
### Connection (local ArcadeDB default)
```properties
clotho.gremlin.url=ws://localhost:8182/gremlin
clotho.gremlin.username=root
clotho.gremlin.password=playwithdata
clotho.gremlin.traversal-source=g
```
---
## Implementation Status
| Phase | Description | Status |
|---|---|---|
| 1 | Project housekeeping — parent POM, module scaffold, package rename | Done |
| 2 | Base types and annotations — `ARID`, `ClothoEntity`, `ClothoVertex`, `ClothoEdge`, all annotations, exception hierarchy | Done |
| 3 | `clotho-dev-app` — Gremlin connection wiring, smoke test against live ArcadeDB | Done |
| 4 | `TypeRegistry` — classpath scan, label→class map, hierarchy inference, `additionalParents`/`parentLabel` | Done |
| 5 | `ElementMapper` — Gremlin `Vertex`/`Edge` → Java; always most-specific class by label | Done |
| 6 | `SubgraphLoader` — traverse `@Include`/`@Via`, multi-hop, cycle detection, edge-only; `SubgraphTypeAssembler` | Done |
| 7 | `SubgraphPersistor` — upsert, `@version` optimistic locking, cascade through boundary | Done |
| 8 | `ClothoSession` / `ClothoSessionFactory` — identity map, `load`/`save`/`delete`/`query`, connection lifecycle | Done |
| 9 | `ClothoRepository<T>` — abstract base class; `g()`, `execute()`, `findAll()`, `findById()`, etc.; dropped `@Query`/`@Param` | Done |
| 10 | Spring Boot Starter — `ClothoAutoConfiguration`, `ClothoProperties`, `@ClothoRepository` bean scanning | Done |
| 11 | Dirty tracking (`notifyFieldChanged`, `EntityState`), `SessionContext`, single-query `project()` loading, `@Version` OCC, `FetchType.LAZY`, `FieldMetadataCache`, expanded type coercion, `populateAll()` batch loading, auto-save on close, edge first-class parity | Done |
| 12 | Transaction management — `openTransactionalSession()`, borrow counter, `rollback()`, `getCurrentSession()`, `ClothoTransactionManager`, Spring `@Transactional` bridge, `ClothoAutoConfiguration` tx bean | Done |
---
## Documentation Index
| Document | Contents |
|---|---|
| `docs/TYPE_SYSTEM.md` | `ClothoEntity` hierarchy, `@VertexType`, `@EdgeType`, `@SubgraphType`, inheritance, diamond inheritance, result mapping rule |
| `docs/OBJECT_BOUNDARY.md` | `@Include`/`@Via`, multi-hop traversal, edge-only inclusion, cycle detection |
| `docs/ANNOTATIONS.md` | Complete annotation reference with all attributes and examples |
| `docs/QUERY_MODEL.md` | `@Query`, `@ClothoRepository`, `@SubgraphType` assembly, result mapping, parameter binding |
| `docs/SPRING_INTEGRATION.md` | Autoconfigure, `@Transactional`, `application.properties` reference |
| `docs/ARCHITECTURE.md` | Module breakdown, key components, data flow, session lifecycle |
| `docs/TRANSACTIONS.md` | Transactional sessions, Spring `@Transactional`, nested propagation, `@Version` interaction, limitations |
+61
View File
@@ -0,0 +1,61 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-parent</artifactId>
<version>0.1.0-SNAPSHOT</version>
</parent>
<artifactId>clotho-core</artifactId>
<name>Clotho Core</name>
<description>Core OGM logic — zero Spring dependency</description>
<dependencies>
<!-- TinkerPop remote Gremlin client -->
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
</dependency>
<!-- Classpath scanning for TypeRegistry -->
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
</dependency>
<!-- Lombok (annotation processor only — not included in output jar) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- Null annotations (compile + runtime for reflection-based checks) -->
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
</dependency>
<!-- Test: JUnit 5 -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<!-- Test: TinkerGraph — in-memory TinkerPop graph for unit tests (no real DB needed) -->
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>tinkergraph-gremlin</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -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());
}
}
+95
View File
@@ -0,0 +1,95 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-parent</artifactId>
<version>0.1.0-SNAPSHOT</version>
</parent>
<artifactId>clotho-dev-app</artifactId>
<name>Clotho Dev App</name>
<description>
Development sandbox — connects to a live ArcadeDB instance for manual and
exploratory testing during library development. Not a production artifact.
</description>
<dependencies>
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-spring-boot-starter</artifactId>
</dependency>
<!-- Spring Boot baseline: context, logging, autoconfigure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,12 @@
package com.binarygolem.clotho.dev;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ClothoDevApp {
public static void main(String[] args) {
SpringApplication.run(ClothoDevApp.class, args);
}
}
@@ -0,0 +1,25 @@
package com.binarygolem.clotho.dev;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Slf4j
@Component
@Order(1)
@RequiredArgsConstructor
public class ConnectionSmokeTest implements ApplicationRunner {
private final GraphTraversalSource traversalSource;
@Override
public void run(ApplicationArguments args) {
log.info("Testing Gremlin connection...");
long count = traversalSource.V().count().next();
log.info("Connection OK — total vertex count: {}", count);
}
}
@@ -0,0 +1,39 @@
package com.binarygolem.clotho.dev;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection;
import org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.util.ser.GraphSONMessageSerializerV3;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.net.URI;
@Configuration
@EnableConfigurationProperties(GremlinProperties.class)
public class GremlinConfig {
@Bean(destroyMethod = "close")
public Cluster gremlinCluster(GremlinProperties props) {
URI uri = URI.create(props.getUrl());
int port = uri.getPort() > 0 ? uri.getPort() : 8182;
return Cluster.build()
.addContactPoint(uri.getHost())
.port(port)
.credentials(props.getUsername(), props.getPassword())
.serializer(new GraphSONMessageSerializerV3())
.create();
}
@Bean
public DriverRemoteConnection remoteConnection(Cluster cluster, GremlinProperties props) {
return DriverRemoteConnection.using(cluster, props.getTraversalSource());
}
@Bean(destroyMethod = "close")
public GraphTraversalSource traversalSource(DriverRemoteConnection connection) {
return AnonymousTraversalSource.traversal().withRemote(connection);
}
}
@@ -0,0 +1,14 @@
package com.binarygolem.clotho.dev;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("clotho.gremlin")
@Data
public class GremlinProperties {
private String url = "";
private String username = "";
private String password = "";
private String traversalSource = "g";
}
@@ -0,0 +1,301 @@
package com.binarygolem.clotho.dev.demo;
import com.binarygolem.clotho.dev.demo.model.Company;
import com.binarygolem.clotho.dev.demo.model.Person;
import com.binarygolem.clotho.dev.demo.model.WorksAt;
import com.binarygolem.clotho.dev.demo.repository.PersonRepository;
import com.binarygolem.clotho.model.ARID;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jspecify.annotations.Nullable;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* Demonstrates core Clotho features against a live ArcadeDB instance.
*
* <p>Requires these ArcadeDB types to exist before running:
* <pre>
* CREATE VERTEX TYPE Person;
* CREATE PROPERTY Person.name STRING;
* CREATE PROPERTY Person.email STRING;
* CREATE PROPERTY Person.age INTEGER;
*
* CREATE VERTEX TYPE Company;
* CREATE PROPERTY Company.name STRING;
* CREATE PROPERTY Company.industry STRING;
*
* CREATE EDGE TYPE WORKS_AT;
* CREATE PROPERTY WORKS_AT.role STRING;
* CREATE PROPERTY WORKS_AT.startYear INTEGER;
* </pre>
*
* <p>All demo data is cleaned up after the run regardless of success or failure.
*/
@Slf4j
@Component
@Order(2)
@RequiredArgsConstructor
public class FeatureDemo implements ApplicationRunner {
private final ClothoSessionFactory sessionFactory;
private final PersonRepository personRepository;
@Override
public void run(ApplicationArguments args) {
log.info("");
log.info("══════════════════════════════════════");
log.info(" Clotho Feature Demo ");
log.info("══════════════════════════════════════");
@Nullable ARID personId = null;
@Nullable ARID bobId = null;
@Nullable ARID charlieId = null;
@Nullable ARID companyId = null;
try {
// ── 1. Create entities (session cascades: person → edge → company) ──
log.info("");
log.info("1. Creating entities");
try (ClothoSession session = sessionFactory.openSession()) {
Company acme = new Company();
acme.setName("Acme Corp");
acme.setIndustry("Technology");
Person alice = new Person();
alice.setName("Alice Smith");
alice.setEmail("alice@example.com");
alice.setAge(32);
WorksAt aliceJob = new WorksAt();
aliceJob.setCompany(acme);
aliceJob.setRole("Senior Engineer");
aliceJob.setStartYear(2020);
alice.setJobs(List.of(aliceJob));
Person bob = new Person();
bob.setName("Bob Jones");
bob.setEmail("bob@example.com");
bob.setAge(28);
WorksAt bobJob = new WorksAt();
bobJob.setCompany(acme);
bobJob.setRole("Engineer");
bobJob.setStartYear(2022);
bob.setJobs(List.of(bobJob));
Person charlie = new Person();
charlie.setName("Charlie Lee");
charlie.setEmail("charlie@example.com");
charlie.setAge(41);
WorksAt charlieJob = new WorksAt();
charlieJob.setCompany(acme);
charlieJob.setRole("Engineering Manager");
charlieJob.setStartYear(2018);
charlie.setJobs(List.of(charlieJob));
session.save(alice);
session.save(bob);
session.save(charlie);
personId = alice.getId();
bobId = bob.getId();
charlieId = charlie.getId();
companyId = acme.getId();
log.info(" ✓ Company {} → {}", acme.getName(), acme.getId());
log.info(" ✓ Person {} ({}) → {}", alice.getName(), aliceJob.getRole(), alice.getId());
log.info(" ✓ Person {} ({}) → {}", bob.getName(), bobJob.getRole(), bob.getId());
log.info(" ✓ Person {} ({}) → {}", charlie.getName(), charlieJob.getRole(), charlie.getId());
}
// ── 2. Load by ID — @Include boundary auto-populated in a single query ──
log.info("");
log.info("2. Loading by ID (@Include populated atomically)");
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
List<WorksAt> jobs = alice.getJobs();
log.info(" ✓ Loaded: {} (age {}), {} job(s)", alice.getName(), alice.getAge(),
jobs == null ? 0 : jobs.size());
if (jobs != null && !jobs.isEmpty()) {
WorksAt job = jobs.get(0);
String companyName = job.getCompany() != null ? job.getCompany().getName() : "?";
log.info(" └─ {} at {} (since {})", job.getRole(), companyName, job.getStartYear());
}
}
// ── 3. Dirty tracking — only modified fields are written ──
log.info("");
log.info("3. Dirty tracking (partial update)");
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
alice.setEmail("alice.smith@example.com"); // dirty: email
alice.setAge(33); // dirty: age
// name is unchanged — not written
session.save(alice);
log.info(" ✓ Saved 2 dirty fields (email, age); name not touched");
}
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
log.info(" ✓ Verified: email={}, age={}", alice.getEmail(), alice.getAge());
}
// ── 4. Auto-save on session close ──
log.info("");
log.info("4. Auto-save on session close");
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
alice.setAge(34);
// no explicit save() — session.close() persists dirty MANAGED entities
}
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
log.info(" ✓ Age auto-saved on close: {}", alice.getAge());
}
// ── 5. Repository queries ──
log.info("");
log.info("5. Repository queries");
List<Person> byName = personRepository.findByName("Alice Smith");
log.info(" ✓ findByName(\"Alice Smith\"): {} result(s)", byName.size());
List<Person> byAge = personRepository.findByAgeGreaterThan(30);
log.info(" ✓ findByAgeGreaterThan(30): {} result(s)", byAge.size());
List<Person> employed = personRepository.findEmployed();
log.info(" ✓ findEmployed(): {} result(s)", employed.size());
long total = personRepository.count();
log.info(" ✓ count(): {} total Person(s) in graph", total);
// ── 6. Ad-hoc traversal + session-aware execute ──
log.info("");
log.info("6. Ad-hoc traversal: findCoworkers() with session-aware execute");
log.info(" (traverses WORKS_AT not declared as @Include — results are MANAGED)");
@Nullable ARID firstCoworkerId = null;
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, personId);
// session-aware overload: returned entities are MANAGED in this session
List<Person> coworkers = personRepository.findCoworkers(alice, session);
log.info(" ✓ Alice's co-workers at Acme Corp: {} found", coworkers.size());
for (Person cw : coworkers) {
String role = cw.getJobs() != null && !cw.getJobs().isEmpty()
? cw.getJobs().get(0).getRole() : "?";
log.info(" └─ {} ({})", cw.getName(), role);
}
if (!coworkers.isEmpty()) {
firstCoworkerId = coworkers.get(0).getId();
coworkers.get(0).setEmail("updated-by-demo@example.com");
// no explicit save() — dirty tracking fires; auto-saved on session close
}
} // ← session.close() auto-saves the dirty co-worker here
if (firstCoworkerId != null) {
try (ClothoSession session = sessionFactory.openSession()) {
Person cw = session.load(Person.class, firstCoworkerId);
log.info(" ✓ Co-worker email auto-saved on close: {}", cw.getEmail());
}
}
// ── 7. Transactional session ──
log.info("");
log.info("7. Transactional session (atomic multi-step write)");
ARID txPersonId = null;
try (ClothoSession session = sessionFactory.openTransactionalSession()) {
Company startupCo = new Company();
startupCo.setName("StartupCo");
startupCo.setIndustry("FinTech");
Person diana = new Person();
diana.setName("Diana Prince");
diana.setEmail("diana@startupco.io");
diana.setAge(29);
// openSession() inside a transactional session borrows the same session
ClothoSession borrowed = sessionFactory.openSession();
log.info(" openSession() inside @Transactional returns same session? {}",
borrowed == session ? "yes" : "no");
borrowed.close(); // borrow close — no-op
session.save(diana);
txPersonId = diana.getId();
log.info(" ✓ Diana created: {} → {}", diana.getName(), diana.getId());
log.info(" ✓ (company would be linked here; session commits on close)");
} // ← tx.commit() fires here
if (txPersonId != null) {
try (ClothoSession session = sessionFactory.openSession()) {
Person diana = session.load(Person.class, txPersonId);
log.info(" ✓ Verified commit: {} loaded after tx close", diana.getName());
session.delete(diana);
}
}
} catch (Exception e) {
log.error("Demo failed — check that the required ArcadeDB schema exists", e);
log.error("Required types: Person, Company, WORKS_AT (see FeatureDemo Javadoc)");
} finally {
cleanup(personId, bobId, charlieId, companyId);
}
}
private void cleanup(@Nullable ARID personId, @Nullable ARID bobId,
@Nullable ARID charlieId, @Nullable ARID companyId) {
log.info("");
log.info("Cleaning up demo data");
try {
// Delete all persons in one traversal. Sequential per-session deletes cause OrientDB's
// Gremlin Server to cache the Company vertex at its initial @version and then fail the
// MVCC check when cascade-deleting later edges bumps the DB version above the cached one.
// A single g.V(...).drop() request loads Company once and applies all cascades atomically.
List<Object> personIds = new ArrayList<>();
if (personId != null) personIds.add(personId.asString());
if (bobId != null) personIds.add(bobId.asString());
if (charlieId != null) personIds.add(charlieId.asString());
if (!personIds.isEmpty()) {
sessionFactory.traversal().V(personIds.toArray()).drop().iterate();
log.info(" ✓ Deleted {} Person(s) (+ incident WORKS_AT edge(s))", personIds.size());
}
if (companyId != null) {
try {
sessionFactory.traversal().V(companyId.asString()).drop().iterate();
log.info(" ✓ Deleted Company");
} catch (Exception e) {
// OrientDB cascade-deletes the Company when the last incident WORKS_AT edge is
// removed by the person bulk-drop above — treat "not found" as already gone.
if (e.getMessage() != null && e.getMessage().contains("was not found")) {
log.info(" ✓ Company already removed (cascade)");
} else {
throw e;
}
}
}
} catch (Exception e) {
log.warn("Cleanup failed — demo data may remain in the graph: {}", e.getMessage());
}
log.info("");
log.info("══════════════════════════════════════");
log.info(" Demo complete ");
log.info("══════════════════════════════════════");
log.info("");
}
}
@@ -0,0 +1,103 @@
package com.binarygolem.clotho.dev.demo;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* Confirms that Clotho's application-managed {@code @Version} OCC mechanism works
* against a live ArcadeDB instance.
*
* <p>ArcadeDB's internal {@code @version} property is not accessible via the Gremlin
* WebSocket interface. Clotho therefore manages the version counter itself as a regular
* graph property (default: {@code "_version"}). This probe verifies that the Gremlin
* filter step {@code .has("_version", expectedValue)} works correctly with ArcadeDB for
* regular properties — the foundation of the pre-flight conflict check.
*/
@Slf4j
@Component
@Order(3)
@RequiredArgsConstructor
public class VersionConflictProbe implements ApplicationRunner {
private final ClothoSessionFactory sessionFactory;
@Override
public void run(ApplicationArguments args) {
log.info("");
log.info("══════════════════════════════════════════════════════");
log.info(" Clotho @Version OCC Mechanism Smoke Test ");
log.info("══════════════════════════════════════════════════════");
GraphTraversalSource g = sessionFactory.traversal();
String probeId = null;
try {
// Create a vertex with an initial _version=0 (mimics what Clotho does on persist)
Vertex v = g.addV("Person")
.property("name", "OccProbe")
.property("_version", 0L)
.next();
probeId = v.id().toString();
log.info(" Probe vertex created: {}", probeId);
// ── Part 1: does .has("_version", value) actually filter? ──
log.info("");
log.info("Part 1: _version filter works with regular properties");
long matchCorrect = g.V(probeId).has("_version", 0L).count().next();
long matchWrong = g.V(probeId).has("_version", 99L).count().next();
log.info(" .has('_version', 0L) → {}", matchCorrect);
log.info(" .has('_version', 99L) → {}", matchWrong);
boolean filterWorks = matchCorrect == 1 && matchWrong == 0;
log.info(" → Filter functional? → {}", filterWorks ? "YES ✓" : "NO ✗");
// ── Part 2: pre-flight check + atomic version-increment update ──
log.info("");
log.info("Part 2: check-and-increment update (Clotho's write step)");
// This is what Clotho's updateEntity() does: filter by version, write dirty props,
// increment version — all in one traversal.
long updated = g.V(probeId)
.has("_version", 0L)
.property("name", "OccProbe-v1")
.property("_version", 1L)
.count().next();
log.info(" Update with correct version (0→1): matched={}", updated);
// Try stale update — version is now 1, so filtering by 0 must return 0
long stale = g.V(probeId)
.has("_version", 0L)
.property("name", "MUST-NOT-BE-WRITTEN")
.count().next();
log.info(" Update with stale version (0 after bump): matched={}", stale);
String finalName = (String) g.V(probeId).values("name").next();
Long finalVer = (Long) g.V(probeId).values("_version").next();
log.info(" Final name: {} (expected: OccProbe-v1)", finalName);
log.info(" Final _version: {} (expected: 1)", finalVer);
boolean occWorks = updated == 1 && stale == 0
&& "OccProbe-v1".equals(finalName) && Long.valueOf(1L).equals(finalVer);
log.info(" → Application-managed OCC works? → {}", occWorks ? "YES ✓" : "NO ✗");
} catch (Exception e) {
log.error("Probe failed unexpectedly", e);
} finally {
if (probeId != null) {
try { g.V(probeId).drop().iterate(); } catch (Exception ignored) {}
}
log.info("");
log.info("══════════════════════════════════════════════════════");
log.info(" Probe complete ");
log.info("══════════════════════════════════════════════════════");
log.info("");
}
}
}
@@ -0,0 +1,38 @@
package com.binarygolem.clotho.dev.demo.model;
import com.binarygolem.clotho.annotation.Property;
import com.binarygolem.clotho.annotation.VertexType;
import com.binarygolem.clotho.model.ClothoVertex;
import lombok.Getter;
import org.jspecify.annotations.Nullable;
/**
* ArcadeDB type: {@code Company}.
*
* <p>Required schema:
* <pre>
* CREATE VERTEX TYPE Company;
* CREATE PROPERTY Company.name STRING;
* CREATE PROPERTY Company.industry STRING;
* </pre>
*/
@VertexType("Company")
@Getter
public class Company extends ClothoVertex {
@Property("name")
private @Nullable String name;
@Property("industry")
private @Nullable String industry;
public void setName(@Nullable String name) {
this.name = name;
notifyFieldChanged("name");
}
public void setIndustry(@Nullable String industry) {
this.industry = industry;
notifyFieldChanged("industry");
}
}
@@ -0,0 +1,60 @@
package com.binarygolem.clotho.dev.demo.model;
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.model.ClothoVertex;
import lombok.Getter;
import org.jspecify.annotations.Nullable;
import java.util.List;
/**
* ArcadeDB type: {@code Person}.
*
* <p>Required schema:
* <pre>
* CREATE VERTEX TYPE Person;
* CREATE PROPERTY Person.name STRING;
* CREATE PROPERTY Person.email STRING;
* CREATE PROPERTY Person.age INTEGER;
* </pre>
*/
@VertexType("Person")
@Getter
public class Person extends ClothoVertex {
@Property("name")
private @Nullable String name;
@Property("email")
private @Nullable String email;
@Property("age")
private @Nullable Integer age;
@Include
@Via("WORKS_AT")
private @Nullable List<WorksAt> jobs;
public void setName(@Nullable String name) {
this.name = name;
notifyFieldChanged("name");
}
public void setEmail(@Nullable String email) {
this.email = email;
notifyFieldChanged("email");
}
public void setAge(@Nullable Integer age) {
this.age = age;
notifyFieldChanged("age");
}
public void setJobs(@Nullable List<WorksAt> jobs) {
this.jobs = jobs;
notifyFieldChanged("jobs");
}
}
@@ -0,0 +1,56 @@
package com.binarygolem.clotho.dev.demo.model;
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.model.ClothoEdge;
import lombok.Getter;
import org.jspecify.annotations.Nullable;
/**
* ArcadeDB type: {@code WORKS_AT}.
*
* <p>Required schema:
* <pre>
* CREATE EDGE TYPE WORKS_AT;
* CREATE PROPERTY WORKS_AT.role STRING;
* CREATE PROPERTY WORKS_AT.startYear INTEGER;
* </pre>
*/
@EdgeType("WORKS_AT")
@Getter
public class WorksAt extends ClothoEdge {
@Property("role")
private @Nullable String role;
@Property("startYear")
private @Nullable Integer startYear;
@OutVertex
private @Nullable Person person;
@InVertex
private @Nullable Company company;
public void setRole(@Nullable String role) {
this.role = role;
notifyFieldChanged("role");
}
public void setStartYear(@Nullable Integer startYear) {
this.startYear = startYear;
notifyFieldChanged("startYear");
}
public void setPerson(@Nullable Person person) {
this.person = person;
notifyFieldChanged("person");
}
public void setCompany(@Nullable Company company) {
this.company = company;
notifyFieldChanged("company");
}
}
@@ -0,0 +1,61 @@
package com.binarygolem.clotho.dev.demo.repository;
import com.binarygolem.clotho.dev.demo.model.Person;
import com.binarygolem.clotho.repository.ClothoRepository;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import java.util.List;
@com.binarygolem.clotho.annotation.ClothoRepository
public class PersonRepository extends ClothoRepository<Person> {
public PersonRepository(ClothoSessionFactory factory) {
super(factory);
}
public List<Person> findByName(String name) {
return execute(g().V().has("Person", "name", name));
}
public List<Person> findByAgeGreaterThan(int minAge) {
return execute(allEntities(), t -> t.has("age", P.gt(minAge)));
}
/** Returns all people who have at least one outgoing WORKS_AT edge. */
public List<Person> findEmployed() {
return execute(allEntities(), t -> t.where(__.outE("WORKS_AT")));
}
/**
* Returns co-workers as detached (untracked) entities — suitable for read-only use.
*
* <p>Traverses WORKS_AT edges that are not declared as {@code @Include} on
* {@code Person}, demonstrating that repository methods can freely cross any
* edge in the graph regardless of object-boundary declarations.
*/
public List<Person> findCoworkers(Person person) {
return execute(
g().V(person.getId().asString()).as("self")
.out("WORKS_AT") // Person → Company
.in("WORKS_AT") // Company → all Persons at that company
.where(P.neq("self"))
);
}
/**
* Returns co-workers registered into {@code session} as MANAGED entities.
* Dirty-field changes on the returned objects are tracked and auto-saved when
* the session closes — no explicit {@code save()} needed.
*/
public List<Person> findCoworkers(Person person, ClothoSession session) {
return execute(session,
g().V(person.getId().asString()).as("self")
.out("WORKS_AT")
.in("WORKS_AT")
.where(P.neq("self"))
);
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.dev;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,14 @@
spring.application.name=clotho-dev-app
# OrientDB Gremlin endpoint (no auth — Gremlin Server configured without authentication)
clotho.gremlin.url=ws://localhost:8182/gremlin
clotho.gremlin.username=
clotho.gremlin.password=
clotho.gremlin.traversal-source=g
# Clotho behaviour
clotho.default-direction=OUT
clotho.unknown-type-behavior=STRICT
# Packages to scan for @VertexType / @EdgeType / @ClothoRepository
clotho.packages=com.binarygolem.clotho.dev
+105
View File
@@ -0,0 +1,105 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-parent</artifactId>
<version>0.1.0-SNAPSHOT</version>
</parent>
<artifactId>clotho-spring-boot-starter</artifactId>
<name>Clotho Spring Boot Starter</name>
<description>Spring Boot autoconfiguration and @Transactional bridge for Clotho</description>
<dependencies>
<!-- Clotho core -->
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-core</artifactId>
</dependency>
<!-- Spring Boot autoconfiguration infrastructure -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<!-- Transaction management (arrives transitively but pinned to prevent version drift) -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
</dependency>
<!-- Generates META-INF/spring-configuration-metadata.json for IDE support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Test: in-memory TinkerGraph — avoids needing a real ArcadeDB in tests -->
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>tinkergraph-gremlin</artifactId>
<scope>test</scope>
</dependency>
<!-- Test: ApplicationContextRunner -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test-autoconfigure</artifactId>
<scope>test</scope>
</dependency>
<!-- Test: AssertJ — required by ApplicationContextRunner -->
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<!-- Test: Mockito for ClothoTransactionManagerTest -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,105 @@
package com.binarygolem.clotho.spring.config;
import com.binarygolem.clotho.registry.TypeRegistry;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import com.binarygolem.clotho.spring.repository.ClothoRepositoryRegistrar;
import com.binarygolem.clotho.spring.tx.ClothoTransactionManager;
import org.apache.tinkerpop.gremlin.driver.Cluster;
import org.apache.tinkerpop.gremlin.driver.remote.DriverRemoteConnection;
import org.apache.tinkerpop.gremlin.process.traversal.AnonymousTraversalSource;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.util.ser.GraphSONMessageSerializerV3;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.PlatformTransactionManager;
import java.net.URI;
import java.util.List;
/**
* Autoconfigures the Clotho OGM layer for Spring Boot.
*
* <p>Creates a Gremlin {@link Cluster}, {@link DriverRemoteConnection},
* {@link GraphTraversalSource}, {@link TypeRegistry}, and {@link ClothoSessionFactory}
* from {@code clotho.*} properties. All beans are conditional on missing; override any
* bean in your own {@code @Configuration} to customise.
*
* <p>Also imports {@link ClothoRepositoryRegistrar}, which scans {@code clotho.packages}
* for {@code @ClothoRepository}-annotated {@link com.binarygolem.clotho.repository.ClothoRepository}
* subclasses and registers them as Spring beans.
*/
@AutoConfiguration
@EnableConfigurationProperties(ClothoProperties.class)
@Import(ClothoRepositoryRegistrar.class)
public class ClothoAutoConfiguration {
/**
* Gremlin cluster connecting to the configured server.
* Override this bean to use a custom cluster configuration.
*/
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean
public Cluster clothoGremlinCluster(ClothoProperties props) {
ClothoProperties.Gremlin gremlin = props.getGremlin();
URI uri = URI.create(gremlin.getUrl());
int port = uri.getPort() > 0 ? uri.getPort() : 8182;
return Cluster.build()
.addContactPoint(uri.getHost())
.port(port)
.credentials(gremlin.getUsername(), gremlin.getPassword())
.serializer(new GraphSONMessageSerializerV3())
.create();
}
@Bean
@ConditionalOnMissingBean
public DriverRemoteConnection clothoRemoteConnection(Cluster cluster, ClothoProperties props) {
return DriverRemoteConnection.using(cluster, props.getGremlin().getTraversalSource());
}
/**
* Live {@link GraphTraversalSource} backed by the remote Gremlin server.
* Override with a TinkerGraph-backed source in tests.
*/
@Bean(destroyMethod = "close")
@ConditionalOnMissingBean
public GraphTraversalSource clothoTraversalSource(DriverRemoteConnection connection) {
return AnonymousTraversalSource.traversal().withRemote(connection);
}
/**
* {@link TypeRegistry} populated by scanning {@code clotho.packages}.
* Registers no types when no packages are configured.
*/
@Bean
@ConditionalOnMissingBean
public TypeRegistry clothoTypeRegistry(ClothoProperties props) {
List<String> packages = props.getPackages();
if (packages.isEmpty()) {
return TypeRegistry.builder().build();
}
return TypeRegistry.scan(packages.toArray(String[]::new));
}
@Bean
@ConditionalOnMissingBean
public ClothoSessionFactory clothoSessionFactory(GraphTraversalSource g,
TypeRegistry registry,
ClothoProperties props) {
return ClothoSessionFactory.builder()
.g(g)
.registry(registry)
.unknownTypeBehavior(props.getUnknownTypeBehavior())
.defaultDirection(props.getDefaultDirection())
.build();
}
@Bean
@ConditionalOnMissingBean(PlatformTransactionManager.class)
public ClothoTransactionManager clothoTransactionManager(ClothoSessionFactory factory) {
return new ClothoTransactionManager(factory);
}
}
@@ -0,0 +1,45 @@
package com.binarygolem.clotho.spring.config;
import com.binarygolem.clotho.model.TraversalDirection;
import com.binarygolem.clotho.model.UnknownTypeBehavior;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* Binds {@code clotho.*} properties from {@code application.properties} or YAML.
*
* <pre>{@code
* clotho.gremlin.url=ws://localhost:8182/gremlin
* clotho.gremlin.username=root
* clotho.gremlin.password=secret
* clotho.gremlin.traversal-source=g
* clotho.default-direction=OUT
* clotho.unknown-type-behavior=STRICT
* clotho.packages=com.example.domain,com.example.graph
* }</pre>
*/
@ConfigurationProperties("clotho")
@Data
public class ClothoProperties {
private Gremlin gremlin = new Gremlin();
private TraversalDirection defaultDirection = TraversalDirection.OUT;
private UnknownTypeBehavior unknownTypeBehavior = UnknownTypeBehavior.STRICT;
/**
* Base packages to scan for {@code @VertexType}, {@code @EdgeType}, and
* {@code @ClothoRepository} classes.
*/
private List<String> packages = new ArrayList<>();
@Data
public static class Gremlin {
private String url = "ws://localhost:8182/gremlin";
private String username = "";
private String password = "";
private String traversalSource = "g";
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.spring.config;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,91 @@
package com.binarygolem.clotho.spring.repository;
import com.binarygolem.clotho.repository.ClothoRepository;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.Environment;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import java.util.List;
/**
* Scans {@code clotho.packages} for classes annotated with
* {@link com.binarygolem.clotho.annotation.ClothoRepository @ClothoRepository}
* that extend {@link ClothoRepository}, and registers each as a singleton Spring bean.
*
* <p>Each registered bean receives the shared {@code clothoSessionFactory} bean
* as its constructor argument; Spring resolves the dependency at context refresh time.
*/
public class ClothoRepositoryRegistrar
implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
List<String> packages = Binder.get(environment)
.bind("clotho.packages", Bindable.listOf(String.class))
.orElse(List.of());
if (packages.isEmpty()) {
return;
}
ClassPathScanningCandidateComponentProvider scanner = buildScanner();
for (String pkg : packages) {
for (var candidate : scanner.findCandidateComponents(pkg)) {
String className = candidate.getBeanClassName();
if (className == null) continue;
Class<?> cls;
try {
cls = Class.forName(className);
} catch (ClassNotFoundException e) {
continue;
}
if (!ClothoRepository.class.isAssignableFrom(cls)) continue;
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(cls);
bd.getConstructorArgumentValues()
.addGenericArgumentValue(new RuntimeBeanReference("clothoSessionFactory"));
bd.setLazyInit(false);
registry.registerBeanDefinition(beanName(cls), bd);
}
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// no-op
}
private ClassPathScanningCandidateComponentProvider buildScanner() {
var scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(
com.binarygolem.clotho.annotation.ClothoRepository.class));
return scanner;
}
private static String beanName(Class<?> cls) {
String name = cls.getSimpleName();
return Character.toLowerCase(name.charAt(0)) + name.substring(1);
}
}
@@ -0,0 +1,4 @@
@NullMarked
package com.binarygolem.clotho.spring.repository;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,54 @@
package com.binarygolem.clotho.spring.tx;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import com.binarygolem.clotho.session.SessionContext;
import org.jspecify.annotations.Nullable;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionStatus;
/**
* Integrates Clotho transactional sessions with Spring's {@code @Transactional} mechanism.
*
* <p>Register as a bean (done automatically by {@code ClothoAutoConfiguration}) and annotate
* service methods with {@code @Transactional}. Spring calls {@link #getTransaction},
* {@link #commit}, and {@link #rollback}; application code calls
* {@link ClothoSessionFactory#openSession()} or {@link ClothoSessionFactory#getCurrentSession()}
* to obtain the session bound to the transaction.
*
* <p>Nested {@code @Transactional} methods join the outer transaction — no new session or
* commit is created for the inner method.
*/
public class ClothoTransactionManager implements PlatformTransactionManager {
private final ClothoSessionFactory sessionFactory;
public ClothoTransactionManager(ClothoSessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public TransactionStatus getTransaction(@Nullable TransactionDefinition definition) {
ClothoSession existing = SessionContext.get();
if (existing != null) {
return new DefaultTransactionStatus(existing, false, false, false, false, null);
}
ClothoSession session = sessionFactory.openTransactionalSession();
return new DefaultTransactionStatus(session, true, true, false, false, null);
}
@Override
public void commit(TransactionStatus status) {
if (!status.isNewTransaction()) return;
ClothoSession session = (ClothoSession) ((DefaultTransactionStatus) status).getTransaction();
session.close();
}
@Override
public void rollback(TransactionStatus status) {
ClothoSession session = (ClothoSession) ((DefaultTransactionStatus) status).getTransaction();
session.rollback();
}
}
@@ -0,0 +1,2 @@
/** Spring transaction management bridge for Clotho. */
package com.binarygolem.clotho.spring.tx;
@@ -0,0 +1 @@
com.binarygolem.clotho.spring.config.ClothoAutoConfiguration
@@ -0,0 +1,118 @@
package com.binarygolem.clotho.spring.config;
import com.binarygolem.clotho.annotation.VertexType;
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 com.binarygolem.clotho.session.ClothoSessionFactory;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import static org.junit.jupiter.api.Assertions.*;
class ClothoAutoConfigurationTest {
// --- Fixtures ---
@VertexType("Widget")
static class Widget extends ClothoVertex {}
@com.binarygolem.clotho.annotation.ClothoRepository
static class WidgetRepo extends com.binarygolem.clotho.repository.ClothoRepository<Widget> {
WidgetRepo(ClothoSessionFactory factory) { super(factory); }
}
// --- Context runner ---
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(ClothoAutoConfiguration.class));
/** Provides a TinkerGraph traversal source so no real ArcadeDB is needed. */
private ApplicationContextRunner withTinkerGraph(ApplicationContextRunner runner) {
return runner
.withBean("clothoTraversalSource", GraphTraversalSource.class,
() -> TinkerGraph.open().traversal())
.withBean("clothoTypeRegistry", TypeRegistry.class,
() -> TypeRegistry.builder().build());
}
// --- Tests ---
@Test
void sessionFactoryBeanIsCreated() {
withTinkerGraph(contextRunner).run(ctx -> {
assertNull(ctx.getStartupFailure(),
() -> ctx.getStartupFailure().getMessage());
assertNotNull(ctx.getBean(ClothoSessionFactory.class));
});
}
@Test
void sessionFactoryBacksOffWhenUserProvides() {
ClothoSessionFactory existing = ClothoSessionFactory.builder()
.g(TinkerGraph.open().traversal())
.registry(TypeRegistry.builder().build())
.build();
withTinkerGraph(contextRunner)
.withBean(ClothoSessionFactory.class, () -> existing)
.run(ctx -> {
assertNull(ctx.getStartupFailure());
assertSame(existing, ctx.getBean(ClothoSessionFactory.class));
});
}
@Test
void propertiesDefaultsApply() {
withTinkerGraph(contextRunner).run(ctx -> {
assertNull(ctx.getStartupFailure());
ClothoProperties props = ctx.getBean(ClothoProperties.class);
assertEquals(TraversalDirection.OUT, props.getDefaultDirection());
assertEquals(UnknownTypeBehavior.STRICT, props.getUnknownTypeBehavior());
assertTrue(props.getPackages().isEmpty());
});
}
@Test
void propertiesOverridesApply() {
withTinkerGraph(contextRunner)
.withPropertyValues(
"clotho.default-direction=IN",
"clotho.unknown-type-behavior=GENERIC"
)
.run(ctx -> {
assertNull(ctx.getStartupFailure());
ClothoProperties props = ctx.getBean(ClothoProperties.class);
assertEquals(TraversalDirection.IN, props.getDefaultDirection());
assertEquals(UnknownTypeBehavior.GENERIC, props.getUnknownTypeBehavior());
});
}
@Test
void repositoryIsRegisteredWhenPackageConfigured() {
withTinkerGraph(contextRunner)
.withPropertyValues(
"clotho.packages=com.binarygolem.clotho.spring.config"
)
.run(ctx -> {
assertNull(ctx.getStartupFailure(),
() -> ctx.getStartupFailure() != null
? ctx.getStartupFailure().getMessage() : "");
assertTrue(ctx.containsBean("widgetRepo"),
"WidgetRepo should be registered as 'widgetRepo'");
assertNotNull(ctx.getBean(WidgetRepo.class));
});
}
@Test
void noRepositoriesRegisteredWhenNoPackagesConfigured() {
withTinkerGraph(contextRunner).run(ctx -> {
assertNull(ctx.getStartupFailure());
assertTrue(ctx.getBeansOfType(
com.binarygolem.clotho.repository.ClothoRepository.class).isEmpty());
});
}
}
@@ -0,0 +1,119 @@
package com.binarygolem.clotho.spring.tx;
import com.binarygolem.clotho.session.ClothoSession;
import com.binarygolem.clotho.session.ClothoSessionFactory;
import com.binarygolem.clotho.session.SessionContext;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ClothoTransactionManagerTest {
private final ClothoSessionFactory factory = mock(ClothoSessionFactory.class);
private final ClothoTransactionManager manager = new ClothoTransactionManager(factory);
@AfterEach
void clearThreadLocal() {
// Ensure no session bleeds between tests
ClothoSession bound = SessionContext.get();
if (bound != null) bound.rollback();
}
// --- getTransaction ---
@Test
void getTransaction_opensNewTransactionalSession_whenNoBoundSession() {
ClothoSession session = mock(ClothoSession.class);
when(factory.openTransactionalSession()).thenReturn(session);
// SessionContext has no bound session — simulate by not calling any bind
TransactionStatus status = manager.getTransaction(new DefaultTransactionDefinition());
assertTrue(status.isNewTransaction());
verify(factory).openTransactionalSession();
}
@Test
void getTransaction_joinsExistingSession_whenSessionAlreadyBound() {
// We need an actual session bound to the thread; use a spy-friendly stub
ClothoSession existing = mock(ClothoSession.class);
// Bind it manually via reflection helper (package-private) isn't available;
// instead, call openTransactionalSession mock, get a status, then check a second call
when(factory.openTransactionalSession()).thenReturn(existing);
// First transaction binds the session (simulate by capturing what the manager does)
// We can't bind via SessionContext directly (package-private), so we test the
// second getTransaction() call by verifying isNewTransaction is false when
// openTransactionalSession() has been called and SessionContext already has a value.
// The real behaviour is tested end-to-end in ClothoSessionTransactionTest.
// Here we verify: when SessionContext.get() returns non-null, isNewTransaction is false.
// We cannot inject into SessionContext from outside the package — so we test the
// manager with a real session bound:
when(factory.openTransactionalSession()).thenReturn(mock(ClothoSession.class));
// Outer: binds a session
TransactionStatus outer = manager.getTransaction(new DefaultTransactionDefinition());
assertTrue(outer.isNewTransaction());
// manager.commit() to clean up at end of test — but SessionContext needs to be
// populated by a real ClothoSession. Since the mock doesn't call bind, we can't
// test the join path purely with mocks. So we verify by calling commit() / rollback()
// correctly; the join test is covered in the integration-style session test.
manager.rollback(outer);
}
// --- commit ---
@Test
void commit_closesSessionOnNewTransaction() {
ClothoSession session = mock(ClothoSession.class);
when(factory.openTransactionalSession()).thenReturn(session);
TransactionStatus status = manager.getTransaction(new DefaultTransactionDefinition());
// isNewTransaction == true (no prior bound session since mock doesn't call bind)
manager.commit(status);
verify(session).close();
}
@Test
void commit_doesNotCloseSessionOnNestedTransaction() {
// Build a status where isNewTransaction == false
ClothoSession session = mock(ClothoSession.class);
org.springframework.transaction.support.DefaultTransactionStatus nestedStatus =
new org.springframework.transaction.support.DefaultTransactionStatus(
session, false, false, false, false, null);
manager.commit(nestedStatus);
verify(session, never()).close();
}
// --- rollback ---
@Test
void rollback_callsSessionRollback() {
ClothoSession session = mock(ClothoSession.class);
when(factory.openTransactionalSession()).thenReturn(session);
TransactionStatus status = manager.getTransaction(new DefaultTransactionDefinition());
manager.rollback(status);
verify(session).rollback();
}
@Test
void rollback_callsSessionRollback_onNestedTransaction() {
ClothoSession session = mock(ClothoSession.class);
org.springframework.transaction.support.DefaultTransactionStatus nestedStatus =
new org.springframework.transaction.support.DefaultTransactionStatus(
session, false, false, false, false, null);
manager.rollback(nestedStatus);
verify(session).rollback();
}
}
+341
View File
@@ -0,0 +1,341 @@
# Annotation Reference
## Class-Level Annotations
---
### `@VertexType`
Declares a class as a Clotho-managed vertex type. The class must extend `ClothoVertex`.
```java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface VertexType {
String value(); // ArcadeDB vertex type name (required)
String[] additionalParents() // ArcadeDB parent type names beyond Java hierarchy
default {}; // Use for diamond inheritance
String parentLabel() // Explicit ArcadeDB parent when Java hierarchy diverges
default "";
}
```
**Examples:**
```java
// Simple
@VertexType("Employee")
public class Employee extends ClothoVertex { }
// Abstract type
@VertexType("Person")
public abstract class Person extends ClothoVertex { }
// Diamond inheritance
@VertexType(value = "ContractEmployee", additionalParents = {"Contractor"})
public class ContractEmployee extends Employee { }
// Divergent Java/ArcadeDB hierarchy
@VertexType(value = "ExternalWorker", parentLabel = "Employee")
public class ExternalWorker extends ClothoVertex { }
```
---
### `@EdgeType`
Declares a class as a Clotho-managed edge type. The class must extend `ClothoEdge`.
```java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EdgeType {
String value(); // ArcadeDB edge type name (required)
}
```
**Example:**
```java
@EdgeType("WORKS_AT")
public class WorksAt extends ClothoEdge {
public static final String LABEL = "WORKS_AT";
// ...
}
```
Convention: define `LABEL` as a constant on the edge class to avoid magic strings at call
sites when referencing the label in `@Via`.
---
### `@SubgraphType`
Declares a composite type assembled from a Gremlin `select()` traversal. Must NOT extend
`ClothoVertex` or `ClothoEdge`. Has no ARID.
```java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SubgraphType {
}
```
**Example:**
```java
@SubgraphType
public class EmployeeProfile {
Employee employee;
Manager manager;
@Alias("dept") Department department;
List<WorksAt> workHistory;
}
```
---
## Field-Level Annotations
---
### `@RID`
Marks the field that holds the element's `ARID`. Inherited from `ClothoEntity`; generally
not needed unless overriding the base class field.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RID {
}
```
---
### `@Property`
Maps a field to an ArcadeDB vertex or edge property. Optional when the field name exactly
matches the property name.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String value(); // ArcadeDB property name
}
```
**Example:**
```java
@Property("startDate") LocalDate start; // field name differs from property name
LocalDate endDate; // no annotation needed; names match
```
---
### `@Include`
Marks a field as part of this object's eager-load boundary. Always paired with `@Via`.
The field type must be a `@VertexType` class, an `@EdgeType` class, or a `List<>` of either.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Include {
}
```
---
### `@Via`
Specifies the ArcadeDB edge label to traverse for an `@Include` field.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Via {
String value(); // Edge label (required)
}
```
**Strongly preferred pattern** — use the edge class's `LABEL` constant:
```java
@Include @Via(WorksAt.LABEL)
List<WorksAt> workHistory;
```
---
### `@Direction`
Specifies which edge direction to follow for an `@Include` + `@Via` traversal.
Defaults to `OUT` (or the global configured default).
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Direction {
Direction value() default Direction.OUT;
}
public enum Direction { OUT, IN, BOTH }
```
**Example:**
```java
@Include @Via("ASSIGNED_TO") @Direction(Direction.IN)
List<Task> assignedTasks;
```
---
### `@OutVertex`
On an `@EdgeType` class: marks the field holding the out-vertex (source) of the edge.
The field type must be a `@VertexType` class.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface OutVertex {
}
```
---
### `@InVertex`
On an `@EdgeType` class: marks the field holding the in-vertex (target) of the edge.
The field type must be a `@VertexType` class.
Omitting `@InVertex` entirely = edge-only inclusion; the target vertex is not loaded.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface InVertex {
}
```
---
### `@Alias`
On a `@SubgraphType` field: specifies the Gremlin `as()` alias that this field is bound
to. Defaults to the field name when omitted.
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Alias {
String value();
}
```
**Example:**
```java
@Alias("dept")
Department department; // binds to .as("dept") in the Gremlin query
```
---
## Query Annotations
---
### `@Query`
Declares a Gremlin traversal. Used on `@ClothoRepository` interface methods (primary use)
or on `@VertexType` classes as named queries (secondary use).
```java
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Queries.class) // allows multiple @Query on a class (different names)
public @interface Query {
String value() default ""; // Gremlin string (for method use)
String name() default ""; // Named query identifier (for class-level use)
String gremlin() default ""; // Gremlin string (for class-level use; alias for clarity)
boolean mapResult() default true; // false = return raw Gremlin result
}
```
**Examples:**
```java
// On a repository method
@Query("g.V().hasLabel('Employee').has('dept',:dept)")
List<Employee> findByDepartment(@Param("dept") String dept);
// Raw result — no Clotho mapping
@Query(value = "g.V().hasLabel('Employee').count()", mapResult = false)
long countAll();
// Named query on a class
@VertexType("Order")
@Query(name = "openForCustomer",
gremlin = "g.V().has('Customer','id',:custId).out('PLACED').has('status','OPEN')")
public class Order extends ClothoVertex { ... }
```
---
### `@Param`
Binds a method parameter to a named placeholder in a `@Query` Gremlin string.
```java
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Param {
String value(); // placeholder name (without the colon)
}
```
**Example:**
```java
@Query("g.V().has('Employee','dept',:dept).has('level',:level)")
List<Employee> findByDeptAndLevel(
@Param("dept") String department,
@Param("level") int level);
```
---
## Spring Annotation
---
### `@ClothoRepository`
Marks an interface as a Clotho query interface. The `clotho-spring-boot-starter` scans for
these interfaces and registers a dynamic proxy as a Spring bean.
```java
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ClothoRepository {
}
```
**Example:**
```java
@ClothoRepository
public interface OrderQueries {
@Query("g.V().has('Order','status','OPEN')")
List<Order> findOpenOrders();
}
```
Inject via Spring as you would any repository:
```java
@Autowired OrderQueries orderQueries;
```
+248
View File
@@ -0,0 +1,248 @@
# Architecture
## Module Overview
```
clotho-core
Zero Spring dependency.
All mapping, session, registry, and query logic.
clotho-spring-boot-starter
Spring Boot 3.x autoconfiguration.
Thin layer: creates beans, bridges @Transactional, scans @ClothoRepository.
Depends on clotho-core.
clotho-dev-app
Minimal Spring Boot application.
Connected to a live ArcadeDB instance.
Used throughout development for real-DB testing.
Not a production artifact; not published.
```
---
## clotho-core Component Map
```
ClothoSessionFactory (entry point)
│ Holds: DriverRemoteConnection, TypeRegistry, global config
│
├── TypeRegistry
│ Built once at startup from classpath scan.
│ Maps: ArcadeDB label → Class<? extends ClothoEntity>
│ Knows: Java + ArcadeDB inheritance hierarchy, additionalParents
│
└── ClothoSession (unit of work, one per transaction/request)
│ Holds: identity map (ARID → ClothoEntity instance)
│
├── load(Class<T>, ARID) → T
│ └── SubgraphLoader
│ Uses: TypeRegistry, ObjectMapper
│ Executes Gremlin traversal for root vertex + @Include boundary
│ Cycle detection via visited-ARID set
│
├── save(entity)
│ └── SubgraphPersistor
│ Upserts root vertex/edge + all @Include elements recursively
│ Uses ArcadeDB @version for optimistic locking
│ @SubgraphType: iterates all ClothoEntity fields, saves each
│
├── delete(entity)
│ Removes root vertex/edge from graph
│ Does NOT cascade deletion to @Include elements
│
└── query(Class<T>, queryName, params) → List<T>
└── QueryExecutor
Resolves named @Query, binds params, executes, maps results
Also drives @ClothoRepository proxy methods
ObjectMapper (used by SubgraphLoader and QueryExecutor)
Gremlin Vertex/Edge → ClothoEntity subclass
Always uses most-specific registered class (TypeRegistry lookup by label)
Sets @Property fields, @OutVertex/@InVertex fields on edges
SubgraphTypeAssembler (used by QueryExecutor for @SubgraphType returns)
Maps Gremlin select() result map → @SubgraphType fields
Binding: field name or @Alias → select key
Each bound value is mapped via ObjectMapper
```
---
## Data Flow: Loading a Composite Object
```
Developer: session.load(Order.class, arid)
│
▼
SubgraphLoader
1. g.V(arid.asString()) → TinkerPop Vertex (Order)
2. ObjectMapper.map(vertex) → Order instance (most-specific class)
3. Register in identity map
4. For each @Include field on Order:
@Include @Via("HAS_LINE") List<OrderLine> lines
┌──────────────────────────────────────────┐
│ g.V(arid).out("HAS_LINE") │
│ → [TinkerPop Vertex, Vertex, ...] │
│ for each: ObjectMapper.map(v) │
│ → OrderLine (or subtype by label) │
│ recurse: load OrderLine @Include fields│
└──────────────────────────────────────────┘
5. Assemble Order.lines = [OrderLine, ...]
6. Return fully assembled Order
```
---
## Data Flow: Saving a Composite Object
```
Developer: session.save(order)
│
▼
SubgraphPersistor
1. Upsert root Order vertex
if order.getId() == null → create vertex with label "Order"
else → update vertex, check @version (optimistic lock)
2. For each @Include field on Order:
Field type is @VertexType (e.g., List<OrderLine>):
for each element → recursively save (SubgraphPersistor.save(orderLine))
ensure edge "HAS_LINE" exists from Order to OrderLine
Field type is @EdgeType (e.g., List<WorksAt>):
save edge properties; ensure @OutVertex and @InVertex are already persisted
3. Identity map deduplication: elements already saved in this call are skipped
4. Removed elements: NOT deleted automatically
```
---
## Data Flow: `@Query` on a `@ClothoRepository`
```
Developer: employeeQueries.findByDepartment("Engineering")
│
▼
ClothoRepository proxy (generated by QueryExecutor at startup)
1. Read @Query gremlin string from method annotation
2. Bind @Param values: replace :dept with "Engineering"
3. Execute: g.V().hasLabel('Employee').has('dept','Engineering')
4. For each result vertex:
ObjectMapper.map(vertex) → most-specific Employee subclass
5. Return List<Employee>
```
For `@SubgraphType` return:
```
3. Execute query with select() → List of Maps
4. For each Map:
SubgraphTypeAssembler.assemble(EmployeeProfile.class, map)
→ bind map keys to fields by name / @Alias
→ ObjectMapper.map() each value
5. Return List<EmployeeProfile>
```
---
## Session Identity Map
The identity map is the session's in-memory cache of loaded vertices and edges.
- Key: `ARID`
- Value: `ClothoEntity` instance
Rules:
- First load of an ARID → fetch from DB, map to Java, store in map, return
- Subsequent load of same ARID → return existing instance (no DB call)
- `save()` does NOT clear the identity map; the instance is mutated in place
- `close()` clears the map and releases the Gremlin connection
The map operates at the individual vertex/edge level. Multiple composite objects (e.g., an
`Order` and an `EmployeeProfile`) may both hold references to the same `Address` instance
if their traversals reached the same ARID.
---
## TypeRegistry Startup Validation
At `ClothoSessionFactory.build()` time, the TypeRegistry validates:
- Every `@VertexType` class extends `ClothoVertex`
- Every `@EdgeType` class extends `ClothoEdge`
- No two classes claim the same label
- `additionalParents` labels are resolvable to registered classes
- `parentLabel` values are resolvable to registered classes
- Every `@Include` field is paired with `@Via`
- `@OutVertex` / `@InVertex` field types are `@VertexType` classes
Startup failure with a descriptive message is strongly preferred over silent misconfiguration
that produces confusing runtime errors.
---
## Package Structure
```
com.binarygolem.clotho
.model
ClothoEntity
ClothoVertex
ClothoEdge
ARID
UnknownTypeBehavior
.annotation
VertexType
EdgeType
SubgraphType
RID
Property
Include
Via
Direction
OutVertex
InVertex
Alias
Query
Queries (container for @Repeatable @Query)
Param
ClothoRepository
.session
ClothoSession
ClothoSessionFactory
ClothoSessionFactoryBuilder
.registry
TypeRegistry
TypeRegistryBuilder
TypeDescriptor (holds metadata for one registered type)
.mapping
ObjectMapper
SubgraphLoader
SubgraphPersistor
SubgraphTypeAssembler
.query
QueryExecutor
QueryDescriptor (holds parsed @Query metadata for one method)
ParameterBinder
.exception
ClothoException
UnknownTypeException
OptimisticLockException
ClothoConfigurationException
// clotho-spring-boot-starter
com.binarygolem.clotho.spring
.config
ClothoAutoConfiguration
ClothoProperties
.tx
ClothoTransactionManager
ClothoTransactionObject
.repository
ClothoRepositoryScanner
ClothoRepositoryProxyFactory
```
+686
View File
@@ -0,0 +1,686 @@
# Getting Started with Clotho
Clotho is a Java OGM (Object-Graph Mapper) for ArcadeDB built on Apache TinkerPop/Gremlin.
A "Clotho object" is not a single vertex — it is a **subgraph**: a root vertex plus a declared
set of edges and adjacent vertices that are loaded atomically in a single Gremlin traversal.
---
## Prerequisites
| Requirement | Version |
|---|---|
| Java | 21 |
| Maven | 3.9+ |
| ArcadeDB | any recent release |
| Spring Boot | 3.x (optional — Clotho also works standalone) |
Clotho is **schema-first**: it maps to a schema you have already created in ArcadeDB.
It does not generate DDL.
---
## 1. Maven dependency
```xml
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-spring-boot-starter</artifactId>
<version>0.1.0-SNAPSHOT</version>
</dependency>
```
Use `clotho-core` instead if you are not using Spring Boot.
---
## 2. ArcadeDB schema
Create the required types in ArcadeDB before starting your application.
Use the ArcadeDB console, HTTP API, or any migration tool:
```sql
-- Vertices
CREATE VERTEX TYPE Person;
CREATE PROPERTY Person.name STRING;
CREATE PROPERTY Person.email STRING;
CREATE PROPERTY Person.age INTEGER;
CREATE VERTEX TYPE Company;
CREATE PROPERTY Company.name STRING;
CREATE PROPERTY Company.industry STRING;
-- Edge
CREATE EDGE TYPE WORKS_AT;
CREATE PROPERTY WORKS_AT.role STRING;
CREATE PROPERTY WORKS_AT.startYear INTEGER;
```
---
## 3. Spring Boot configuration
```properties
# application.properties
clotho.gremlin.url=ws://localhost:8182/gremlin
clotho.gremlin.username=root
clotho.gremlin.password=playwithdata
clotho.gremlin.traversal-source=g
# Packages to scan for @VertexType, @EdgeType, @ClothoRepository
clotho.packages=com.example.myapp
# Whether unknown graph labels cause an exception (STRICT) or map to a generic type (IGNORE_AND_MAP_TO_GENERIC)
clotho.unknown-type-behavior=STRICT
# Default traversal direction for @Include fields that have no @Direction annotation
clotho.default-direction=OUT
```
---
## 4. Define entity classes
### Vertex type
```java
@VertexType("Person")
@Getter
public class Person extends ClothoVertex {
@Property("name")
private @Nullable String name;
@Property("email")
private @Nullable String email;
@Property("age")
private @Nullable Integer age;
// Eagerly loaded when Person is fetched — single Gremlin project() query
@Include
@Via("WORKS_AT")
private @Nullable List<WorksAt> jobs;
// Manual setters call notifyFieldChanged() so Clotho tracks which fields changed.
// Do NOT use Lombok @Setter on @Property, @Include, @OutVertex, @InVertex, or @Version fields.
public void setName(@Nullable String name) {
this.name = name;
notifyFieldChanged("name");
}
public void setEmail(@Nullable String email) {
this.email = email;
notifyFieldChanged("email");
}
public void setAge(@Nullable Integer age) {
this.age = age;
notifyFieldChanged("age");
}
public void setJobs(@Nullable List<WorksAt> jobs) {
this.jobs = jobs;
notifyFieldChanged("jobs");
}
}
```
### Edge type
```java
@EdgeType("WORKS_AT")
@Getter
public class WorksAt extends ClothoEdge {
@Property("role")
private @Nullable String role;
@Property("startYear")
private @Nullable Integer startYear;
@OutVertex
private @Nullable Person person; // populated when edge is loaded via @Include
@InVertex
private @Nullable Company company; // populated when edge is loaded via @Include
public void setRole(@Nullable String role) {
this.role = role;
notifyFieldChanged("role");
}
public void setStartYear(@Nullable Integer startYear) {
this.startYear = startYear;
notifyFieldChanged("startYear");
}
public void setCompany(@Nullable Company company) {
this.company = company;
notifyFieldChanged("company");
}
}
```
---
## 5. Using the session
`ClothoSession` is the primary unit of work. Open one per logical operation, then close it.
Sessions are **not thread-safe** — use one per thread or virtual thread.
```java
@Service
@RequiredArgsConstructor
public class PersonService {
private final ClothoSessionFactory sessionFactory;
/** Create a person with an employment edge. */
public void createPersonWithJob(String name, String role, String companyName) {
try (ClothoSession session = sessionFactory.openSession()) {
Company company = new Company();
company.setName(companyName);
company.setIndustry("Technology");
WorksAt job = new WorksAt();
job.setRole(role);
job.setStartYear(2024);
job.setCompany(company); // @InVertex — resolved during edge creation
Person person = new Person();
person.setName(name);
person.setJobs(List.of(job));
session.save(person);
// cascade: person → job → company (all created in order)
System.out.println("Created: " + person.getId());
}
}
/** Load a person — jobs are populated atomically with the vertex. */
public Person findById(ARID id) {
try (ClothoSession session = sessionFactory.openSession()) {
return session.load(Person.class, id);
// person.getJobs() is already populated — no extra round-trip
}
}
/** Update — only the fields you changed are written. */
public void promoteEmployee(ARID personId, String newRole) {
try (ClothoSession session = sessionFactory.openSession()) {
Person person = session.load(Person.class, personId);
if (person.getJobs() != null && !person.getJobs().isEmpty()) {
person.getJobs().get(0).setRole(newRole);
session.save(person);
// only role is written; no other properties touched
}
}
}
/** Auto-save — dirty MANAGED entities are saved when the session closes. */
public void updateEmailAutoSave(ARID personId, String newEmail) {
try (ClothoSession session = sessionFactory.openSession()) {
Person person = session.load(Person.class, personId);
person.setEmail(newEmail);
// no explicit save() — session.close() persists dirty entities
}
}
/** Delete a person — ArcadeDB also removes all incident edges. */
public void deletePerson(ARID id) {
try (ClothoSession session = sessionFactory.openSession()) {
Person person = session.load(Person.class, id);
session.delete(person);
}
}
}
```
---
## 6. Session lifecycle
### What a session is
A `ClothoSession` is a unit of work. It wraps a graph connection, keeps an **identity map**
(same ARID → same Java instance within a session), tracks dirty fields, and auto-saves
managed entities when it closes. Sessions are **not thread-safe** — never share one across
threads.
### Short-lived sessions (recommended default)
Open a session with try-with-resources. The session closes — and auto-saves any dirty
entities — at the end of the block:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, id);
alice.setEmail("new@example.com");
} // auto-saves alice here
```
This is the right pattern for web request handlers, background jobs, and any operation
with a clear start and end.
### Long-lived sessions
For a simple single-threaded process (a CLI tool, a startup task, a scheduled job that
runs on one thread), you can keep one session open for as long as you need:
```java
ClothoSession session = sessionFactory.openSession();
// ... do many things ...
session.close(); // or call in a shutdown hook
```
The trade-off is that the **identity map grows indefinitely** — every entity loaded stays
in memory until the session closes. For long-running processes that load many entities,
call `session.clearCache()` periodically to release them without closing the session:
```java
// After a large batch operation — drop all cached instances from memory.
// The next load() for any of those IDs will re-fetch from the graph.
session.clearCache();
```
`clearCache()` does NOT flush dirty fields first. Call `session.save(entity)` explicitly
for anything you want to keep before clearing.
### Do you ever need more than one session?
**Multiple threads: yes, one per thread.**
Sessions bind to the current thread via a `ThreadLocal`. Start a new session on each
thread (or virtual thread) and close it when the thread's work is done.
```java
// With virtual threads (Java 21+):
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
executor.submit(() -> {
try (ClothoSession session = sessionFactory.openSession()) {
// ... work on this virtual thread ...
}
});
}
```
**Multiple isolated operations on the same thread: open them sequentially.**
Each `openSession()` call replaces the previous thread-local binding, so open only one
session at a time on any given thread. Close the first before opening the second:
```java
// First operation
try (ClothoSession s1 = sessionFactory.openSession()) {
session.load(Person.class, id);
}
// Second operation — clean identity map, independent unit of work
try (ClothoSession s2 = sessionFactory.openSession()) {
session.load(Person.class, id); // fresh load, not the cached s1 instance
}
```
**Spring Boot — session-per-request:**
The `clotho-spring-boot-starter` provides a `ClothoSessionFactory` bean. Wire it into
your `@Service` classes and open a session per method (as shown in section 5), or use a
request-scoped session bean if you want one session for the lifetime of an HTTP request:
```java
@Bean
@RequestScope
public ClothoSession requestSession(ClothoSessionFactory factory) {
return factory.openSession();
}
```
Declare the bean as `@RequestScope` and Spring will open it on the first injection and
call `close()` (triggering auto-save) at the end of the request.
### Transactional sessions
By default, each Gremlin traversal is auto-committed immediately by ArcadeDB. If a
multi-step save fails midway, the graph is left in a partial state. Use a **transactional
session** to wrap all operations in a single atomic transaction:
```java
try (ClothoSession session = sessionFactory.openTransactionalSession()) {
session.save(alice);
session.save(acme);
} // ← tx.commit() fires here; any exception triggers tx.rollback()
```
With the Spring Boot starter you can use `@Transactional` instead of managing the
session manually. `ClothoTransactionManager` is registered automatically:
```java
@Service
@RequiredArgsConstructor
public class PersonService {
private final ClothoSessionFactory sessionFactory;
@Transactional
public void promote(ARID personId) {
try (ClothoSession session = sessionFactory.openSession()) { // borrows tx session
Person p = session.load(Person.class, personId);
p.setRole("SENIOR");
} // session close is a no-op; Spring tx manager commits on method return
}
}
```
Inside a `@Transactional` method, `openSession()` detects the existing transaction and
borrows its session rather than opening a new one. The transaction is committed (or rolled
back) when the outermost `@Transactional` boundary exits.
See [docs/TRANSACTIONS.md](TRANSACTIONS.md) for a complete guide including nested
transactions, multi-manager setups, and the interaction with `@Version` optimistic locking.
### Summary
| Scenario | Pattern |
|---|---|
| Web request / discrete operation | `try (ClothoSession s = factory.openSession())` |
| Atomic multi-step write | `try (ClothoSession s = factory.openTransactionalSession())` |
| Spring `@Transactional` | Annotate service method; use `openSession()` inside |
| Single-threaded background process | Open once; call `clearCache()` after big batches |
| Multi-threaded / virtual threads | One session per thread, opened and closed on that thread |
| Spring HTTP request scope | `@Bean @RequestScope ClothoSession` |
---
## 7. Repository pattern
Define a repository by extending `ClothoRepository<T>` and annotating with `@ClothoRepository`.
The Spring Boot starter registers it as a bean automatically.
```java
@ClothoRepository
public class PersonRepository extends ClothoRepository<Person> {
public PersonRepository(ClothoSessionFactory factory) {
super(factory);
}
// Built-in: findAll(), findById(), count(), save(), delete(), findWithPagination()
public List<Person> findByName(String name) {
return execute(g().V().has("Person", "name", name));
}
public List<Person> findByAgeGreaterThan(int minAge) {
return execute(allEntities(), t -> t.has("age", P.gt(minAge)));
}
public List<Person> findEmployed() {
// people who have at least one outgoing WORKS_AT edge
return execute(allEntities(), t -> t.where(__.outE("WORKS_AT")));
}
public long countByIndustry(String industry) {
// raw result — no Clotho mapping
return this.<Long>executeRaw(
g().V().has("Company", "industry", industry).count()
).get(0);
}
}
```
Inject the repository in your service:
```java
@Service
@RequiredArgsConstructor
public class PersonService {
private final PersonRepository personRepository;
public List<Person> listSeniorEngineers() {
return personRepository.findByAgeGreaterThan(35);
}
public List<Person> listAll() {
return personRepository.findAll(); // inherited
}
public List<Person> listPage(long page, long pageSize) {
return personRepository.findWithPagination(page * pageSize, pageSize); // inherited
}
}
```
---
## 8. Ad-hoc traversals from a loaded entity
Repository methods can traverse any edge in the graph — there is no requirement that the
edge be declared as `@Include` on the entity class. Start from the loaded entity's ID and
write a Gremlin traversal as usual.
**Example: find co-workers** — people who share a company via `WORKS_AT`, but where
`WORKS_AT` is not declared as `@Include` on `Person`:
```java
@ClothoRepository
public class PersonRepository extends ClothoRepository<Person> {
// ...
public List<Person> findCoworkers(Person person) {
return execute(
g().V(person.getId().asString()).as("self")
.out("WORKS_AT") // Person → Company
.in("WORKS_AT") // Company → all Persons at that company
.where(P.neq("self")) // exclude the starting person
);
}
}
```
Call it with any already-loaded `Person`:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, aliceId);
List<Person> coworkers = personRepository.findCoworkers(alice);
// returned Person objects have their @Include fields populated (jobs, etc.)
}
```
**Key point:** `execute()` maps every resulting vertex to its most-specific registered
Clotho type and calls `populateAll()` on the result list, so the returned objects are fully
hydrated (all eager `@Include` fields present) — regardless of how the traversal was built.
The object boundary and the query traversal are completely independent concerns.
### Tracked results — execute with a session
By default, `execute()` returns **detached** entities: they are not registered in any
session and mutations are silently ignored. Pass a `ClothoSession` to get back **MANAGED**
entities instead — dirty-field tracking fires, and the session auto-saves any changes when
it closes:
```java
public List<Person> findCoworkers(Person person, ClothoSession session) {
return execute(session,
g().V(person.getId().asString()).as("self")
.out("WORKS_AT").in("WORKS_AT")
.where(P.neq("self"))
);
}
```
```java
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, aliceId);
List<Person> coworkers = personRepository.findCoworkers(alice, session);
// Mutations are tracked — no explicit save() needed
coworkers.get(0).setEmail("new@example.com");
} // ← session.close() auto-saves the dirty co-worker
```
`session.register(vertex)` is the underlying mechanism — it recursively marks the vertex
and all entities reachable through its `@Include` boundary as MANAGED and adds them to the
session's identity map. You can call it directly if you need finer control.
For raw scalar results (counts, aggregates), use `executeRaw()`:
```java
public long countCoworkers(Person person) {
return this.<Long>executeRaw(
g().V(person.getId().asString())
.out("WORKS_AT").in("WORKS_AT")
.where(P.neq("self"))
.count()
).get(0);
}
```
---
## 9. Object boundary with @Include
`@Include @Via("EDGE_LABEL")` declares that a field is part of this object's boundary.
All `@Include` fields on a vertex are loaded in a single atomic `project()` traversal —
no N+1 queries, no risk of seeing inconsistent state between fields.
```java
@VertexType("Department")
@Getter
public class Department extends ClothoVertex {
@Property("name") private @Nullable String name;
// EAGER (default): loaded with the vertex, always present
@Include
@Via("HAS_MANAGER")
private @Nullable Person manager;
// LAZY: skipped on initial load; call session.loadField() when needed
@Include(fetchType = FetchType.LAZY)
@Via("HAS_MEMBER")
private @Nullable List<Person> members;
}
```
Load a lazy field on demand:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Department dept = session.load(Department.class, deptId);
// dept.getMembers() is null here — field was declared LAZY
session.loadField(dept, "members");
// dept.getMembers() is now populated
log.info("Members: {}", dept.getMembers().size());
}
```
---
## 10. Optimistic locking with @Version
ArcadeDB maintains a `@version` counter on every record that increments on each write.
Clotho reads it on load and includes it in update traversals, so concurrent writes are detected.
```java
@VertexType("Order")
@Getter
public class Order extends ClothoVertex {
@Property("status") private @Nullable String status;
@Version // maps to ArcadeDB's built-in @version property
private @Nullable Long version;
public void setStatus(@Nullable String status) {
this.status = status;
notifyFieldChanged("status");
}
}
```
If two sessions load the same Order and both try to save a change, the second save throws
`OptimisticLockException`:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Order order = session.load(Order.class, orderId);
order.setStatus("SHIPPED");
session.save(order);
} catch (OptimisticLockException e) {
log.warn("Concurrent update detected for {} at version {}",
e.getId(), e.getExpectedVersion());
// retry or report conflict
}
```
---
## 11. Subgraph queries
Use `executeSubgraph()` when a traversal returns multiple entity types in a single result row.
```java
@SubgraphType
public class EmployeeProfile {
Person person; // field name matches .as("person") in the Gremlin query
@Alias("employer")
Company company; // @Alias maps the field to a different Gremlin alias
}
```
```java
@ClothoRepository
public class EmployeeRepo extends ClothoRepository<Person> {
public EmployeeRepo(ClothoSessionFactory factory) { super(factory); }
public List<EmployeeProfile> findProfiles() {
return executeSubgraph(EmployeeProfile.class,
g().V().hasLabel("Person").as("person")
.out("WORKS_AT").in("WORKS_AT").as("company") // traverse to Company
.select("person", "company"));
}
}
```
---
## 12. Type inheritance
Define a class hierarchy in Java and tell Clotho which ArcadeDB parent types to wire:
```java
@VertexType(value = "Employee", additionalParents = {"Person"})
public class Employee extends Person {
@Property("employeeNumber") private @Nullable String employeeNumber;
// ...
}
```
When Clotho loads a vertex labeled `Employee`, it maps it to `Employee.class`.
When it loads a vertex labeled `Person` (no `Employee` subtype), it maps it to `Person.class`.
This "most specific type wins" rule is enforced by the `TypeRegistry`.
---
## Reference docs
| Document | Contents |
|---|---|
| `docs/TYPE_SYSTEM.md` | Entity hierarchy, inheritance, label resolution |
| `docs/OBJECT_BOUNDARY.md` | `@Include`/`@Via`, multi-hop, edge-only inclusion, cycle detection |
| `docs/ANNOTATIONS.md` | Complete annotation reference |
| `docs/QUERY_MODEL.md` | Repository pattern, `executeSubgraph`, result mapping |
| `docs/SPRING_INTEGRATION.md` | Autoconfigure, properties reference |
| `docs/ARCHITECTURE.md` | Module breakdown, session lifecycle, data flow |
The `clotho-dev-app` module contains a runnable `FeatureDemo` that exercises all the patterns
described here against a live ArcadeDB instance.
+165
View File
@@ -0,0 +1,165 @@
# Object Boundary
## What Is the Object Boundary?
Clotho has no lazy loading. When you call `session.load(Employee.class, rid)`, you receive the
fully assembled object — root vertex plus everything within its declared boundary — in one
operation. Nothing is deferred.
The **object boundary** is the set of edges and vertices Clotho traverses and assembles when
loading a `@VertexType` instance. It is declared entirely in the Java class using `@Include`
and `@Via`. Everything outside the boundary is accessed via `@Query` traversals written by
the developer.
---
## Declaring the Boundary: `@Include` and `@Via`
```java
@VertexType("Order")
public class Order extends ClothoVertex {
String status;
@Include @Via("HAS_LINE")
List<OrderLine> lines;
@Include @Via("HAS_BILLING_ADDRESS")
Address billingAddress;
}
```
- `@Include` marks the field as part of this object's boundary.
- `@Via` specifies the ArcadeDB edge label to traverse.
- The field type determines what is loaded (see below).
Both annotations are required together. `@Include` without `@Via` is a compile-time error.
---
## What Gets Loaded: Field Type Rules
### Field type is a `@VertexType` class
Clotho traverses the edge, loads the target vertex (and its own boundary recursively),
and discards the edge itself (edge properties are not available).
```java
@Include @Via("HAS_BILLING_ADDRESS")
Address billingAddress; // Address is a @VertexType; edge properties ignored
```
### Field type is an `@EdgeType` class
Clotho loads the full edge object — edge properties, plus `@OutVertex` and `@InVertex`
fields if declared on the edge class.
```java
@Include @Via("HAS_LINE")
List<OrderLineEdge> lines; // OrderLineEdge is an @EdgeType; edge props + vertices loaded
```
### Edge-only inclusion (no `@InVertex` on the edge class)
When the `@EdgeType` class declares no `@InVertex` field, the target vertex is not fetched.
Useful when you need the edge's own properties but not the vertex it points to.
```java
@EdgeType("TAGGED_WITH")
public class TagEdge extends ClothoEdge {
@OutVertex Order order;
// No @InVertex — Tag vertex is never loaded
String tagValue;
int weight;
}
// In Order:
@Include @Via("TAGGED_WITH")
List<TagEdge> tags; // Only edge properties; Tag vertices stay in the DB
```
---
## Edge Direction
Default direction is `OUT` (follow outgoing edges from the current vertex).
Override per field with `@Direction`:
```java
@Include @Via("ASSIGNED_TO") @Direction(Direction.IN)
List<Task> assignedTasks; // follow INCOMING ASSIGNED_TO edges to find tasks
@Include @Via("CONNECTED") @Direction(Direction.BOTH)
List<Node> neighbors; // follow edges in both directions
```
The global default can be changed in session factory configuration:
```properties
clotho.default-direction=OUT
```
---
## Multi-Hop Boundaries
`@Include` is applied recursively. If `OrderLine` itself has `@Include` fields, they are
loaded as part of loading `Order`.
```java
@VertexType("Order")
public class Order extends ClothoVertex {
@Include @Via("HAS_LINE")
List<OrderLine> lines; // hop 1
}
@VertexType("OrderLine")
public class OrderLine extends ClothoVertex {
int quantity;
BigDecimal unitPrice;
@Include @Via("HAS_NOTE")
List<Note> notes; // hop 2 — loaded as part of Order
}
```
Loading an `Order` traverses: `Order → HAS_LINE → OrderLine → HAS_NOTE → Note`.
There is no depth limit. The developer is responsible for designing boundaries that do not
load unbounded portions of the graph.
---
## Cycle Detection
Clotho tracks visited ARIDs during a boundary load. If a traversal reaches a vertex it has
already loaded in the current operation, it uses the existing instance and stops traversing
further — it does not loop. The developer still bears responsibility for not creating
boundaries that load huge subgraphs.
---
## Persistence of Boundary Elements
When `session.save(order)` is called:
1. The root `Order` vertex is upserted (created if ARID is null, updated if set).
2. Each `@Include` field is recursively persisted in the same way.
3. Elements reachable via multiple paths are saved exactly once (identity map deduplication).
4. **Removed items are NOT automatically deleted.** If you remove an `OrderLine` from
`order.lines`, calling `save()` does not delete the `OrderLine` vertex or its edges.
Call `session.delete(orderLine)` explicitly.
---
## Design Guidance
The boundary should reflect **ownership**, not just connectivity. Include elements that:
- Are always loaded and managed together with the root
- Are not meaningful without the root (e.g., `OrderLine` without `Order`)
- Form a bounded transaction unit
Do NOT include:
- Large, unbounded collections (e.g., all products a customer ever bought)
- Elements that are independently meaningful and queried on their own
- Elements reachable via long traversal chains across the domain
For everything outside the boundary, write a `@Query` on a `@ClothoRepository` interface.
+194
View File
@@ -0,0 +1,194 @@
# Query Model
## Philosophy
Graph databases excel at complex relationship queries. That complexity belongs in the
developer's Gremlin code, not inside the ORM. Clotho's query model is a **bridge**:
- Developer writes a Gremlin traversal
- Clotho executes it and maps the results back to registered Java types
- Developer injects the repository interface like any Spring bean
---
## `@ClothoRepository` Interfaces
The primary way to define queries. Clotho generates a dynamic proxy at startup.
```java
@ClothoRepository
public interface EmployeeQueries {
@Query("g.V().hasLabel('Employee').has('dept',:dept)")
List<Employee> findByDepartment(@Param("dept") String dept);
@Query("""
g.V().has('Employee','id',:id)
.repeat(out('MANAGES')).times(2).emit()
.dedup()
""")
List<Employee> findTwoLevelsOfReports(@Param("id") String managerId);
}
```
```java
@Autowired EmployeeQueries employeeQueries;
List<Employee> staff = employeeQueries.findByDepartment("Engineering");
```
---
## Parameter Binding
Use `:paramName` placeholders in the Gremlin string and `@Param("paramName")` on the
corresponding method parameter.
```java
@Query("g.V().has('Order','status',:status).has('total',gt(:minTotal))")
List<Order> findByStatusAndMinTotal(
@Param("status") String status,
@Param("minTotal") BigDecimal minTotal);
```
Clotho substitutes parameters before executing the traversal. Parameter types are passed
as-is to Gremlin — use Java types that Gremlin/ArcadeDB understands (String, int, long,
double, boolean, LocalDate, etc.).
---
## Return Type Rules
The declared return type tells Clotho how to map the traversal result.
### `@VertexType` or `@EdgeType` class
Clotho maps each result element to the most specific registered class matching its label.
The declared type is the upper bound.
```java
// May return Employee, HourlyEmployee, SalariedEmployee — all ClothoVertex subtypes
List<Employee> findAll();
// Explicitly mixed: any registered @VertexType
List<ClothoVertex> findAllVertices();
```
When the return type is a single object (not a `List`), Clotho returns the first result or
`null` if none.
```java
@Nullable
@Query("g.V().has('Employee','id',:id)")
Employee findById(@Param("id") String id);
```
### `@SubgraphType` class
When the return type is annotated `@SubgraphType`, Clotho expects the traversal to return a
`select()` map. It maps each key to the matching field by name (or by `@Alias`).
```java
@Query("""
g.V().has('Employee','id',:id).as('employee')
.out('MANAGED_BY').as('manager')
.out('IN_DEPT').as('dept')
.select('employee','manager','dept')
""")
EmployeeProfile loadProfile(@Param("id") String id);
```
```java
@SubgraphType
public class EmployeeProfile {
Employee employee; // bound to key "employee"
Manager manager; // bound to key "manager"
@Alias("dept") Department department; // bound to key "dept"
}
```
If the traversal returns a list of select maps, declare `List<EmployeeProfile>`.
### Raw result (no mapping)
Set `mapResult = false` to receive the Gremlin result directly without Clotho mapping.
Return type can be a scalar, `List<Object>`, or any type Gremlin produces.
```java
@Query(value = "g.V().hasLabel('Employee').count()", mapResult = false)
long countEmployees();
@Query(value = "g.V().has('Order','id',:id).values('status')", mapResult = false)
String getOrderStatus(@Param("id") String id);
```
---
## Named Queries on `@VertexType` Classes
An alternative to repository interfaces for simple per-type queries.
Place `@Query` directly on the vertex class with a `name` attribute:
```java
@VertexType("Order")
@Query(name = "openForCustomer",
gremlin = "g.V().has('Customer','id',:custId).out('PLACED').has('status','OPEN')")
public class Order extends ClothoVertex { ... }
```
Invoke via the session:
```java
List<Order> open = session.query(Order.class, "openForCustomer",
Map.of("custId", customerId));
```
**Note on magic strings**: the query name `"openForCustomer"` is a raw string.
Prefer defining it as a constant on the class:
```java
@VertexType("Order")
@Query(name = Order.QUERY_OPEN_FOR_CUSTOMER, ...)
public class Order extends ClothoVertex {
public static final String QUERY_OPEN_FOR_CUSTOMER = "openForCustomer";
}
// Call site:
session.query(Order.class, Order.QUERY_OPEN_FOR_CUSTOMER, params);
```
Multiple `@Query` annotations on a class are allowed (the annotation is `@Repeatable`).
---
## Gremlin Traversal Source
The `GraphTraversalSource` (`g`) is managed by `ClothoSessionFactory`. It is configured
once and shared across sessions. Clotho configures the traversal source to use the remote
ArcadeDB connection.
For advanced cases where a developer needs direct traversal source access:
```java
@Autowired ClothoSessionFactory factory;
GraphTraversalSource g = factory.traversalSource();
// Write raw Gremlin, then map manually:
List<ClothoVertex> results = factory.currentSession()
.mapVertices(ClothoVertex.class, g.V().has("name", "Alice").out("KNOWS"));
```
---
## Mapping Detail: How Clotho Maps a Gremlin Vertex to a Java Object
1. Read the vertex label from the TinkerPop `Vertex` object
2. Look up the label in the `TypeRegistry` → find the most specific registered class
3. Construct an instance of that class (via reflection; Lombok builder support planned)
4. Set the `ARID` from the vertex ID
5. For each `@Property` field on the class: read the property from the vertex, set the field
6. For each `@Include` field: recursively execute the boundary traversal (see `OBJECT_BOUNDARY.md`)
7. Register the instance in the session identity map keyed by ARID
8. Return the assembled instance
If the same ARID is encountered again during step 6, the identity map returns the already-
assembled instance without re-fetching from the DB.
+165
View File
@@ -0,0 +1,165 @@
# Spring Integration
## Overview
The `clotho-spring-boot-starter` module provides:
- Autoconfiguration of `ClothoSessionFactory` as a singleton Spring bean
- Session scoping tied to the Spring `@Transactional` lifecycle
- Classpath scanning for `@ClothoRepository` interfaces and automatic proxy bean registration
- `application.properties` / `application.yml` configuration support
The core `clotho-core` module has zero Spring dependency. Everything Spring-specific lives
in `clotho-spring-boot-starter`.
---
## Adding the Starter
```xml
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-spring-boot-starter</artifactId>
<version>${clotho.version}</version>
</dependency>
```
No additional `@EnableXxx` annotation is required. The autoconfiguration activates
automatically when the starter is on the classpath and `clotho.gremlin.url` is configured.
---
## `application.properties` Reference
| Key | Default | Description |
|---|---|---|
| `clotho.gremlin.url` | (required) | WebSocket URL for ArcadeDB Gremlin endpoint |
| `clotho.gremlin.username` | `""` | ArcadeDB username |
| `clotho.gremlin.password` | `""` | ArcadeDB password |
| `clotho.gremlin.traversal-source` | `g` | Name of the traversal source on the server |
| `clotho.default-direction` | `OUT` | Default edge direction for `@Via` fields |
| `clotho.unknown-type-behavior` | `STRICT` | `STRICT`, `NEAREST_ANCESTOR`, or `GENERIC` |
| `clotho.packages` | (required) | Comma-separated packages to scan for `@VertexType` / `@EdgeType` / `@ClothoRepository` |
**Example:**
```properties
clotho.gremlin.url=ws://localhost:8182/gremlin
clotho.gremlin.username=root
clotho.gremlin.password=playwithdata
clotho.gremlin.traversal-source=g
clotho.default-direction=OUT
clotho.unknown-type-behavior=STRICT
clotho.packages=com.example.myapp.domain,com.example.myapp.repository
```
---
## Beans Provided by Autoconfiguration
| Bean | Type | Description |
|---|---|---|
| `clothoSessionFactory` | `ClothoSessionFactory` | Singleton; holds connection and TypeRegistry |
| `clothoTransactionManager` | `PlatformTransactionManager` | Bridges Spring `@Transactional` to Clotho sessions |
Repository beans (one per `@ClothoRepository` interface found during scan) are also
registered automatically.
---
## Transaction Integration
Clotho integrates with Spring's `@Transactional` annotation via a `PlatformTransactionManager`
implementation. A `ClothoSession` is opened when a transaction begins and closed (or rolled
back) when the transaction ends.
```java
@Service
public class OrderService {
@Autowired ClothoSessionFactory sessionFactory;
@Autowired OrderQueries orderQueries;
@Transactional
public void fulfillOrder(ARID orderId) {
ClothoSession session = sessionFactory.currentSession();
Order order = session.load(Order.class, orderId);
order.setStatus("FULFILLED");
session.save(order);
// session.save() is called; commit happens when @Transactional method returns
}
}
```
### Session Scope
Within a `@Transactional` method, `sessionFactory.currentSession()` always returns the
same `ClothoSession`. The identity map is scoped to this session — the same ARID loaded
twice returns the same Java instance.
Outside a transaction, each `sessionFactory.openSession()` call creates a new session.
The caller is responsible for closing it:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Employee emp = session.load(Employee.class, rid);
// ...
}
```
### Transaction Semantics
**Note**: ArcadeDB's Gremlin Server transaction behavior needs verification. Gremlin
typically treats each request as an auto-committed transaction. For multi-step operations
(e.g., creating a vertex and then an edge), the behavior depends on the server configuration.
This will be refined once verified against the live ArcadeDB instance.
---
## `@ClothoRepository` Injection
```java
@ClothoRepository
public interface EmployeeQueries {
@Query("g.V().hasLabel('Employee').has('dept',:dept)")
List<Employee> findByDepartment(@Param("dept") String dept);
}
```
```java
@Service
public class EmployeeService {
@Autowired EmployeeQueries employeeQueries; // injected by Spring
public List<Employee> getEngineers() {
return employeeQueries.findByDepartment("Engineering");
}
}
```
The proxy generated for `EmployeeQueries` uses the `ClothoSession` from the current
transaction context (or opens a new one for the call duration if no transaction is active).
---
## Manually Constructing `ClothoSessionFactory` (without Spring)
```java
ClothoSessionFactory factory = ClothoSessionFactory.builder()
.url("ws://localhost:8182/gremlin")
.credentials("root", "playwithdata")
.traversalSource("g")
.defaultDirection(Direction.OUT)
.unknownTypeBehavior(UnknownTypeBehavior.STRICT)
.scanPackages("com.example.domain")
.build();
try (ClothoSession session = factory.openSession()) {
Employee emp = session.load(Employee.class, ARID.of("#10:0"));
emp.setName("Updated");
session.save(emp);
}
factory.close();
```
+341
View File
@@ -0,0 +1,341 @@
# Clotho Transactions
Clotho provides two levels of transactional control:
1. **Optimistic locking** via `@Version` — detects concurrent modifications on individual
entities at write time. Does not require a database transaction.
2. **Transactional sessions** — wraps all reads and writes in a single ArcadeDB transaction,
providing atomicity for multi-step operations.
This document covers transactional sessions.
---
## Why transactions?
Without a transaction:
- Each Gremlin traversal is auto-committed by ArcadeDB immediately.
- A multi-step save that fails midway leaves the graph in a partial state.
- Two concurrent sessions can read and overwrite each other's changes without any
isolation guarantee.
With a transactional session, all operations share a single transaction scope. Either
everything commits or nothing does.
---
## Manual transactional sessions
```java
ClothoSession session = sessionFactory.openTransactionalSession();
try {
Company acme = new Company();
acme.setName("Acme Corp");
Person alice = new Person();
alice.setName("Alice");
session.save(alice);
session.save(acme);
session.close(); // auto-save dirty entities + tx.commit()
} catch (RuntimeException e) {
session.rollback(); // tx.rollback(), cache cleared, session unbound
throw e;
}
```
Or use try-with-resources (preferred — `close()` commits on success, rolls back on
exception):
```java
try (ClothoSession session = sessionFactory.openTransactionalSession()) {
session.save(alice);
session.save(acme);
} // ← tx.commit() fires here; RuntimeException triggers tx.rollback()
```
---
## Spring `@Transactional`
When using the Spring Boot starter, `ClothoTransactionManager` is registered automatically
(conditional on no other `PlatformTransactionManager` bean being present). This wires
Clotho into Spring's standard `@Transactional` machinery.
### Obtaining the session inside a transactional method
**Option A — `openSession()` (recommended):** behaves correctly in and out of a transaction.
Inside a `@Transactional` method the active session is borrowed (no new session created);
outside, a new non-transactional session is opened.
```java
@Service
@RequiredArgsConstructor
public class PersonService {
private final ClothoSessionFactory sessionFactory;
private final PersonRepository personRepo;
@Transactional
public void promote(ARID personId) {
try (ClothoSession session = sessionFactory.openSession()) { // borrows tx session
Person p = session.load(Person.class, personId);
p.setRole("SENIOR");
// auto-saved on session close; tx committed by Spring tx manager
}
}
}
```
**Option B — `getCurrentSession()`:** throws `ClothoException` if no session is active.
Use when you explicitly require a session to already be bound (e.g. in a helper that
must only be called from within a `@Transactional` context).
```java
@Transactional
public void doWork() {
ClothoSession session = sessionFactory.getCurrentSession();
// ...
}
```
### Repository queries inside a transaction
`ClothoRepository.execute(traversal)` (no-session overload) uses the factory's base
`GraphTraversalSource` and is **not** part of the transaction. Use the session-aware
overload instead:
```java
@Transactional
public void updateEngineers() {
try (ClothoSession session = sessionFactory.openSession()) {
List<Person> engineers = personRepo.execute(session,
personRepo.allEntities(), t -> t.has("role", "Engineer"));
for (Person p : engineers) {
p.setRole("Senior Engineer");
// dirty tracking fires; auto-saved on session close
}
}
}
```
---
## Nested `@Transactional` methods
Spring's default propagation is `REQUIRED`: an inner `@Transactional` method joins the
outer transaction rather than starting a new one. Clotho honours this via the borrow
counter:
```java
@Transactional // outer — opens a transactional session
public void outer() {
inner(); // inner joins; no new session or commit
// commit happens here when outer returns
}
@Transactional // inner — borrows the outer session
public void inner() {
// ... same transaction
}
```
If you need the inner method to run in its own transaction, use
`@Transactional(propagation = Propagation.REQUIRES_NEW)`. Clotho does not currently
support REQUIRES_NEW natively — the inner `openSession()` will still borrow the outer
session. If true nested transaction isolation is required, manage sessions manually with
separate `openTransactionalSession()` calls.
---
## Apps with another transaction manager (JPA, R2DBC)
`ClothoTransactionManager` registers with `@ConditionalOnMissingBean(PlatformTransactionManager.class)`.
If your application already has a JPA or R2DBC transaction manager, the Clotho bean is
skipped.
To use Clotho transactions alongside another tx manager, declare the bean explicitly
and qualify it:
```java
@Bean
public ClothoTransactionManager clothoTransactionManager(ClothoSessionFactory factory) {
return new ClothoTransactionManager(factory);
}
```
Then annotate service methods:
```java
@Transactional("clothoTransactionManager")
public void myGraphOperation() { ... }
```
Or declare Clotho's manager as `@Primary` if it is the dominant transaction manager
in your application.
---
## Relationship between `@Version` and transactions
`@Version` provides **optimistic** concurrency control — it detects conflicts at write time
by checking the entity's application-managed version counter against what is stored in the
database. It works independently of the transactional session API.
Combining both:
- The batch auto-save at `close()` provides atomic writing of all dirty entities in one
Gremlin request (the only atomicity guarantee available over ArcadeDB's Gremlin
WebSocket).
- `@Version` prevents lost updates when two sessions modify the same entity concurrently,
via a two-step check-then-write that fails the entire batch if any version is stale.
A `@Version` check failure throws `OptimisticLockException` during the pre-flight step.
Inside a transactional session, the exception propagates out of `close()`. Since no
properties were written during the pre-flight, no rollback is necessary (but `close()`
will attempt `g.tx().rollback()` regardless, which is a no-op with ArcadeDB Gremlin).
---
## Session auto-close behaviour in transactions
| Scenario | What happens on `session.close()` |
|---|---|
| Non-transactional | Auto-saves dirty managed entities; clears cache; unbinds |
| Transactional (new) | Auto-saves dirty managed entities; `tx.commit()`; clears cache; unbinds |
| Transactional (borrowed) | Decrements borrow count; no-op until count reaches 0 |
| Exception during auto-save | `tx.rollback()`; clears cache; unbinds; re-throws |
Call `session.rollback()` explicitly to abort the transaction at any point without saving.
`rollback()` always resets the borrow count to 0 and unbinds immediately.
---
## Batch auto-save and the safe session pattern
When `session.close()` triggers auto-save, Clotho collects every dirty MANAGED entity from
the session cache — vertices and edges — and persists them in **a single Gremlin traversal**:
```
inject(0).union(
__.V(id1).property("name", "Alice"), // dirty vertex
__.V(id2).property("dept", "Eng"), // dirty vertex
__.E(eid).property("role", "Senior"), // dirty edge
...
).iterate()
```
This collapses N round-trips into one, making the auto-save as efficient as possible and
treating all updates as a single ArcadeDB request.
### Recommended session pattern
Load everything you intend to modify at the start of the session, make your changes, then
let `close()` flush them together:
```java
try (ClothoSession session = sessionFactory.openSession()) {
Person alice = session.load(Person.class, aliceId); // load upfront
Person bob = session.load(Person.class, bobId);
Company acme = session.load(Company.class, acmeId);
// ... fetch any read-only helper data here too ...
alice.setEmail("alice@new.example.com"); // dirty tracking fires
bob.setRole("Senior Engineer");
acme.setName("Acme Corp International");
}
// ↑ single batch traversal flushes all three changes here
```
The more entities you modify before closing, the more work is consolidated into that one
round-trip.
### Atomicity — what "single request" means here
ArcadeDB auto-commits each incoming Gremlin request as one database operation. Because the
auto-save batch is one request, updates to entities that **pass** their checks are committed
together. Any interruption (network failure, server error) affects the entire request.
However, there are two important caveats:
**Explicit `session.save()` calls mid-session are NOT batched.** Each call to `session.save(entity)`
issues an immediate individual traversal. Only the auto-save triggered by `session.close()`
uses the batch path.
**`@Version` conflicts fail the whole batch.** The batch auto-save runs in two Gremlin
round-trips:
1. **Pre-flight** — one request checks that every `@Version`-guarded entity still has its
expected version in the database. If any version is stale, `OptimisticLockException` is
thrown immediately and no properties are written.
2. **Batch update** — one request writes all dirty properties for all entities, plus the
incremented version for each `@Version` entity.
Concretely: if session has dirty entities A (no `@Version`), B (`@Version`, stale), and C
(`@Version`, current), the outcome is:
- Pre-flight detects B's stale version → `OptimisticLockException` thrown
- Neither A, B, nor C has been written yet
There is a narrow TOCTOU window between the pre-flight and the write (a concurrent session
could change B's version in that gap), but within that window only already-confirmed
entities would be overwritten.
### `@Version` — application-managed OCC
`@Version` does **not** rely on ArcadeDB's internal `@version` property (which is not
accessible via the Gremlin WebSocket interface). Instead, Clotho manages the counter as
a regular graph property:
- **On create**: the version property is initialised to `0` in the graph; the in-memory
field is set to `0`.
- **On load**: the version is read like any other property.
- **On update**: the pre-flight filter is `.has(versionProp, currentVersion)`. If matched,
the new version `currentVersion + 1` is written atomically in the same traversal step.
The in-memory field is updated after a successful write.
The property name defaults to `"_version"` and can be overridden via `@Version("myProp")`.
### ArcadeDB Gremlin transaction limitations
ArcadeDB's Gremlin WebSocket interface returns a transaction-bound `GraphTraversalSource`
from `g.tx().begin()`, but subsequent Gremlin bytecode operations on that source fail at
runtime. `openTransactionalSession()` therefore uses the base traversal source — the same
one used by non-transactional sessions. The practical consequences:
- Each Gremlin request is auto-committed by ArcadeDB immediately.
- `g.tx().commit()` / `g.tx().rollback()` (called by `close()` / `rollback()`) are
effective no-ops in this mode.
- The **batch auto-save** at `close()` is still a single Gremlin request, so it is
atomic at the request level.
- The **borrow counter** and **Spring `@Transactional` bridge** (`ClothoTransactionManager`)
work correctly and provide the expected API surface.
True multi-request atomicity requires ArcadeDB's native Java or HTTP API directly.
### OrientDB Gremlin transaction limitations
OrientDB with `orient-transactional=false` (required so that `addV` returns real record IDs
immediately rather than temporary `#-1:-2` IDs) rejects `g.tx()` calls entirely, throwing
`Graph does not support transactions`.
At startup, `ClothoSessionFactory` probes transaction support by calling `g.tx().rollback()`.
If the graph rejects the call with the "does not support transactions" message, all
`g.tx().commit()` and `g.tx().rollback()` calls are skipped for every session. The
`transactional` flag still drives the batch auto-save path and the borrow/Spring
`@Transactional` semantics — only the explicit `g.tx()` calls are suppressed.
- Each Gremlin request auto-commits individually; the batch auto-save in `close()` provides
request-level atomicity (one request = all dirty entity writes).
- True multi-request transactions require OrientDB's native Java or binary protocol.
---
## Limitations
- `ClothoRepository.execute(traversal)` without a session is NOT part of the current
transaction. Always use `execute(session, traversal)` for transactional repository queries.
- `ClothoSession` is NOT thread-safe. One session per thread / virtual thread.
- ArcadeDB requires the schema (vertex and edge types) to exist before any write.
Clotho does not manage schema creation.
+231
View File
@@ -0,0 +1,231 @@
# Type System
## Base Class Hierarchy
Every type Clotho knows about descends from `ClothoEntity`:
```
ClothoEntity (abstract)
├── ClothoVertex (abstract)
│ └── Employee, Person, Company, ... (developer-defined @VertexType classes)
└── ClothoEdge (abstract)
└── WorksAt, PlacedBy, ... (developer-defined @EdgeType classes)
@SubgraphType classes do NOT extend ClothoEntity — they are plain Java classes
that aggregate ClothoVertex / ClothoEdge instances.
```
### ClothoEntity
Carries the identity and metadata common to all graph elements:
| Member | Purpose |
|---|---|
| `ARID getId()` | ArcadeDB record ID; null for unsaved elements |
| `String getLabel()` | ArcadeDB type name (e.g. `"Employee"`) |
| `Object getProperty(String key)` | Raw property access; bypass typed fields when needed |
| `boolean hasLabel(String label)` | Convenience type check |
### ClothoVertex
Adds vertex-specific behavior. All `@VertexType` classes must extend this.
### ClothoEdge
Adds edge-specific behavior. Carries `outVertexId` and `inVertexId` as `ARID` values.
All `@EdgeType` classes must extend this.
---
## ARID — ArcadeDB Record ID
`ARID` is a typed value object wrapping the ArcadeDB record ID string (e.g. `#10:0`).
It is deliberately opaque to avoid coupling call sites to ArcadeDB's ID format.
```java
ARID id = ARID.of("#10:0");
String raw = id.asString();
```
Using `ARID` rather than `String` everywhere:
- Makes it impossible to accidentally pass an arbitrary string as a record ID
- Allows the internal representation to evolve (e.g., for future DB portability)
- Null `ARID` reliably indicates "not yet persisted"
---
## Vertex Types
```java
@VertexType("Employee")
public class Employee extends ClothoVertex {
@Property("name") String name;
@Property("dept") String department;
}
```
The `@VertexType` label must match the ArcadeDB vertex type name exactly (case-sensitive).
Field names that match the ArcadeDB property name do not need `@Property`; use it when
names differ or for explicit documentation.
---
## Edge Types
```java
@EdgeType("WORKS_AT")
public class WorksAt extends ClothoEdge {
public static final String LABEL = "WORKS_AT"; // avoids magic strings at call sites
@OutVertex Employee employee;
@InVertex Company company;
@Property("startDate") LocalDate startDate;
@Property("role") String role;
}
```
Declaring `@InVertex` is optional. Omitting it means the edge is loaded for its own
properties only — the target vertex is not fetched. See `docs/OBJECT_BOUNDARY.md`.
---
## Subgraph Types
```java
@SubgraphType
public class EmployeeProfile {
Employee employee; // matches Gremlin as("employee")
Manager manager; // matches Gremlin as("manager")
@Alias("dept")
Department department; // @Alias when field name ≠ Gremlin alias
List<WorksAt> workHistory;
}
```
- Has no `ARID`; does not extend `ClothoEntity`
- Assembled by `SubgraphTypeAssembler` from a Gremlin `select()` result
- `session.save(profile)` iterates all `ClothoEntity` fields and saves each;
the session identity map ensures each element is persisted exactly once
- See `docs/QUERY_MODEL.md` for how `@Query` populates subgraph types
---
## Inheritance
### Standard Single-Parent Inheritance
Mirror the ArcadeDB `EXTENDS` hierarchy in Java:
```java
@VertexType("Person")
public abstract class Person extends ClothoVertex {
String name;
}
@VertexType("Employee")
public class Employee extends Person {
String employeeId;
}
@VertexType("HourlyEmployee")
public class HourlyEmployee extends Employee {
BigDecimal hourlyRate;
}
```
Clotho infers: `"HourlyEmployee"` is a subtype of `"Employee"` is a subtype of `"Person"`.
### Diamond Inheritance
ArcadeDB supports multi-parent inheritance. Java does not allow extending multiple classes.
Declare the second (and further) ArcadeDB parents explicitly:
```java
// ArcadeDB schema: ContractEmployee EXTENDS Employee, Contractor
@VertexType(value = "ContractEmployee", additionalParents = {"Contractor"})
public class ContractEmployee extends Employee {
// Java hierarchy: ContractEmployee IS-A Employee
// ArcadeDB hierarchy: ContractEmployee is also subtype of Contractor (via annotation)
}
```
Clotho uses `additionalParents` only for type registry resolution — not for Java polymorphism.
If you need `ContractEmployee` to be usable as a `Contractor` in Java, use an interface:
```java
public interface ContractorType { /* shared interface */ }
@VertexType("Contractor")
public class Contractor extends ClothoVertex implements ContractorType { ... }
@VertexType(value = "ContractEmployee", additionalParents = {"Contractor"})
public class ContractEmployee extends Employee implements ContractorType { ... }
```
### Divergent Hierarchies
When the ArcadeDB hierarchy cannot be represented via Java `extends` at all, declare the
parent explicitly:
```java
@VertexType(value = "ExternalEmployee", parentLabel = "Employee")
public class ExternalEmployee extends ClothoVertex {
// Does not extend Employee in Java, but is a subtype in ArcadeDB
}
```
---
## Result Mapping Rule
**Clotho always instantiates the most specific registered class matching the vertex/edge label.**
The declared return type is an upper bound — the actual runtime instances are the narrowest
match in the TypeRegistry.
```java
// The query may return HourlyEmployee and SalariedEmployee vertices
List<Employee> staff = repo.findAllEmployees();
// → List contains HourlyEmployee and SalariedEmployee instances
// (both assignable to Employee; caller may instanceof-check if needed)
List<ClothoVertex> anything = repo.findMixed();
// → List contains whatever registered types the traversal returned
```
### Unknown Types
When a vertex/edge label has no registered Java class, behavior depends on the configured
`UnknownTypeBehavior`:
| Mode | Behavior |
|---|---|
| `STRICT` (default) | Throw `UnknownTypeException` |
| `NEAREST_ANCESTOR` | Instantiate closest registered ancestor; subtype-specific fields are null |
| `GENERIC` | Wrap in `ClothoVertex`/`ClothoEdge` with raw `getProperty()` access |
Configure globally:
```properties
clotho.unknown-type-behavior=STRICT
```
Or per session factory:
```java
ClothoSessionFactory.builder()
.unknownTypeBehavior(UnknownTypeBehavior.NEAREST_ANCESTOR)
...
```
---
## TypeRegistry
The `TypeRegistry` is built once at `ClothoSessionFactory` creation time.
It scans the declared packages for `@VertexType` and `@EdgeType` classes and builds:
- `label → Class<? extends ClothoEntity>` direct lookup
- Inheritance tree (for `NEAREST_ANCESTOR` resolution and polymorphic query hints)
- Validation: duplicate labels, missing `extends ClothoVertex`/`ClothoEdge`, etc.
Startup failure is preferred over silent misconfiguration at runtime.
+136
View File
@@ -0,0 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-parent</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Clotho Parent</name>
<description>Graph ORM for ArcadeDB via TinkerPop/Gremlin — parent POM</description>
<modules>
<module>clotho-core</module>
<module>clotho-spring-boot-starter</module>
<module>clotho-dev-app</module>
</modules>
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-boot.version>3.3.4</spring-boot.version>
<tinkerpop.version>3.7.2</tinkerpop.version>
<lombok.version>1.18.34</lombok.version>
<jspecify.version>1.0.0</jspecify.version>
<classgraph.version>4.8.174</classgraph.version>
<maven-compiler-plugin.version>3.13.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>3.3.1</maven-surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot BOM — provides managed versions for Spring, JUnit 5, etc. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- TinkerPop -->
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>gremlin-driver</artifactId>
<version>${tinkerpop.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tinkerpop</groupId>
<artifactId>tinkergraph-gremlin</artifactId>
<version>${tinkerpop.version}</version>
</dependency>
<!-- Clotho inter-module -->
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.binarygolem.clotho</groupId>
<artifactId>clotho-spring-boot-starter</artifactId>
<version>${project.version}</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- JSpecify null annotations -->
<dependency>
<groupId>org.jspecify</groupId>
<artifactId>jspecify</artifactId>
<version>${jspecify.version}</version>
</dependency>
<!-- ClassGraph — classpath scanning for TypeRegistry -->
<dependency>
<groupId>io.github.classgraph</groupId>
<artifactId>classgraph</artifactId>
<version>${classgraph.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>