diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 000000000..fae6b746e --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,7 @@ +/.gradle +/.idea +/out +/build +*.iml +*.ipr +*.iws diff --git a/server/build.gradle b/server/build.gradle new file mode 100644 index 000000000..543e5531a --- /dev/null +++ b/server/build.gradle @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +buildscript { + repositories { + jcenter() + } + + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' +apply plugin: 'application' + +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" + testImplementation "io.ktor:ktor-server-tests:$ktor_version" + testImplementation "org.mockito:mockito-core:2.+" +} diff --git a/server/gradle.properties b/server/gradle.properties new file mode 100644 index 000000000..9df9c1449 --- /dev/null +++ b/server/gradle.properties @@ -0,0 +1,23 @@ +# +# Copyright (C) 2016-2020 Alinson Santos Xavier +# +# 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 . +# + +ktor_version=1.4.2 +kotlin.code.style=official +kotlin_version=1.4.10 +logback_version=1.2.1 diff --git a/server/gradle/wrapper/gradle-wrapper.jar b/server/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..28861d273 Binary files /dev/null and b/server/gradle/wrapper/gradle-wrapper.jar differ diff --git a/server/gradle/wrapper/gradle-wrapper.properties b/server/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..33682bbbf --- /dev/null +++ b/server/gradle/wrapper/gradle-wrapper.properties @@ -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 diff --git a/server/gradlew b/server/gradlew new file mode 100755 index 000000000..beb887fbf --- /dev/null +++ b/server/gradlew @@ -0,0 +1,191 @@ +#!/usr/bin/env sh + +# +# Copyright (C) 2016-2020 Alinson Santos Xavier +# +# 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 . +# + +############################################################################## +## +## 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" "$@" diff --git a/server/gradlew.bat b/server/gradlew.bat new file mode 100644 index 000000000..f9553162f --- /dev/null +++ b/server/gradlew.bat @@ -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 diff --git a/server/resources/application.conf b/server/resources/application.conf new file mode 100644 index 000000000..d5b282277 --- /dev/null +++ b/server/resources/application.conf @@ -0,0 +1,9 @@ +ktor { + deployment { + port = 8080 + port = ${?PORT} + } + application { + modules = [ org.isoron.uhabits.sync.app.SyncApplicationKt.main ] + } +} diff --git a/server/resources/logback.xml b/server/resources/logback.xml new file mode 100644 index 000000000..04028d5de --- /dev/null +++ b/server/resources/logback.xml @@ -0,0 +1,31 @@ + + + + + + %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + diff --git a/server/settings.gradle b/server/settings.gradle new file mode 100644 index 000000000..e866a88ff --- /dev/null +++ b/server/settings.gradle @@ -0,0 +1,20 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +rootProject.name = "syncserver" diff --git a/server/src/org/isoron/uhabits/sync/AbstractSyncServer.kt b/server/src/org/isoron/uhabits/sync/AbstractSyncServer.kt new file mode 100644 index 000000000..efaa7ed06 --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/AbstractSyncServer.kt @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync + +interface AbstractSyncServer { + /** + * Generates and returns a new sync key, which can be used to store and retrive + * data. + * + * @throws RegistrationUnavailableException If key cannot be generated at this + * time, for example, due to insufficient server resources or temporary + * maintenance. + */ + 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. + */ + fun put(key: String, newData: SyncData) + + /** + * Returns data for a given sync key. + * + * @throws KeyNotFoundException If key is not found + */ + fun get(key: String): SyncData +} \ No newline at end of file diff --git a/server/src/org/isoron/uhabits/sync/MemorySyncServer.kt b/server/src/org/isoron/uhabits/sync/MemorySyncServer.kt new file mode 100644 index 000000000..44798665f --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/MemorySyncServer.kt @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync + +import java.util.* +import kotlin.streams.* + +/** + * An AbstractSyncServer that stores all data in memory. + */ +class MemorySyncServer : AbstractSyncServer { + private val db = mutableMapOf() + + override fun register(): String { + synchronized(db) { + val key = generateKey() + db[key] = SyncData(0, "") + return key + } + } + + override fun put(key: String, newData: SyncData) { + synchronized(db) { + if (!db.containsKey(key)) { + throw KeyNotFoundException() + } + val prevData = db.getValue(key) + if (newData.version != prevData.version + 1) { + throw EditConflictException() + } + db[key] = newData + } + } + + override fun get(key: String): SyncData { + synchronized(db) { + if (!db.containsKey(key)) { + throw KeyNotFoundException() + } + return db.getValue(key) + } + } + + private fun generateKey(): String { + val chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + while (true) { + val key = Random().ints(64, 0, chars.length) + .asSequence() + .map(chars::get) + .joinToString("") + if (!db.containsKey(key)) + return key + } + + } +} diff --git a/server/src/org/isoron/uhabits/sync/SyncData.kt b/server/src/org/isoron/uhabits/sync/SyncData.kt new file mode 100644 index 000000000..634982ec5 --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/SyncData.kt @@ -0,0 +1,30 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync + +import com.fasterxml.jackson.databind.* + +data class SyncData( + val version: Int, + val content: String, +) + +val defaultMapper = ObjectMapper() +fun SyncData.toJson(): String = defaultMapper.writeValueAsString(this) diff --git a/server/src/org/isoron/uhabits/sync/SyncException.kt b/server/src/org/isoron/uhabits/sync/SyncException.kt new file mode 100644 index 000000000..8be49b301 --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/SyncException.kt @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync + +/** + * Generic class for all exceptions thrown by SyncServer. + */ +open class SyncException: RuntimeException() + +class KeyNotFoundException: SyncException() + +class RegistrationUnavailableException: SyncException() + +class EditConflictException: SyncException() \ No newline at end of file diff --git a/server/src/org/isoron/uhabits/sync/app/RegistrationModule.kt b/server/src/org/isoron/uhabits/sync/app/RegistrationModule.kt new file mode 100644 index 000000000..adc8f0e5d --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/app/RegistrationModule.kt @@ -0,0 +1,37 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +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, mapOf("key" to key)) + } catch (e: RegistrationUnavailableException) { + call.respond(HttpStatusCode.ServiceUnavailable) + } + } +} diff --git a/server/src/org/isoron/uhabits/sync/app/StorageModule.kt b/server/src/org/isoron/uhabits/sync/app/StorageModule.kt new file mode 100644 index 000000000..5d1a17679 --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/app/StorageModule.kt @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +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.get(key) + call.respond(HttpStatusCode.OK, data) + } catch(e: KeyNotFoundException) { + call.respond(HttpStatusCode.NotFound) + } + } + put { + val key = call.parameters["key"]!! + val data = call.receive() + try { + app.server.put(key, data) + call.respond(HttpStatusCode.OK) + } catch (e: KeyNotFoundException) { + call.respond(HttpStatusCode.NotFound) + } catch (e: EditConflictException) { + val currData = app.server.get(key) + call.respond(HttpStatusCode.Conflict, currData) + } + } + } +} \ No newline at end of file diff --git a/server/src/org/isoron/uhabits/sync/app/SyncApplication.kt b/server/src/org/isoron/uhabits/sync/app/SyncApplication.kt new file mode 100644 index 000000000..92798b58b --- /dev/null +++ b/server/src/org/isoron/uhabits/sync/app/SyncApplication.kt @@ -0,0 +1,44 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +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.* + +fun Application.main() = SyncApplication().apply { main() } + +class SyncApplication( + val server: AbstractSyncServer = MemorySyncServer(), +) { + fun Application.main() { + install(DefaultHeaders) + install(CallLogging) + install(ContentNegotiation) { + jackson { } + } + routing { + registration(this@SyncApplication) + storage(this@SyncApplication) + } + } +} diff --git a/server/test/org/isoron/uhabits/sync/MemorySyncServerTest.kt b/server/test/org/isoron/uhabits/sync/MemorySyncServerTest.kt new file mode 100644 index 000000000..c7ec025ee --- /dev/null +++ b/server/test/org/isoron/uhabits/sync/MemorySyncServerTest.kt @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync + +import org.junit.Test +import kotlin.test.* + +class MemorySyncServerTest { + + private val server = MemorySyncServer() + private val key = server.register() + + @Test + fun testUsage() { + val data0 = SyncData(0, "") + assertEquals(server.get(key), data0) + + val data1 = SyncData(1, "Hello world") + server.put(key, data1) + assertEquals(server.get(key), data1) + + val data2 = SyncData(2, "Hello new world") + server.put(key, data2) + assertEquals(server.get(key), data2) + + assertFailsWith { + server.put(key, data2) + } + + assertFailsWith { + server.get("INVALID") + } + + assertFailsWith { + server.put("INVALID", data0) + } + } +} \ No newline at end of file diff --git a/server/test/org/isoron/uhabits/sync/app/BaseApplicationTest.kt b/server/test/org/isoron/uhabits/sync/app/BaseApplicationTest.kt new file mode 100644 index 000000000..190fc6fcf --- /dev/null +++ b/server/test/org/isoron/uhabits/sync/app/BaseApplicationTest.kt @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync.app + +import io.ktor.application.* +import org.isoron.uhabits.sync.* +import org.mockito.Mockito.* + +open class BaseApplicationTest { + + protected val server: AbstractSyncServer = mock(AbstractSyncServer::class.java) + + protected fun app(): Application.() -> Unit = { + SyncApplication(server).apply { + main() + } + } +} diff --git a/server/test/org/isoron/uhabits/sync/app/RegistrationModuleTest.kt b/server/test/org/isoron/uhabits/sync/app/RegistrationModuleTest.kt new file mode 100644 index 000000000..2375fe4fb --- /dev/null +++ b/server/test/org/isoron/uhabits/sync/app/RegistrationModuleTest.kt @@ -0,0 +1,49 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync.app + +import io.ktor.http.* +import io.ktor.server.testing.* +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`() { + `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`() { + `when`(server.register()).thenThrow(RegistrationUnavailableException()) + withTestApplication(app()) { + val call = handleRequest(HttpMethod.Post, "/register") + assertEquals(HttpStatusCode.ServiceUnavailable, call.response.status()) + } + } +} \ No newline at end of file diff --git a/server/test/org/isoron/uhabits/sync/app/StorageModuleTest.kt b/server/test/org/isoron/uhabits/sync/app/StorageModuleTest.kt new file mode 100644 index 000000000..01e23b328 --- /dev/null +++ b/server/test/org/isoron/uhabits/sync/app/StorageModuleTest.kt @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2016-2020 Alinson Santos Xavier + * + * 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 . + */ + +package org.isoron.uhabits.sync.app + +import io.ktor.http.* +import io.ktor.server.testing.* +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`() { + `when`(server.get("k1")).thenReturn(data1) + withTestApplication(app()) { + handleGet("/db/k1").apply { + assertEquals(HttpStatusCode.OK, response.status()) + assertEquals(data1.toJson(), response.content) + } + } + } + + @Test + fun `when get with invalid key should return 404`() { + `when`(server.get("k1")).thenThrow(KeyNotFoundException()) + withTestApplication(app()) { + handleGet("/db/k1").apply { + assertEquals(HttpStatusCode.NotFound, response.status()) + } + } + } + + + @Test + fun `when put succeeds should return OK`() { + withTestApplication(app()) { + handlePut("/db/k1", data1).apply { + assertEquals(HttpStatusCode.OK, response.status()) + verify(server).put("k1", data1) + } + } + } + + @Test + fun `when put with invalid key should return 404`() { + `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`() { + `when`(server.put("k1", data1)).thenThrow(EditConflictException()) + `when`(server.get("k1")).thenReturn(data2) + withTestApplication(app()) { + handlePut("/db/k1", data1).apply { + assertEquals(HttpStatusCode.Conflict, response.status()) + assertEquals(data2.toJson(), response.content) + } + } + } + + 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) + } +}