Ktkit:使用Ktor构建服务器应用程序的Kotlin工具包
Ktkit: A Kotlin toolkit for building server applications with Ktor

原始链接: https://github.com/smyrgeorge/ktkit

## KtKit:用于服务器开发的 Kotlin 多平台工具包 KtKit 是一个不断发展的开源 Kotlin 多平台工具包,旨在加速使用 Ktor 的服务器端应用程序开发。它通过集成多个库到一个连贯的框架中,简化了常见的后端任务。 目前,KtKit 提供依赖注入(Koin)的应用引导、JSON 处理以及自动注册的 REST 端点。它通过追踪、身份验证钩子和符合 RFC 9457 标准的错误处理,以及内置的健康和指标端点来标准化请求处理。配置通过 TOML 进行管理,并支持环境变量。 关键组件包括使用函数式错误处理(使用 Arrow)的 Ktor HTTP 客户端抽象,以及 sqlx4k 集成,用于支持 PostgreSQL、MySQL 和 SQLite 的类型安全数据库访问。还包含一个轻量级的基于 Postgres 的消息队列 (PGMQ)。 KtKit 利用 Arrow 和 Kotlin 上下文参数来实现简洁的错误处理和上下文传播。**重要安全提示:** 它的 X-Real-Name 身份验证依赖于受信任的反向代理来防止头部伪造。 虽然可以用于生产环境,但预计随着项目成熟,API 会发生变化。欢迎贡献和反馈!

黑客新闻 新 | 过去 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 Ktkit: 使用Ktor构建服务器应用程序的Kotlin工具包 (github.com/smyrgeorge) 3点 由 smyrgeorge 1小时前 | 隐藏 | 过去 | 收藏 | 讨论 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请YC | 联系 搜索:
相关文章

原文

Build Maven Central GitHub License GitHub commit activity GitHub issues Kotlin

A comprehensive Kotlin multiplatform toolkit for building server applications with Ktor.

📖 Documentation

🏠 Homepage (under construction)

implementation("io.github.smyrgeorge:ktkit:x.y.z")

KtKit is a Kotlin multiplatform toolkit designed to speed up server-side application development with Ktor. It brings together several libraries into a cohesive set of tools that handle the repetitive aspects of backend development.

Note

Early Stage Project: KtKit is actively evolving. APIs may change between versions as we refine the abstractions based on real-world usage. Production use is possible but expect some breaking changes. Feedback and contributions are highly appreciated!

What it does (today):

  • Provides a small application bootstrap around Ktor with DI, JSON, and auto-registered REST handlers
  • Standardizes request handling with tracing, auth/permissions hooks, and RFC 9457-style API errors
  • Exposes basic health and metrics endpoints for services built on the toolkit
  • Offers TOML configuration loading with environment-variable interpolation and file/resource merging
  • Adds convenience helpers for retries, JSON/TOML utilities, and KMP-friendly file/http/process access
  • Uses Arrow (Raise/Either) and Kotlin context parameters to keep error handling and context passing lightweight

Planned features:

  • Application wrapper for Ktor server startup/shutdown, JSON setup, Koin DI, and routing
  • AbstractRestHandler with typed request helpers, ExecContext propagation, and error mapping
  • Built-in /api/status/health and /api/status/metrics endpoints
  • Error model (ErrorSpec/ApiError) aligned with RFC 9457 conventions
  • Config loader for TOML with environment substitution and layered overrides

Security: X-Real-Name Header Authentication

Warning

The XRealNamePrincipalExtractor and XRealNameRestClient use a base64-encoded JSON header (x-real-name) to identify the authenticated user. This mechanism is not safe to expose directly to the internet.

This pattern assumes a trusted reverse proxy or API gateway sits in front of your application and:

  1. Authenticates the user (e.g., via OAuth, JWT, or session cookies)
  2. Strips any incoming x-real-name header from client requests
  3. Sets the x-real-name header with the authenticated user's information before forwarding

If your application is exposed directly to the internet without such a proxy, any client can forge the header and impersonate any user. Only use this extractor when your application runs behind a trusted infrastructure layer that controls this header.

Ktor HTTP Client (ktkit-ktor-httpclient)

A multiplatform REST client abstraction built on Ktor's HttpClient with functional error handling via Arrow's Raise.

  • HttpClientFactory for creating pre-configured HttpClient instances with timeouts, connection pooling, and JSON setup
  • AbstractRestClient base class with typed HTTP methods (GET, POST, PUT, PATCH, DELETE, etc.)
  • Built-in implementations: BearerRestClient (Bearer token auth) and XRealNameRestClient (X-Real-Name header auth)
  • Error handling via sealed RestClientErrorSpec hierarchy

sqlx4k integration (ktkit-sqlx4k)

A coroutine-first SQL toolkit with compile-time query validations for Kotlin Multiplatform. PostgreSQL, MySQL/MariaDB, and SQLite supported.

  • DatabaseService helpers for error mapping and traced transactions
  • AuditableRepository hooks for createdAt/createdBy/updatedAt/updatedBy
  • AuditableDatabaseService interface for services with auditable entities and a save() extension
  • JsonSupport utility for JSON column serialization with sqlx4k's ValueEncoder system

PGMQ integration (ktkit-sqlx4k-pgmq)

A lightweight message queue. Like AWS SQS and RSMQ but on Postgres.

  • Pgmq wrapper and AbstractPgmqEventHandler with trace/user propagation
  • Consumer lifecycle helpers with retry + shutdown handling

Ergonomics (Arrow + context-parameters)

The example module shows how Arrow's Raise and Kotlin context parameters keep service code compact while preserving explicitness around errors and execution context:

class TestService(
    override val db: Driver,
    override val repo: TestRepository,
) : AuditableDatabaseService<Test> {
    val log = Logger.of(this::class)

    context(_: ExecContext, _: QueryExecutor)
    private suspend fun findAll(): List<Test> = db { repo.findAll() }

    context(_: ExecContext, _: Transaction)
    suspend fun test(): List<Test> {
        log.info { "Fetching all tests" }
        return findAll().also {
            log.info { "Fetched ${it.size} tests" }
        }
    }
}

The execution context is a coroutine context element that also implements Arrow's Raise and log4k's tracing context:

class ExecContext(
    val reqId: String,
    val reqTs: Instant,
    val principal: Principal,
    // Only a part of the context is presented here.
    // Check the documentation for more information.
) : Raise<ErrorSpec>, TracingContext by tracing, CoroutineContext.Element

This lets handlers and services raise domain errors, access tracing, and carry request metadata without threading parameters manually. The context is propagated in two ways at once: via CoroutineContext and via context parameters in function signatures.

Check the example application here.

# Build all modules, for Jvm and your current platform
./gradlew build

# Build all modules for all supported platforms
./gradlew build -Ptargets=all
#

The project includes a docker-compose.yml for PostgreSQL:

This is an open-source project. Contributions are welcome!

Check the repository for license information.

  • log4k – Multiplatform logging with tracing
  • sqlx4k – Multiplatform database access

Yorgos S. (@smyrgeorge)

联系我们 contact @ memedata.com