Reorganize top level directory

This commit is contained in:
2021-01-03 14:43:49 -06:00
parent 9fd36d8d53
commit bebb356425
841 changed files with 0 additions and 0 deletions

7
uhabits-server/.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
/.gradle
/.idea
/out
/build
*.iml
*.ipr
*.iws

11
uhabits-server/Dockerfile Normal file
View File

@@ -0,0 +1,11 @@
FROM openjdk:8-jre-alpine
RUN mkdir /app
COPY uhabits-server.jar /app/uhabits-server.jar
ENV LOOP_REPO_PATH /data/
WORKDIR /app
CMD ["java", \
"-server", \
"-XX:MaxGCPauseMillis=100", \
"-XX:+UseStringDeduplication", \
"-jar", \
"uhabits-server.jar"]

View File

@@ -0,0 +1,88 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.github.jengelman.gradle.plugins:shadow:5.2.0"
classpath "com.palantir.gradle.docker:gradle-docker:0.25.0"
}
}
apply plugin: 'kotlin'
apply plugin: "com.github.johnrengelman.shadow"
apply plugin: 'application'
apply plugin: "com.palantir.docker"
apply plugin: "com.palantir.docker-run"
group 'org.isoron.uhabits'
version '0.0.1'
mainClassName = "io.ktor.server.netty.EngineMain"
sourceSets {
main.kotlin.srcDirs = main.java.srcDirs = ['src']
test.kotlin.srcDirs = test.java.srcDirs = ['test']
main.resources.srcDirs = ['resources']
test.resources.srcDirs = ['testresources']
}
repositories {
mavenLocal()
jcenter()
maven { url 'https://kotlin.bintray.com/ktor' }
maven { url 'https://kotlin.bintray.com/kotlin-js-wrappers' }
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation "io.ktor:ktor-server-netty:$ktor_version"
implementation "ch.qos.logback:logback-classic:$logback_version"
implementation "io.ktor:ktor-server-core:$ktor_version"
implementation "io.ktor:ktor-html-builder:$ktor_version"
implementation "io.ktor:ktor-jackson:$ktor_version"
implementation "org.jetbrains:kotlin-css-jvm:1.0.0-pre.31-kotlin-1.2.41"
implementation "io.prometheus:simpleclient:0.9.0"
implementation "io.prometheus:simpleclient_httpserver:0.9.0"
implementation "io.prometheus:simpleclient_hotspot:0.9.0"
testImplementation "io.ktor:ktor-server-tests:$ktor_version"
testImplementation "org.mockito:mockito-core:2.+"
}
shadowJar {
baseName = 'uhabits-server'
classifier = null
version = null
}
docker {
name = "docker.axavier.org/uhabits-server:$version"
files "build/libs/uhabits-server.jar"
}
dockerRun {
name = 'uhabits-server'
image "uhabits-server:$version"
ports '8080:8080'
daemonize false
clean true
}

View File

@@ -0,0 +1,23 @@
#
# Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
#
# This file is part of Loop Habit Tracker.
#
# Loop Habit Tracker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Loop Habit Tracker is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
ktor_version=1.4.1
kotlin.code.style=official
kotlin_version=1.4.10
logback_version=1.2.1

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

191
uhabits-server/gradlew vendored Executable file
View File

@@ -0,0 +1,191 @@
#!/usr/bin/env sh
#
# Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
#
# This file is part of Loop Habit Tracker.
#
# Loop Habit Tracker is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Loop Habit Tracker is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
# more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# 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"
which java >/dev/null 2>&1 || 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
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
uhabits-server/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@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=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@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=
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,9 @@
ktor {
deployment {
port = 8080
port = ${?PORT}
}
application {
modules = [ org.isoron.uhabits.sync.app.SyncApplicationKt.main ]
}
}

View File

