Add an initial Kotlin client. #146 #144

Missing:
 * No docs examples yet.
 * No realtime subscriptions yet.

I'm not overly familar with Kotlin, so another set of eyes would be appreciated to converge towards a more idiomatic implementation.
This commit is contained in:
Sebastian Jeltsch
2025-09-11 21:51:51 +02:00
parent 972f6a50af
commit be3cd2f6f7
18 changed files with 1274 additions and 12 deletions

View File

@@ -82,6 +82,7 @@ Client packages for various languages are available via:
- [Rust](https://crates.io/crates/trailbase-client)
- [C#/.Net](https://www.nuget.org/packages/TrailBase/)
- [Swift](https://github.com/trailbaseio/trailbase/tree/main/client/swift/trailbase)
- [Kotlin](https://github.com/trailbaseio/trailbase/tree/main/client/kotlin)
- [Go](https://github.com/trailbaseio/trailbase/tree/main/client/go/trailbase)
- [Python](https://pypi.org/project/trailbase/)

View File

@@ -461,11 +461,9 @@ class Client {
} else {
await fetch('${_authApi}/logout');
}
} catch (err) {
_logger.warning(err);
} finally {
_updateTokens(null);
}
_updateTokens(null);
}
// Future<void> deleteUser() async {
@@ -617,10 +615,7 @@ class _TokenState {
User? user() {
final jwt = state?.$2;
if (jwt != null) {
return User(id: jwt.sub, email: jwt.email);
}
return null;
return (jwt != null) ? User(id: jwt.sub, email: jwt.email) : null;
}
/// Returns refresh token if refresh is warranted.

11
client/kotlin/.gitattributes vendored Normal file
View File

@@ -0,0 +1,11 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
# Binary files should be left untouched
*.jar binary

10
client/kotlin/.gitignore vendored Normal file
View File

@@ -0,0 +1,10 @@
# Ignore Gradle/Kotlin project-specific cache directory
.gradle
.kotlin
*.jar
!gradle/wrapper/gradle-wrapper.jar
# Ignore Gradle build output directory
build
*.db

7
client/kotlin/Makefile Normal file
View File

@@ -0,0 +1,7 @@
test:
gradle test
format:
gradle spotlessApply
.PHONY: test format

View File

@@ -0,0 +1,6 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties
org.gradle.configuration-cache=true
org.gradle.parallel=true
org.gradle.caching=true

View File

@@ -0,0 +1,26 @@
# This file was generated by the Gradle 'init' task.
# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format
[versions]
commons-math3 = "3.6.1"
guava = "33.4.5-jre"
kotlin = "2.2.20"
ktor = "3.2.3"
spotless = "6.21.0"
[libraries]
commons-math3 = { module = "org.apache.commons:commons-math3", version.ref = "commons-math3" }
guava = { module = "com.google.guava:guava", version.ref = "guava" }
ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
ktor-client-cio = { group = "io.ktor", name = "ktor-client-cio", version.ref = "ktor" }
ktor-client-negotiation = { group = "io.ktor", name = "ktor-client-content-negotiation", version.ref = "ktor" }
ktor-serialization-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version = "1.9.0" }
kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version = "1.10.2" }
[plugins]
kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" }
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
spotless = { id = "com.diffplug.spotless", version.ref = "spotless" }

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
client/kotlin/gradlew vendored Executable file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
client/kotlin/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,77 @@
import org.gradle.api.tasks.testing.logging.TestExceptionFormat
import org.gradle.api.tasks.testing.logging.TestLogEvent
plugins {
alias(libs.plugins.kotlin.jvm)
alias(libs.plugins.kotlin.serialization)
// Code formatting, linting, ...
alias(libs.plugins.spotless)
// Apply the java-library plugin for API and implementation separation.
`java-library`
}
repositories {
// Use Maven Central for resolving dependencies.
mavenCentral()
}
dependencies {
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.cio)
implementation(libs.ktor.client.negotiation)
implementation(libs.ktor.serialization.json)
implementation(libs.kotlinx.serialization.json)
testImplementation(libs.kotlinx.coroutines.test)
// This dependency is exported to consumers, that is to say found on their compile
// classpath.
api(libs.commons.math3)
// This dependency is used internally, and not exposed to consumers on their own compile
// classpath.
implementation(libs.guava)
}
testing {
suites {
// Configure the built-in test suite
val test by
getting(JvmTestSuite::class) {
// Use Kotlin Test test framework
useKotlinTest("2.1.20")
}
}
}
allprojects {
tasks.withType<Test> {
testLogging {
showStandardStreams = true
showExceptions = true
showCauses = true
events = setOf(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED)
exceptionFormat = TestExceptionFormat.FULL
}
outputs.upToDateWhen { false }
}
}
spotless {
kotlin {
ktfmt().kotlinlangStyle()
// ktlint()
// diktat()
}
kotlinGradle {
target("*.gradle.kts")
ktfmt().kotlinlangStyle()
// ktlint()
}
}
// Apply a specific Java toolchain to ease working on different environments.
java { toolchain { languageVersion = JavaLanguageVersion.of(21) } }

View File

@@ -0,0 +1,399 @@
package io.trailbase.client
import io.ktor.client.*
import io.ktor.client.call.body
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlin.io.encoding.Base64
import kotlin.time.Clock
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.*
@Serializable data class User(val id: String, val email: String)
@Serializable
data class Tokens(val auth_token: String, val refresh_token: String?, val csrf_token: String?)
@Serializable
data class JwtTokenClaims(
val sub: String,
val iat: Long,
val exp: Long,
val email: String,
val csrf_token: String
)
class TokenState(val state: Pair<Tokens, JwtTokenClaims>?, val headers: Map<String, List<String>>) {
companion object {
fun build(tokens: Tokens?): TokenState {
return TokenState(
if (tokens != null) Pair(tokens, decodeJwtTokenClaims(tokens.auth_token)) else null,
buildHeaders(tokens)
)
}
}
fun user(): User? {
val jwt = state?.second
return if (jwt != null) User(jwt.sub, jwt.email) else null
}
@OptIn(kotlin.time.ExperimentalTime::class)
internal fun shouldRefresh(): String? {
if (state != null) {
val now = Clock.System.now().toEpochMilliseconds() / 1000
if (state.second.exp - 60 < now) {
return state.first.refresh_token
}
}
return null
}
}
sealed class RecordId {
abstract fun id(): String
companion object {
fun uuid(id: String): RecordId {
return StringRecordId(id)
}
fun string(id: String): RecordId {
return StringRecordId(id)
}
fun int(id: Int): RecordId {
return IntegerRecordId(id)
}
}
override fun equals(other: Any?): Boolean {
return other is RecordId && id() == other.id()
}
}
class StringRecordId(private val id: String) : RecordId() {
override fun id(): String {
return id
}
}
class IntegerRecordId(private val id: Int) : RecordId() {
override fun id(): String {
return id.toString()
}
}
@Serializable private data class ResponseRecordIds(val ids: List<String>)
@Serializable
data class ListResponse<T>(
val records: List<T>,
val cursor: String? = null,
val total_count: Int? = null
)
class Pagination(val cursor: String? = null, val limit: Int? = null, val offset: Int? = null) {}
enum class CompareOp {
equal,
notEqual,
lessThan,
lessThanEqual,
greaterThan,
greaterThanEqual,
like,
regexp,
}
private fun opToString(op: CompareOp): String {
return when (op) {
CompareOp.equal -> "\$eq"
CompareOp.notEqual -> "\$ne"
CompareOp.lessThan -> "\$lt"
CompareOp.lessThanEqual -> "\$lte"
CompareOp.greaterThan -> "\$gt"
CompareOp.greaterThanEqual -> "\$gte"
CompareOp.like -> "\$like"
CompareOp.regexp -> "\$re"
}
}
sealed class FilterBase {}
class Filter(val column: String, val value: String, val op: CompareOp? = null) : FilterBase() {}
class And(val filters: List<FilterBase>) : FilterBase() {}
class Or(val filters: List<FilterBase>) : FilterBase() {}
class RecordApi(val name: String, val client: Client) {
suspend inline fun <reified T> read(id: RecordId, expand: List<String>? = null): T {
return client
.fetch(
"${RECORD_API}/${name}/${id.id()}",
params =
if (expand != null) mapOf(Pair("expand", expand.joinToString(","))) else null
)
.body()
}
suspend inline fun <reified T> list(
pagination: Pagination? = null,
order: List<String>? = null,
filters: List<FilterBase>? = null,
count: Boolean = false,
expand: List<String>? = null,
): ListResponse<T> {
val params: MutableMap<String, String> = mutableMapOf()
if (pagination != null) {
val cursor = pagination.cursor
if (cursor != null) params["cursor"] = cursor
val limit = pagination.limit
if (limit != null) params["limit"] = limit.toString()
val offset = pagination.offset
if (offset != null) params["offset"] = offset.toString()
}
if (order != null) {
params["order"] = order.joinToString(",")
}
if (count) {
params["count"] = "true"
}
if (expand != null) {
params["expand"] = expand.joinToString(",")
}
filters?.forEach { addFiltersToParams(params, "filter", it) }
return client.fetch("${RECORD_API}/${name}", params = params).body()
}
suspend fun <T> create(record: T): RecordId {
val response = client.fetch("${RECORD_API}/${name}", Method.post, record)
val ids: ResponseRecordIds = response.body()
return StringRecordId(ids.ids[0])
}
suspend fun <T> update(id: RecordId, record: T) {
client.fetch("${RECORD_API}/${name}/${id.id()}", Method.patch, record)
}
suspend fun delete(id: RecordId) {
client.fetch("${RECORD_API}/${name}/${id.id()}", Method.delete)
}
}
enum class Method {
get,
post,
patch,
delete,
}
class HttpException(val status: Int, message: String?) : Throwable(message) {}
class Client(
private val site: Url,
private var tokenState: TokenState,
private val http: HttpClient = initClient()
) {
constructor(
site: String
) : this(
Url(site),
TokenState.build(null),
)
companion object {
suspend fun withTokens(site: String, tokens: Tokens): Client {
val client = Client(site)
client.tokenState = TokenState.build(tokens)
client.refreshAuthToken()
return client
}
}
fun site(): Url {
return this.site
}
fun tokens(): Tokens? {
return tokenState.state?.first
}
fun user(): User? {
return tokenState.user()
}
fun records(name: String): RecordApi {
return RecordApi(name, this)
}
suspend fun login(email: String, password: String): Tokens {
@Serializable data class Credentials(val email: String, val password: String)
val tokens: Tokens =
fetch("${AUTH_API}/login", Method.post, Credentials(email, password)).body()
tokenState = TokenState.build(tokens)
return tokens
}
suspend fun logout() {
try {
val refreshToken = tokenState.state?.first?.refresh_token
if (refreshToken != null) {
@Serializable data class Body(val refresh_token: String)
fetch("${AUTH_API}/logout", Method.post, Body(refreshToken))
} else {
fetch("${AUTH_API}/logout")
}
} finally {
tokenState = TokenState.build(null)
}
}
suspend fun refreshAuthToken() {
val refreshToken = tokenState.shouldRefresh()
if (refreshToken != null) {
tokenState = refreshTokensImpl(refreshToken)
}
}
suspend fun fetch(
path: String,
method: Method = Method.get,
body: Any? = null,
params: Map<String, String>? = null,
): HttpResponse {
val refreshToken = tokenState.shouldRefresh()
if (refreshToken != null) {
tokenState = refreshTokensImpl(refreshToken)
}
val response =
http.request(site) {
this.method =
when (method) {
Method.get -> HttpMethod.Get
Method.post -> HttpMethod.Post
Method.patch -> HttpMethod.Patch
Method.delete -> HttpMethod.Delete
}
url {
path(path)
if (params != null) {
for ((k, v) in params) {
parameters.append(k, v)
}
}
}
headers { tokenState.headers.forEach { appendAll(it.key, it.value) } }
contentType(ContentType.Application.Json)
setBody(body)
}
if (!response.status.isSuccess()) {
throw HttpException(response.status.value, response.body())
}
return response
}
private suspend fun refreshTokensImpl(refreshToken: String): TokenState {
@Serializable data class Body(val refresh_token: String)
val tokens: Tokens =
http
.post(site) {
url { path("${AUTH_API}/refresh") }
contentType(ContentType.Application.Json)
headers { tokenState.headers.forEach { appendAll(it.key, it.value) } }
setBody(Body(refreshToken))
}
.body()
return TokenState.build(tokens)
}
}
private fun initClient(): HttpClient {
return HttpClient(CIO.create()) {
install(ContentNegotiation) {
// Register Kotlinx.serialization converter
json(
Json {
ignoreUnknownKeys = true
isLenient = true
}
)
}
}
}
private fun buildHeaders(tokens: Tokens?): Map<String, List<String>> {
val headers: MutableMap<String, List<String>> = mutableMapOf()
if (tokens != null) {
headers["Authorization"] = listOf("Bearer ${tokens.auth_token}")
val refresh = tokens.refresh_token
if (refresh != null) {
headers["Refresh-Token"] = listOf(refresh)
}
val csrf = tokens.csrf_token
if (csrf != null) {
headers["CSRF-Token"] = listOf(csrf)
}
}
return headers
}
@OptIn(kotlin.io.encoding.ExperimentalEncodingApi::class)
private fun decodeJwtTokenClaims(jwt: String): JwtTokenClaims {
val parts = jwt.split('.')
if (parts.size != 3) {
throw Exception("Invalid JWT format")
}
val decoded =
Base64.UrlSafe.withPadding(Base64.PaddingOption.PRESENT_OPTIONAL)
.decode(parts[1])
.decodeToString()
return Json.decodeFromString(decoded)
}
fun addFiltersToParams(params: MutableMap<String, String>, path: String, filter: FilterBase) {
when (filter) {
is Filter -> {
if (filter.op != null) {
params["${path}[${filter.column}][${opToString(filter.op)}]"] = filter.value
} else {
params["${path}[${filter.column}]"] = filter.value
}
}
is And -> {
for ((i, f) in filter.filters.withIndex()) {
addFiltersToParams(params, "${path}[\$and][${i}]", f)
}
}
is Or -> {
for ((i, f) in filter.filters.withIndex()) {
addFiltersToParams(params, "${path}[\$or][${i}]", f)
}
}
}
}
private const val AUTH_API: String = "api/auth/v1"
const val RECORD_API: String = "api/records/v1"

View File

@@ -0,0 +1,139 @@
package io.trailbase.client
import io.ktor.client.*
import io.ktor.client.engine.cio.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlin.test.*
import kotlin.test.Test
import kotlin.time.Clock
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlinx.serialization.Serializable
import org.junit.jupiter.api.assertThrows
@Serializable data class SimpleStrict(val id: String, val text_not_null: String)
@Serializable data class SimpleStrictInsert(val text_not_null: String)
@Serializable data class SimpleStrictUpdate(val text_not_null: String?)
class ClientTest {
@Test
fun `filter params`() {
val params: MutableMap<String, String> = mutableMapOf()
val filters =
listOf(
Filter("col0", "0", CompareOp.greaterThan),
Filter("col0", "5", CompareOp.lessThan)
)
for (filter in filters) {
addFiltersToParams(params, "filter", filter)
}
assertEquals(2, params.size)
}
// WARN: TrailBase binding to localhost:4000 doesn't work. ktor only finds it when bound to
// 127.0.0.1 or 0.0.0.0, no IPv6?.
@Test
fun `client authentication`() = runTest {
val client = Client("http://localhost:4000")
assertNull(client.user())
assertNull(client.tokens())
val tokens = client.login("admin@localhost", "secret")
assertNotNull(tokens)
assertEquals("admin@localhost", client.user()?.email)
client.logout()
assertNull(client.tokens())
}
suspend fun connect(): Client {
val client = Client("http://localhost:4000")
client.login("admin@localhost", "secret")
return client
}
@OptIn(kotlin.time.ExperimentalTime::class)
@Test
fun `client records`() = runTest {
val client = connect()
val api = client.records("simple_strict_table")
val now = Clock.System.now().toEpochMilliseconds() / 1000
val messages = listOf("kotlin client test 0: =?&${now}", "kotlin client test 1: =?&${now}")
val ids: MutableList<RecordId> = mutableListOf()
for (msg in messages) {
ids.add(api.create(SimpleStrictInsert(msg)))
}
val record0: SimpleStrict = api.read(ids[0])
assertEquals(RecordId.string(record0.id), ids[0])
if (true) {
val response: ListResponse<SimpleStrict> =
api.list(
filters =
listOf<FilterBase>(Filter(column = "text_not_null", value = messages[0]))
)
assertEquals(messages[0], response.records[0].text_not_null)
}
if (true) {
val response: ListResponse<SimpleStrict> =
api.list(
order = listOf("+text_not_null"),
filters =
listOf<FilterBase>(
Filter(column = "text_not_null", value = "% =?&${now}", CompareOp.like)
)
)
assertEquals(messages, response.records.map { it.text_not_null })
}
if (true) {
val response: ListResponse<SimpleStrict> =
api.list(
order = listOf("-text_not_null"),
filters =
listOf<FilterBase>(
Filter(column = "text_not_null", value = "% =?&${now}", CompareOp.like)
)
)
assertEquals(messages.reversed(), response.records.map { it.text_not_null })
}
if (true) {
val response: ListResponse<SimpleStrict> =
api.list(
count = true,
pagination = Pagination(limit = 1),
order = listOf("-text_not_null"),
filters =
listOf<FilterBase>(
Filter(column = "text_not_null", value = "% =?&${now}", CompareOp.like)
)
)
assertEquals(response.total_count, 2)
assertEquals(
messages.reversed().subList(0, 1),
response.records.map { it.text_not_null }
)
}
val updateMessage = "kotlin client update test 0: =?&${now}"
api.update(ids[0], SimpleStrictUpdate(text_not_null = updateMessage))
val updatedRecord: SimpleStrict = api.read(ids[0])
assertEquals(updateMessage, updatedRecord.text_not_null)
api.delete(ids[0])
assertThrows<HttpException>({ api.read<SimpleStrict>(ids[0]) })
}
}

View File

@@ -0,0 +1,15 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
* For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.14/userguide/multi_project_builds.html in the Gradle documentation.
* This project uses @Incubating APIs which are subject to change.
*/
plugins {
// Apply the foojay-resolver plugin to allow automatic download of JDKs
id("org.gradle.toolchains.foojay-resolver-convention") version "0.10.0"
}
rootProject.name = "trailbase"
include("lib")

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 12 KiB

View File

@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
viewBox="0 0 64 63.999999"
version="1.1"
id="svg9"
sodipodi:docname="Kotlin_logo_(2021-present).svg"
width="64"
height="64"
inkscape:version="1.4 (e7c3feb100, 2024-10-09)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs9" />
<sodipodi:namedview
id="namedview9"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="true"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="5.7443475"
inkscape:cx="21.151227"
inkscape:cy="23.153195"
inkscape:window-width="1920"
inkscape:window-height="1131"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg9" />
<radialGradient
id="a"
cx="22.431999"
cy="3.493"
r="21.679001"
gradientTransform="matrix(3.380286,0,0,3.3820961,-13.962674,-9.1932836)"
gradientUnits="userSpaceOnUse">
<stop
stop-color="#e44857"
offset=".003"
id="stop1" />
<stop
stop-color="#c711e1"
offset=".469"
id="stop2" />
<stop
stop-color="#7f52ff"
offset="1"
id="stop3" />
</radialGradient>
<path
d="M 64,64.000001 H 2.5e-7 V -1e-6 H 64 l -32.660115,31.5249 z"
fill="url(#a)"
stroke-width="1.0858"
id="path9"
style="fill:url(#a)" />
</svg>

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

@@ -39,6 +39,7 @@ import rustLogo from "@/assets/rust_unofficial_logo.svg";
import goLogo from "@/assets/go_logo.svg";
import swiftLogo from "@/assets/swift_logo.svg";
import tsLogo from "@/assets/ts_logo.svg";
import kotlinLogo from "@/assets/kotlin_logo.svg";
import tanstackLogo from "@/assets/tanstack_logo.svg";
import { Duration100kInsertsChart } from "./reference/_benchmarks/benchmarks.tsx";
@@ -108,19 +109,23 @@ export const demoLink = "https://demo.trailbase.io";
Clients as well as code-generation examples for TypeScript,
Dart/Flutter, Python, C#/.NET and Rust are provided out of the box.
<div class="pt-4 m-0 gap-4 grid grid-cols-7 justify-center items-start">
<div class="pt-4 m-0 gap-4 grid grid-cols-8 justify-center items-start">
<a href="https://www.npmjs.com/package/trailbase">
<Image class="p-0 m-0" height={52} src={tsLogo} alt="TypeScript" />
<Image class="p-0 m-0" width={52} height={52} src={tsLogo} alt="TypeScript" />
</a>
<a href="https://pub.dev/packages/trailbase">
<Image margin={0} class="p-0 m-0" width={42} height={52} src={flutterLogo} alt="Flutter" />
<Image margin={0} class="p-0 m-0" width={52} height={52} src={flutterLogo} alt="Flutter" />
</a>
<a href={githubPath("client/swift/trailbase")}>
<Image margin={0} class="p-0 m-0" width={52} height={52} src={swiftLogo} alt="Swift" />
</a>
<a href={githubPath("client/kotlin")}>
<Image margin={0} class="p-0 m-0" width={52} height={52} src={kotlinLogo} alt="Kotlin" />
</a>
<a href="https://pypi.org/project/trailbase/">
<Image margin={0} class="p-0 m-0" width={52} height={52} src={pythonLogo} alt="Python" />
</a>