Skip to content

v0.1.0

Latest

Choose a tag to compare

@MelSardes MelSardes released this 24 Nov 01:09
· 11 commits to main since this release

🎉 Structus v0.1.0 - Initial Release

Structus - Kotlin Architecture Toolkit is a pure Kotlin JVM library providing foundational building blocks for implementing Explicit Architecture—a synthesis of Domain-Driven Design (DDD), Command/Query Separation (CQS), and Event-Driven Architecture (EDA).

This initial release establishes a production-ready foundation for building large-scale, maintainable applications using clean architecture principles while remaining completely framework-agnostic.


🎯 What is Structus?

Structus serves as a shared kernel for enterprise applications, defining interfaces and base classes for core business concepts and architectural patterns. It eliminates boilerplate code and enforces best practices without coupling your application to any specific framework.

Key Highlights

  • Pure Kotlin - No framework dependencies (Spring, Ktor, Micronaut, etc.)
  • Coroutine-Ready - All I/O operations use suspend functions
  • Minimal Dependencies - Only Kotlin stdlib + kotlinx-coroutines-core (1.9.0)
  • 100% Documented - Comprehensive KDoc on all public APIs
  • Framework-Agnostic - Works with any framework or pure Kotlin
  • AI-Agent Friendly - Includes .ai/ directory with templates and prompts
  • Production-Ready - Explicit API mode, code coverage, quality checks

📦 Installation

Gradle (Kotlin DSL)

dependencies {
    implementation("com.melsardes.libraries:structus-kotlin:0.1.0")
}

Gradle (Groovy)

dependencies {
    implementation 'com.melsardes.libraries:structus-kotlin:0.1.0'
}

Maven

<dependency>
    <groupId>com.melsardes.libraries</groupId>
    <artifactId>structus-kotlin</artifactId>
    <version>0.1.0</version>
</dependency>

🏗️ Architecture Components

Domain Layer (com.melsardes.libraries.structus.domain)

Core Building Blocks

Entity

Abstract base class for identity-based domain objects with proper equality semantics based on ID rather than attributes.

Features:

  • Generic ID type support
  • Proper equals/hashCode implementation based on identity
  • Comprehensive documentation on identity vs attribute equality
  • Thread-safe design
ValueObject

Marker interface for immutable, attribute-based objects designed to work seamlessly with Kotlin data classes.

Features:

  • Immutability guidelines
  • Validation pattern recommendations
  • Attribute-based equality semantics
  • Integration with Kotlin data classes
AggregateRoot

Extends Entity with sophisticated event management capabilities. Serves as the consistency boundary and transactional entry point for aggregates.

Features:

  • Event Management:

    • recordEvent(event: DomainEvent) - Protected method for internal event recording
    • domainEvents: List<DomainEvent> - Public read-only property for event retrieval
    • clearEvents() - Post-publish cleanup method
    • eventCount(), hasEvents() - Helper methods for event inspection
  • Lifecycle Management:

    • markAsCreated(by: String, at: Instant) - Track entity creation
    • markAsUpdated(by: String, at: Instant) - Track modifications
    • softDelete(by: String, at: Instant) - Soft delete support
    • restore(by: String, at: Instant) - Restore deleted entities
    • isDeleted(), isActive() - Status checks
    • incrementVersion() - Optimistic locking support
  • Best Practices:

    • Thread-safety documentation
    • Transaction boundary guidelines
    • Event sourcing compatibility
    • Comprehensive usage examples
Repository

Marker interface establishing the contract for all repository interfaces.

Features:

  • Clear separation between interface (domain) and implementation (infrastructure)
  • Guidelines for suspend functions
  • Collection-like API design patterns
  • Query method naming conventions

Event Infrastructure

DomainEvent

Base interface for all domain events with required metadata.

Properties:

  • eventId: String - Unique event identifier
  • occurredAt: Instant - Timestamp using Kotlin multiplatform time API
  • aggregateId: String - Source aggregate identifier
  • eventType: String - Event type discriminator

Features:

  • Past-tense naming conventions
  • Event sourcing compatibility
  • Serialization guidelines
  • Immutability requirements
BaseDomainEvent

Abstract base implementation providing default event metadata generation with automatic UUID generation and timestamp capture.

MessageOutboxRepository

Complete implementation of the Transactional Outbox Pattern to solve the dual-write problem in distributed systems.