@@ -0,0 +1,31 @@
<!--
~ Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
~
~ This file is part of Loop Habit Tracker.
~
~ Loop Habit Tracker is free software: you can redistribute it and/or modify
~ it under the terms of the GNU General Public License as published by the
~ Free Software Foundation, either version 3 of the License, or (at your
~ option) any later version.
~
~ Loop Habit Tracker is distributed in the hope that it will be useful, but
~ WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
~ more details.
~
~ You should have received a copy of the GNU General Public License along
~ with this program. If not, see <http://www.gnu.org/licenses/>.
-->
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="trace">
<appender-ref ref="STDOUT"/>
</root>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="io.netty" level="INFO"/>
</configuration>

View File

@@ -0,0 +1,20 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
rootProject.name = "uhabits-server"

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync
import com.fasterxml.jackson.databind.*
data class SyncData(
val version: Long,
val content: String
)
data class RegisterReponse(val key: String)
data class GetDataVersionResponse(val version: Long)
val defaultMapper = ObjectMapper()
fun SyncData.toJson(): String = defaultMapper.writeValueAsString(this)
fun GetDataVersionResponse.toJson(): String = defaultMapper.writeValueAsString(this)

View File

@@ -0,0 +1,28 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync
open class SyncException: RuntimeException()
class KeyNotFoundException: SyncException()
class ServiceUnavailable: SyncException()
class EditConflictException: SyncException()

View File

