diff --git a/README.md b/README.md index e617a3b6..36cf2de7 100644 --- a/README.md +++ b/README.md @@ -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/) diff --git a/client/dart/lib/src/client.dart b/client/dart/lib/src/client.dart index 7d96a6a0..f037ac73 100644 --- a/client/dart/lib/src/client.dart +++ b/client/dart/lib/src/client.dart @@ -461,11 +461,9 @@ class Client { } else { await fetch('${_authApi}/logout'); } - } catch (err) { - _logger.warning(err); + } finally { + _updateTokens(null); } - - _updateTokens(null); } // Future 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. diff --git a/client/kotlin/.gitattributes b/client/kotlin/.gitattributes new file mode 100644 index 00000000..a87d264c --- /dev/null +++ b/client/kotlin/.gitattributes @@ -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 diff --git a/client/kotlin/.gitignore b/client/kotlin/.gitignore new file mode 100644 index 00000000..2922417c --- /dev/null +++ b/client/kotlin/.gitignore @@ -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 diff --git a/client/kotlin/Makefile b/client/kotlin/Makefile new file mode 100644 index 00000000..9941e58d --- /dev/null +++ b/client/kotlin/Makefile @@ -0,0 +1,7 @@ +test: + gradle test + +format: + gradle spotlessApply + +.PHONY: test format diff --git a/client/kotlin/gradle.properties b/client/kotlin/gradle.properties new file mode 100644 index 00000000..477dcc9d --- /dev/null +++ b/client/kotlin/gradle.properties @@ -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 diff --git a/client/kotlin/gradle/libs.versions.toml b/client/kotlin/gradle/libs.versions.toml new file mode 100644 index 00000000..0cab1a9d --- /dev/null +++ b/client/kotlin/gradle/libs.versions.toml @@ -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" } diff --git a/client/kotlin/gradle/wrapper/gradle-wrapper.jar b/client/kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..1b33c55b Binary files /dev/null and b/client/kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/client/kotlin/gradle/wrapper/gradle-wrapper.properties b/client/kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..ca025c83 --- /dev/null +++ b/client/kotlin/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/client/kotlin/gradlew b/client/kotlin/gradlew new file mode 100755 index 00000000..23d15a93 --- /dev/null +++ b/client/kotlin/gradlew @@ -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" "$@" diff --git a/client/kotlin/gradlew.bat b/client/kotlin/gradlew.bat new file mode 100644 index 00000000..db3a6ac2 --- /dev/null +++ b/client/kotlin/gradlew.bat @@ -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 diff --git a/client/kotlin/lib/build.gradle.kts b/client/kotlin/lib/build.gradle.kts new file mode 100644 index 00000000..22d12a3e --- /dev/null +++ b/client/kotlin/lib/build.gradle.kts @@ -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 { + 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) } } diff --git a/client/kotlin/lib/src/main/kotlin/Library.kt b/client/kotlin/lib/src/main/kotlin/Library.kt new file mode 100644 index 00000000..36f073d3 --- /dev/null +++ b/client/kotlin/lib/src/main/kotlin/Library.kt @@ -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?, val headers: Map>) { + 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) + +@Serializable +data class ListResponse( + val records: List, + 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() {} + +class Or(val filters: List) : FilterBase() {} + +class RecordApi(val name: String, val client: Client) { + suspend inline fun read(id: RecordId, expand: List? = 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 list( + pagination: Pagination? = null, + order: List? = null, + filters: List? = null, + count: Boolean = false, + expand: List? = null, + ): ListResponse { + val params: MutableMap = 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 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 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? = 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> { + val headers: MutableMap> = 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, 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" diff --git a/client/kotlin/lib/src/test/kotlin/LibraryTest.kt b/client/kotlin/lib/src/test/kotlin/LibraryTest.kt new file mode 100644 index 00000000..ee49829a --- /dev/null +++ b/client/kotlin/lib/src/test/kotlin/LibraryTest.kt @@ -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 = 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 = 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 = + api.list( + filters = + listOf(Filter(column = "text_not_null", value = messages[0])) + ) + + assertEquals(messages[0], response.records[0].text_not_null) + } + + if (true) { + val response: ListResponse = + api.list( + order = listOf("+text_not_null"), + filters = + listOf( + Filter(column = "text_not_null", value = "% =?&${now}", CompareOp.like) + ) + ) + assertEquals(messages, response.records.map { it.text_not_null }) + } + + if (true) { + val response: ListResponse = + api.list( + order = listOf("-text_not_null"), + filters = + listOf( + Filter(column = "text_not_null", value = "% =?&${now}", CompareOp.like) + ) + ) + assertEquals(messages.reversed(), response.records.map { it.text_not_null }) + } + + if (true) { + val response: ListResponse = + api.list( + count = true, + pagination = Pagination(limit = 1), + order = listOf("-text_not_null"), + filters = + listOf( + 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({ api.read(ids[0]) }) + } +} diff --git a/client/kotlin/settings.gradle.kts b/client/kotlin/settings.gradle.kts new file mode 100644 index 00000000..433eb248 --- /dev/null +++ b/client/kotlin/settings.gradle.kts @@ -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") diff --git a/docs/src/assets/flutter_logo.svg b/docs/src/assets/flutter_logo.svg index 8f2cf83c..379f43e3 100644 --- a/docs/src/assets/flutter_logo.svg +++ b/docs/src/assets/flutter_logo.svg @@ -1 +1,160 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/src/assets/kotlin_logo.svg b/docs/src/assets/kotlin_logo.svg new file mode 100644 index 00000000..3e66273c --- /dev/null +++ b/docs/src/assets/kotlin_logo.svg @@ -0,0 +1,60 @@ + + + + + + + + + + + diff --git a/docs/src/content/docs/index.mdx b/docs/src/content/docs/index.mdx index 101a2cb8..0c6bf710 100644 --- a/docs/src/content/docs/index.mdx +++ b/docs/src/content/docs/index.mdx @@ -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. -