Methods:

  • save(message: OutboxMessage) - Save event to outbox table
  • findUnpublished(limit: Int) - Find unpublished messages with pagination
  • markAsPublished(messageId: String) - Mark message as successfully published
  • incrementRetryCount(messageId: String) - Track retry attempts
  • deleteOldPublishedMessages(olderThan: Instant) - Cleanup old messages
  • findFailedMessages(maxRetries: Int) - Detect failed events

Includes:

  • OutboxMessage data class with factory methods
  • Database schema examples for PostgreSQL, MySQL, SQL Server
  • Retry strategy documentation
  • Idempotency guidelines
Result

Explicit error handling type replacing exception-based flows with type-safe success/failure semantics.

Features:

  • Result.Success<T> - Successful operation with value
  • Result.Failure - Failed operation with error message and optional exception
  • Type-safe error handling
  • Railway-oriented programming support
  • Extension functions for mapping and chaining

Application Layer (com.melsardes.libraries.structus.application)

Commands (application.commands)

Command

Marker interface for write operations representing intent to change state.

Features:

  • Imperative naming conventions (CreateOrder, UpdateCustomer)
  • Validation strategy documentation
  • Immutability requirements
  • Data class compatibility
CommandHandler<C, R>

Interface for executing business logic with operator invoke support.

Signature:

suspend operator fun invoke(command: C): R

Features:

  • Orchestration pattern documentation
  • Transaction boundary guidelines
  • Error handling strategies (exceptions vs Result types)
  • Comprehensive implementation examples
  • One-to-one command-to-handler mapping
  • Suspend function support for async operations
CommandBus

Central command dispatcher providing type-safe routing.

Methods:

  • register(handler: CommandHandler<C, R>) - Register command handlers
  • dispatch(command: C): R - Execute commands through registered handlers

Features:

  • Middleware/interceptor pattern support
  • Implementation examples: simple, logging, transactional, validating
  • Type-safe command routing
  • Error propagation strategies

Queries (application.queries)

Query

Marker interface for read operations with question-based naming conventions.

Features:

  • Question-based naming (GetOrderById, FindCustomersByName)
  • CQRS pattern documentation
  • Optimization strategies (projections, caching, denormalization)
  • Read-only guarantee enforcement
QueryHandler<Q, R>

Interface for data retrieval operations.

Signature:

suspend operator fun invoke(query: Q): R

Features:

  • Read-only guarantee enforcement
  • Pagination support examples
  • Projection patterns for optimized data transfer
  • No transaction required documentation
  • Caching strategy recommendations

Events (application.events)

DomainEventPublisher

Interface for publishing events to external systems.

Methods:

  • publish(event: DomainEvent) - Single event publishing
  • publishBatch(events: List<DomainEvent>) - Batch event publishing

Features:

  • Transactional Outbox Pattern integration
  • Implementation examples for Kafka, RabbitMQ, in-memory
  • Event routing strategies
  • Serialization guidelines
  • Error handling and retry logic
  • Idempotency recommendations
DomainEventHandler

Interface for handling domain events asynchronously with support for event-driven workflows.


🛠️ Build Configuration

Gradle Setup

  • Gradle: 9.1.0 with Kotlin DSL
  • Kotlin: 2.2.0 with explicit API mode enabled
  • Java Toolchain: 21
  • JaCoCo: Code coverage with 50% minimum threshold
  • Maven Publishing: GitHub Packages support
  • Artifacts: Main JAR, Sources JAR, Javadoc JAR

Dependencies

// Only external dependency
api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")

// Test dependencies
testImplementation("org.jetbrains.kotlin:kotlin-test")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
testImplementation("io.mockk:mockk:1.13.12")

Zero framework dependencies - No Spring, Ktor, Micronaut, R2DBC, JDBC, Hibernate, or any framework-specific libraries.

Quality Enforcement

  • ✅ Explicit API mode for main sources (strict documentation requirements)
  • ✅ Disabled for test sources to reduce boilerplate
  • ✅ JUnit 5 test framework
  • ✅ Comprehensive compiler options
  • ✅ 100% public API documentation coverage

📚 Documentation

Comprehensive Documentation Suite

README.md

Complete library overview with:

  • Installation instructions
  • Quick start guide
  • Architecture component descriptions
  • Advanced patterns (Transactional Outbox, CQRS)
  • Integration examples for Spring Boot and Ktor

QUICK_REFERENCE.md

  • Package structure overview
  • Core concepts comparison tables
  • Common patterns with code examples
  • Feature implementation checklist
  • Common mistakes to avoid
  • Naming conventions
  • Testing patterns

