Skip to content
bbasinskPublic

About

Accelerating development with powerful Kotlin libraries

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

339 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Katalyst

Katalyst is a collection of powerful Kotlin libraries designed to accelerate development with type-safe, declarative APIs. Built for Kotlin Multiplatform, these libraries provide a unified approach to schema definitions, validation, HTTP service creation, and serialization across multiple formats.

Core Philosophy

Katalyst focuses on:

  • Type safety: Leverage Kotlin's type system for compile-time guarantees
  • Schema-first design: Define your data structures once, use them everywhere
  • Multiplatform support: Build for JVM, Native, and more
  • Declarative APIs: Write expressive, concise code

Modules

Core Modules

  • schema: Define data structures as values, enabling code generation, validation, and serialization
  • validation: Functional data validation with error accumulation
  • tuple: Utilities for working with tuple-like structures

Schema Format Modules

  • schema-json: JSON serialization/deserialization
  • schema-json-kotlinx: Integration with kotlinx.serialization for JSON
  • schema-avro: Apache Avro binary format support
  • schema-hocon: HOCON configuration format support
  • schema-kotlinx-datetime: Date/time type support for kotlinx.datetime
  • schema-json-schema: JSONSchema generation from schemas

HTTP Modules

  • http: Core HTTP abstractions
  • http-server-ktor-2: Ktor 2.x server integration
  • http-server-ktor-3: Ktor 3.x server integration
  • http-client-ktor-3: Type-safe HTTP client for Ktor 3.x
  • http-openapi: OpenAPI specification generation

Getting Started

Installation

Add the required dependencies to your build.gradle.kts:

// For schema definitions
implementation("io.github.bbasinsk:schema:{{version}}")

// For validation
implementation("io.github.bbasinsk:validation:{{version}}")

// For HTTP services with Ktor 3
implementation("io.github.bbasinsk:http:{{version}}")
implementation("io.github.bbasinsk:http-server-ktor-3:{{version}}")

Build Requirements

  • JDK 21 runs Gradle (pinned in gradle/gradle-daemon-jvm.properties, as in CI) and compiles. Published JVM bytecode targets Java 17 (jvmTarget and -Xjdk-release=17 in the convention plugins), so consumers on Java 17 keep working.
  • Run ./gradlew build before pushing: it is what CI runs, and it compiles native test sources that jvmTest and jsNodeTest skip.

Basic Schema Definition

// Define a simple data class
data class Person(val name: String, val age: Int)

// Define a schema for the Person class
val personSchema = with(Schema) {
    record(
        field(string(), "name") { name },
        field(int(), "age") { age },
        ::Person
    )
}

Creating an HTTP Endpoint

// Define an API endpoint
val getPerson = Http.get { Root / "person" / param("id") { int() } }
    .output { status(Ok) { json { personSchema } } }
    .error { status(NotFound) { json { string() } } }

fun main() {
    embeddedServer(CIO, port = 8080) {
        endpoints {
            handle(getPerson) { req ->
                val (id) = tupleValues(req.params)
                if (id > 0) {
                    success(Person("John Doe", 42))
                } else {
                    error("Person not found")
                }
            }
        }
    }.start(wait = true)
}

Using the HTTP Client

The same endpoint definition works on the client side — no duplicate types or manual URL construction:

val client = KatalystClient(HttpClient(CIO))

val result = client.call(getPerson, 42)
when (result) {
    is HttpResult.Success -> println("Got: ${result.value}")
    is HttpResult.Failure -> println("Error ${result.status}: ${result.error}")
    is HttpResult.NetworkError -> println("Network error: ${result.cause.message}")
}

See http-client-ktor-3/readme.md for SSE streaming, authentication, and more.

Streaming with Server-Sent Events (SSE)

Katalyst supports real-time streaming via SSE:

val streamApi = Http.get { Root / "events" }
    .output { sse(Ok) { json { messageSchema } } }

// In your server setup:
handle(streamApi) {
    streamingSuccessData(flow {
        repeat(10) { i ->
            emit(Message("Event $i", System.currentTimeMillis()))
            delay(1000)
        }
    })
}

See http/readme.md for detailed SSE documentation including keepalive, error handling, and best practices.

Validation

fun Validation.Companion.validatePerson(name: String, age: Int): Validation<String, Person> =
    build(
        nonEmpty(name) { "Name must not be empty" },
        nonNegative(age) { "Age must be non-negative" },
        ::Person
    )

// Helper validators
fun <E> Validation.Companion.nonEmpty(value: String, error: () -> E): Validation<E, String> =
    if (value.isNotBlank()) Validation.valid(value) else Validation.invalid(error())

fun <E> Validation.Companion.nonNegative(value: Int, error: () -> E): Validation<E, Int> =
    if (value >= 0) Validation.valid(value) else Validation.invalid(error())

Features

Schema Definitions

Katalyst's schema system enables:

  • Defining data structures as values
  • Generating serializers/deserializers
  • Creating OpenAPI documentation
  • Validating inputs/outputs
  • Deriving patches: schema.patchSchema() describes partial edits of a value (keep, set, or edit per field), applyPatch applies one with typed failures, and diff computes one

Supported types include:

  • Primitives: String, Int, Long, Float, Double, Boolean, ByteArray
  • Collections: List, Map, and keyed lists (Schema.keyedList(item) { it.id }), which patches upsert and remove by key
  • Records (objects with fields)
  • Unions (oneOf)
  • Optional values
  • Default values
  • Custom types via transformations

HTTP APIs

The HTTP modules provide:

  • Type-safe endpoint definitions
  • Automatic request/response parsing
  • OpenAPI documentation generation
  • Built-in validation
  • Framework integration (Ktor 2.x and 3.x)

Serialization Formats

Katalyst supports multiple serialization formats:

  • JSON (with kotlinx.serialization)
  • Avro binary format
  • HOCON configuration
  • JSONSchema

AI Generation

Katalyst can also generate response schemas for AI models such as OpenAI, Claude, Gemini, etc.

Gemini Example:

@Serializable
data class GeminiGenerationConfig(
    val temperature: Double? = null,
    val responseMimeType: String? = null,
    val responseSchema: JsonElement? = null,
    // other fields...
)

// See above for the personSchema definition
val personResponseSchema = OpenApiJson.encodeToJsonElement(
    personSchema.toSchemaObject(OutputOptions.gemini)
)

val generationConfig = GeminiGenerationConfig(
    responseMimeType = "application/json",
    responseSchema = personResponseSchema
)

Examples

Check out the full examples in the codebase:

TODO

High Priority

  • JSON settings
  • More documentation
  • Get gradle api dependencies work with published packages

Lower Priority

  • Kafka Serde
  • CSV Reader/Writer
  • Kotest integration
  • Better Hocon parsing errors

License

Katalyst is released under the Apache License 2.0.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Accelerating development with powerful Kotlin libraries

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages