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
+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.