AI Agent Support (.ai/ directory)

Makes the library AI-agent-friendly for GitHub Copilot, Cursor, Claude, ChatGPT:

  • library-overview.md - Core concepts and architecture for AI coding assistants
  • usage-patterns.md - Correct patterns and anti-patterns
  • code-templates.md - Ready-to-use code templates
  • prompts/ - Pre-written prompts for common tasks

KDoc Coverage

  • ✅ 100% documentation coverage on all public APIs
  • ✅ Extensive inline comments explaining rationale
  • ✅ Usage examples in every component
  • ✅ Pattern explanations and best practices
  • ✅ Thread-safety and concurrency documentation

🏛️ Architecture Principles

Dependency Rule Enforcement

Presentation Layer (not in library)
        ↓
Application Layer (commands, queries, events)
        ↓
Domain Layer (entities, aggregates, repositories, events)
  • Domain layer has zero dependencies (pure business logic)
  • Application layer depends only on domain
  • Infrastructure layer (not in library) depends on domain + application
  • Presentation layer (not in library) depends on application

Framework Independence

  • ✅ Works with Spring Boot, Ktor, Micronaut, Quarkus, or pure Kotlin
  • ✅ No magic or hidden behavior
  • ✅ Clear contracts through interfaces
  • ✅ Explicit error handling
  • ✅ No reflection or runtime code generation

Design Patterns Implemented

  • Aggregate Pattern - One aggregate = one transaction boundary
  • CQRS - Separate read and write operations
  • Event Sourcing - Compatible with event sourcing systems
  • Transactional Outbox Pattern - Reliable event delivery
  • Repository Pattern - Clear interface/implementation separation
  • Command/Query Handler Pattern - Operator invoke support

Kotlin Best Practices

  • ✅ Immutability encouraged throughout
  • ✅ Null safety leveraged
  • ✅ Coroutines integration for async operations
  • ✅ Data classes for Value Objects
  • ✅ Sealed classes for type-safe hierarchies
  • ✅ Explicit API mode for documentation enforcement
  • ✅ Extension functions for enhanced usability

🧪 Testing Infrastructure

  • Framework: Kotlin Test with JUnit 5
  • Mocking: MockK for Kotlin-friendly mocking
  • Async Testing: kotlinx-coroutines-test for suspend function testing
  • Coverage: JaCoCo with 50% minimum threshold
  • Test Suite: Properly configured JVM test suite

📊 Quality Metrics

Metric Status
Explicit API Mode ✅ Enabled (100% public API documentation)
Compiler Warnings ✅ 0
Build Errors ✅ 0
Documentation Coverage ✅ 100%
Layer Separation ✅ Strict (domain → application)
Framework Coupling ✅ None (pure Kotlin)
Testability ✅ High (all interfaces mockable)
Code Coverage ✅ >50%

🚀 Use Cases

Perfect For:

  • ✅ Microservices architectures
  • ✅ Domain-driven design implementations
  • ✅ Event-driven systems
  • ✅ CQRS applications
  • ✅ Clean architecture projects
  • ✅ Framework-agnostic libraries
  • ✅ Large-scale enterprise applications
  • ✅ Multi-module projects with shared kernel

Works With:

  • Spring Boot (with or without Spring Data)
  • Ktor
  • Micronaut
  • Quarkus
  • Pure Kotlin applications
  • Any JVM framework

🔄 Semantic Versioning

This project follows Semantic Versioning:

  • MAJOR version for incompatible API changes
  • MINOR version for new functionality in a backward-compatible manner
  • PATCH version for backward-compatible bug fixes

v0.1.0 is the initial release establishing the core API surface.


📝 License

This project is licensed under the MIT License - see the LICENSE file for details.


🤝 Contributing

Contributions are welcome! This is an open-source project aimed at providing a solid foundation for Kotlin applications using clean architecture principles.


🙏 Acknowledgments

This library synthesizes best practices from:

  • Domain-Driven Design (Eric Evans, Vaughn Vernon)
  • Clean Architecture (Robert C. Martin)
  • Event-Driven Architecture patterns
  • CQRS pattern (Greg Young)
  • Transactional Outbox Pattern (Chris Richardson)

📖 Further Reading


🎯 What's Next?

Future releases will focus on:

  • Additional event handling patterns
  • More comprehensive examples
  • Integration guides for popular frameworks
  • Performance optimizations
  • Extended documentation

Thank you for using Structus! 🚀

For questions, issues, or contributions, please visit the GitHub repository.