@@ -0,0 +1,55 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import org.isoron.uhabits.sync.*
data class LinkRegisterRequestData(
val syncKey: String,
)
fun LinkRegisterRequestData.toJson(): String = defaultMapper.writeValueAsString(this)
fun Routing.links(app: SyncApplication) {
post("/links") {
try {
val data = call.receive<LinkRegisterRequestData>()
val link = app.server.registerLink(data.syncKey)
call.respond(HttpStatusCode.OK, link)
} catch (e: ServiceUnavailable) {
call.respond(HttpStatusCode.ServiceUnavailable)
}
}
get("/links/{id}") {
try {
val id = call.parameters["id"]!!
val link = app.server.getLink(id)
call.respond(HttpStatusCode.OK, link)
} catch (e: ServiceUnavailable) {
call.respond(HttpStatusCode.ServiceUnavailable)
} catch (e: KeyNotFoundException) {
call.respond(HttpStatusCode.NotFound)
}
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import io.prometheus.client.*
import io.prometheus.client.exporter.common.*
import io.prometheus.client.hotspot.*
import java.io.*
fun Routing.metrics(app: SyncApplication) {
// Register JVM metrics
DefaultExports.initialize()
get("/metrics") {
val writer = StringWriter()
TextFormat.write004(
writer,
CollectorRegistry.defaultRegistry.filteredMetricFamilySamples(setOf<String>()),
)
call.respond(HttpStatusCode.OK, writer.toString())
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.routing.*
import org.isoron.uhabits.sync.*
fun Routing.registration(app: SyncApplication) {
post("/register") {
try {
val key = app.server.register()
call.respond(HttpStatusCode.OK, RegisterReponse(key))
} catch (e: ServiceUnavailable) {
call.respond(HttpStatusCode.ServiceUnavailable)
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import io.ktor.http.*
import io.ktor.request.*
import io.ktor.response.*
import io.ktor.routing.*
import org.isoron.uhabits.sync.*
fun Routing.storage(app: SyncApplication) {
route("/db/{key}") {
get {
val key = call.parameters["key"]!!
try {
val data = app.server.getData(key)
call.respond(HttpStatusCode.OK, data)
} catch(e: KeyNotFoundException) {
call.respond(HttpStatusCode.NotFound)
}
}
put {
val key = call.parameters["key"]!!
val data = call.receive<SyncData>()
try {
app.server.put(key, data)
call.respond(HttpStatusCode.OK)
} catch (e: KeyNotFoundException) {
call.respond(HttpStatusCode.NotFound)
} catch (e: EditConflictException) {
call.respond(HttpStatusCode.Conflict)
}
}
get("version") {
val key = call.parameters["key"]!!
try {
val version = app.server.getDataVersion(key)
call.respond(HttpStatusCode.OK, GetDataVersionResponse(version))
} catch(e: KeyNotFoundException) {
call.respond(HttpStatusCode.NotFound)
}
}
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.jackson.*
import io.ktor.routing.*
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.repository.*
import org.isoron.uhabits.sync.server.*
import java.nio.file.*
fun Application.main() = SyncApplication().apply { main() }
val REPOSITORY_PATH: Path = Paths.get(System.getenv("LOOP_REPO_PATH")!!)
class SyncApplication(
val server: AbstractSyncServer = RepositorySyncServer(
FileRepository(REPOSITORY_PATH),
),
) {
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
install(ContentNegotiation) {
jackson { }
}
routing {
registration(this@SyncApplication)
storage(this@SyncApplication)
links(this@SyncApplication)
metrics(this@SyncApplication)
}
}
}

View File

@@ -0,0 +1,37 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.links
import org.isoron.uhabits.sync.*
import java.time.*
/**
* A Link maps a public URL (such as https://sync.loophabits.org/links/B752A6)
* to a synchronization key. They are used to transfer sync keys between devices
* without ever exposing the original sync key. Unlike sync keys, links expire
* after a few minutes.
*/
data class Link(
val id: String,
val syncKey: String,
val createdAt: Long,
)
fun Link.toJson(): String = defaultMapper.writeValueAsString(this)

View File

@@ -0,0 +1,49 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.links
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.utils.*
class LinkManager(
private val timeoutInMillis: Long = 900_000,
) {
private val links = HashMap<String, Link>()
fun register(syncKey: String): Link {
val link = Link(
id = randomString(64),
syncKey = syncKey,
createdAt = System.currentTimeMillis(),
)
links[link.id] = link
return link
}
fun get(id: String): Link {
val link = links[id] ?: throw KeyNotFoundException()
val ageInMillis = System.currentTimeMillis() - link.createdAt
if (ageInMillis > timeoutInMillis) {
links.remove(id)
throw KeyNotFoundException()
}
return link
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.repository
import org.isoron.uhabits.sync.*
import java.io.*
import java.nio.file.*
class FileRepository(
private val basepath: Path,
) : Repository {
override suspend fun put(key: String, data: SyncData) {
// Create directory
val dataPath = key.toDataPath()
val dataDir = dataPath.toFile()
dataDir.mkdirs()
// Create metadata
val metadataFile = dataPath.resolve("version").toFile()
metadataFile.outputStream().use { outputStream ->
PrintWriter(outputStream).use { printWriter ->
printWriter.print(data.version)
}
}
// Create data file
val dataFile = dataPath.resolve("content").toFile()
dataFile.outputStream().use { outputStream ->
PrintWriter(outputStream).use { printWriter ->
printWriter.print(data.content)
}
}
}
override suspend fun get(key: String): SyncData {
val dataPath = key.toDataPath()
val contentFile = dataPath.resolve("content").toFile()
val versionFile = dataPath.resolve("version").toFile()
if (!contentFile.exists() || !versionFile.exists()) {
throw KeyNotFoundException()
}
val version = versionFile.readText().trim().toLong()
return SyncData(version, contentFile.readText())
}
override suspend fun contains(key: String): Boolean {
val dataPath = key.toDataPath()
val versionFile = dataPath.resolve("version").toFile()
return versionFile.exists()
}
private fun String.toDataPath(): Path {
return basepath.resolve("${this[0]}/${this[1]}/${this[2]}/${this[3]}/$this")
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.repository
import com.sun.org.apache.xpath.internal.operations.*
import org.isoron.uhabits.sync.*
/**
* A class that knows how to store and retrieve a large number of [SyncData] items.
*/
interface Repository {
/**
* Stores a data item, under the provided key. The item can be later retrieved with [get].
* Replaces existing items silently.
*/
suspend fun put(key: String, data: SyncData)
/**
* Retrieves a data item that was previously stored using [put].
* @throws KeyNotFoundException If no such key exists.
*/
suspend fun get(key: String): SyncData
/**
* Returns true if the repository contains a given key.
*/
suspend fun contains(key: String): Boolean
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.server
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.links.*
interface AbstractSyncServer {
/**
* Generates and returns a new sync key, which can be used to store and retrive
* data.
*
* @throws ServiceUnavailable If key cannot be generated at this time, for example,
* due to insufficient server resources, temporary server maintenance or network problems.
*/
suspend fun register(): String
/**
* Replaces data for a given sync key.
*
* @throws KeyNotFoundException If key is not found
* @throws EditConflictException If the version of the data provided is not
* exactly the current data version plus one.
* @throws ServiceUnavailable If data cannot be put at this time, for example, due
* to insufficient server resources or network problems.
*/
suspend fun put(key: String, newData: SyncData)
/**
* Returns data for a given sync key.
*
* @throws KeyNotFoundException If key is not found
* @throws ServiceUnavailable If data cannot be retrieved at this time, for example, due
* to insufficient server resources or network problems.
*/
suspend fun getData(key: String): SyncData
/**
* Returns the current data version for the given key
*
* @throws KeyNotFoundException If key is not found
* @throws ServiceUnavailable If data cannot be retrieved at this time, for example, due
* to insufficient server resources or network problems.
*/
suspend fun getDataVersion(key: String): Long
/**
* Registers a new temporary link (mapping to the given sync key) and returns it.
*
* @throws ServiceUnavailable If the link cannot be generated at this time due to
* insufficient server resources.
*/
suspend fun registerLink(syncKey: String): Link
/**
* Retrieves the syncKey associated with the given link id.
*
* @throws ServiceUnavailable If the link cannot be resolved at this time due to
* insufficient server resources.
* @throws KeyNotFoundException If the link id cannot be found, or if it has
* expired.
*/
suspend fun getLink(id: String): Link
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.server
import io.prometheus.client.*
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.links.*
import org.isoron.uhabits.sync.repository.*
import org.isoron.uhabits.sync.utils.*
/**
* An AbstractSyncServer that stores all data in a [Repository].
*/
class RepositorySyncServer(
private val repo: Repository,
private val linkManager: LinkManager = LinkManager(),
) : AbstractSyncServer {
private val requestsCounter: Counter = Counter.build()
.name("requests_total")
.help("Total number of requests")
.labelNames("method")
.register()
override suspend fun register(): String {
requestsCounter.labels("register").inc()
val key = generateKey()
repo.put(key, SyncData(0, ""))
return key
}
override suspend fun put(key: String, newData: SyncData) {
requestsCounter.labels("put").inc()
if (!repo.contains(key)) {
throw KeyNotFoundException()
}
val prevData = repo.get(key)
if (newData.version != prevData.version + 1) {
throw EditConflictException()
}
repo.put(key, newData)
}
override suspend fun getData(key: String): SyncData {
requestsCounter.labels("getData").inc()
if (!repo.contains(key)) {
throw KeyNotFoundException()
}
return repo.get(key)
}
override suspend fun getDataVersion(key: String): Long {
requestsCounter.labels("getDataVersion").inc()
if (!repo.contains(key)) {
throw KeyNotFoundException()
}
return repo.get(key).version
}
override suspend fun registerLink(syncKey: String): Link {
requestsCounter.labels("registerLink").inc()
return linkManager.register(syncKey)
}
override suspend fun getLink(id: String): Link {
requestsCounter.labels("getLink").inc()
return linkManager.get(id)
}
private suspend fun generateKey(): String {
while (true) {
val key = randomString(64)
if (!repo.contains(key))
return key
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.utils
import java.util.*
import kotlin.streams.*
fun randomString(length: Long): String {
val chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
return Random().ints(length, 0, chars.length)
.asSequence()
.map(chars::get)
.joinToString("")
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.application.*
import org.isoron.uhabits.sync.server.*
import org.mockito.Mockito.*
open class BaseApplicationTest {
protected val server: AbstractSyncServer = mock(AbstractSyncServer::class.java)
protected fun app(): Application.() -> Unit = {
SyncApplication(server).apply {
main()
}
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.links.*
import org.junit.Test
import org.mockito.Mockito.*
import kotlin.test.*
class LinksModuleTest : BaseApplicationTest() {
private val link = Link(
id = "ABC123",
syncKey = "SECRET",
createdAt = System.currentTimeMillis(),
)
@Test
fun `when POST is successful should return link`(): Unit = runBlocking {
`when`(server.registerLink("SECRET")).thenReturn(link)
withTestApplication(app()) {
handlePost("/links", LinkRegisterRequestData(syncKey = "SECRET")).apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(link.toJson(), response.content)
}
}
}
@Test
fun `when GET is successful should return link`(): Unit = runBlocking {
`when`(server.getLink("ABC123")).thenReturn(link)
withTestApplication(app()) {
handleGet("/links/ABC123").apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(link.toJson(), response.content)
}
}
}
@Test
fun `GET with invalid link id should return 404`(): Unit = runBlocking {
`when`(server.getLink("ABC123")).thenThrow(KeyNotFoundException())
withTestApplication(app()) {
handleGet("/links/ABC123").apply {
assertEquals(HttpStatusCode.NotFound, response.status())
}
}
}
private fun TestApplicationEngine.handlePost(url: String, data: LinkRegisterRequestData): TestApplicationCall {
return handleRequest(HttpMethod.Post, url) {
addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
setBody(data.toJson())
}
}
private fun TestApplicationEngine.handleGet(url: String): TestApplicationCall {
return handleRequest(HttpMethod.Get, url)
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import org.isoron.uhabits.sync.*
import org.junit.Test
import org.mockito.*
import org.mockito.Mockito.*
import kotlin.test.*
class RegistrationModuleTest : BaseApplicationTest() {
@Test
fun `when register succeeds should return generated key`():Unit = runBlocking {
`when`(server.register()).thenReturn("ABCDEF")
withTestApplication(app()) {
val call = handleRequest(HttpMethod.Post, "/register")
assertEquals(HttpStatusCode.OK, call.response.status())
assertEquals("{\"key\":\"ABCDEF\"}", call.response.content)
}
}
@Test
fun `when registration is unavailable should return 503`():Unit = runBlocking {
`when`(server.register()).thenThrow(ServiceUnavailable())
withTestApplication(app()) {
val call = handleRequest(HttpMethod.Post, "/register")
assertEquals(HttpStatusCode.ServiceUnavailable, call.response.status())
}
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.app
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.coroutines.*
import org.isoron.uhabits.sync.*
import org.junit.Test
import org.mockito.Mockito.*
import kotlin.test.*
class StorageModuleTest : BaseApplicationTest() {
private val data1 = SyncData(1, "Hello world")
private val data2 = SyncData(2, "Hello new world")
@Test
fun `when get succeeds should return data`(): Unit = runBlocking {
`when`(server.getData("k1")).thenReturn(data1)
withTestApplication(app()) {
handleGet("/db/k1").apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(data1.toJson(), response.content)
}
}
}
@Test
fun `when get version succeeds should return version`(): Unit = runBlocking {
`when`(server.getDataVersion("k1")).thenReturn(30)
withTestApplication(app()) {
handleGet("/db/k1/version").apply {
assertEquals(HttpStatusCode.OK, response.status())
assertEquals(GetDataVersionResponse(30).toJson(), response.content)
}
}
}
@Test
fun `when get with invalid key should return 404`(): Unit = runBlocking {
`when`(server.getData("k1")).thenThrow(KeyNotFoundException())
withTestApplication(app()) {
handleGet("/db/k1").apply {
assertEquals(HttpStatusCode.NotFound, response.status())
}
}
}
@Test
fun `when put succeeds should return OK`(): Unit = runBlocking {
withTestApplication(app()) {
handlePut("/db/k1", data1).apply {
runBlocking {
assertEquals(HttpStatusCode.OK, response.status())
verify(server).put("k1", data1)
}
}
}
}
@Test
fun `when put with invalid key should return 404`(): Unit = runBlocking {
`when`(server.put("k1", data1)).thenThrow(KeyNotFoundException())
withTestApplication(app()) {
handlePut("/db/k1", data1).apply {
assertEquals(HttpStatusCode.NotFound, response.status())
}
}
}
@Test
fun `when put with invalid version should return 409 and current data`(): Unit = runBlocking {
`when`(server.put("k1", data1)).thenThrow(EditConflictException())
`when`(server.getData("k1")).thenReturn(data2)
withTestApplication(app()) {
handlePut("/db/k1", data1).apply {
assertEquals(HttpStatusCode.Conflict, response.status())
}
}
}
private fun TestApplicationEngine.handlePut(url: String, data: SyncData): TestApplicationCall {
return handleRequest(HttpMethod.Put, url) {
addHeader(HttpHeaders.ContentType, ContentType.Application.Json.toString())
setBody(data.toJson())
}
}
private fun TestApplicationEngine.handleGet(url: String): TestApplicationCall {
return handleRequest(HttpMethod.Get, url)
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.links
import org.isoron.uhabits.sync.*
import org.junit.Test
import kotlin.test.*
class LinkManagerTest {
@Test
fun testUsage() {
val manager = LinkManager(timeoutInMillis = 250)
val originalLink = manager.register(syncKey = "SECRET")
val retrievedLink = manager.get(originalLink.id)
assertEquals(originalLink, retrievedLink)
Thread.sleep(260) // wait until expiration
assertFailsWith<KeyNotFoundException> {
manager.get(originalLink.id)
}
assertFailsWith<KeyNotFoundException> {
manager.get("INVALID")
}
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
@file:Suppress("BlockingMethodInNonBlockingContext")
package org.isoron.uhabits.sync.repository
import kotlinx.coroutines.*
import org.hamcrest.CoreMatchers.*
import org.isoron.uhabits.sync.*
import org.junit.*
import org.junit.Assert.*
import java.nio.file.*
class FileRepositoryTest {
@Test
fun testUsage() = runBlocking {
val tempdir = Files.createTempDirectory("db")!!
val repo = FileRepository(tempdir)
val original = SyncData(10, "Hello world")
repo.put("abcdefg", original)
val metaPath = tempdir.resolve("a/b/c/d/abcdefg/version")
assertTrue("$metaPath should exist", Files.exists(metaPath))
assertEquals("10", metaPath.toFile().readText())
val dataPath = tempdir.resolve("a/b/c/d/abcdefg/content")
assertTrue("$dataPath should exist", Files.exists(dataPath))
assertEquals("Hello world", dataPath.toFile().readText())
val retrieved = repo.get("abcdefg")
assertThat(retrieved, equalTo(original))
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright (C) 2016-2020 Alinson Santos Xavier <git@axavier.org>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.uhabits.sync.server
import kotlinx.coroutines.*
import org.isoron.uhabits.sync.*
import org.isoron.uhabits.sync.repository.*
import org.junit.Test
import java.nio.file.*
import kotlin.test.*
class RepositorySyncServerTest {
private val tempdir = Files.createTempDirectory("db")
private val server = RepositorySyncServer(FileRepository(tempdir))
private val key = runBlocking { server.register() }
@Test
fun testUsage(): Unit = runBlocking {
val data0 = SyncData(0, "")
assertEquals(server.getData(key), data0)
val data1 = SyncData(1, "Hello world")
server.put(key, data1)
assertEquals(server.getData(key), data1)
val data2 = SyncData(2, "Hello new world")
server.put(key, data2)
assertEquals(server.getData(key), data2)
assertFailsWith<EditConflictException> {
server.put(key, data2)
}
assertFailsWith<KeyNotFoundException> {
server.getData("INVALID")
}
assertFailsWith<KeyNotFoundException> {
server.put("INVALID", data0)
}
}
}