diff --git a/eej_rate_limiter/Dockerfile b/eej_rate_limiter/Dockerfile index f943e9f..efd2640 100644 --- a/eej_rate_limiter/Dockerfile +++ b/eej_rate_limiter/Dockerfile @@ -1,4 +1,4 @@ -FROM arm64v8/openjdk:17-ea-16-jdk +FROM openjdk:17-jdk ARG DEPENDENCY=build/dependency diff --git a/eej_rate_limiter/docker-compose.yml b/eej_rate_limiter/docker-compose.yml index dc11769..1262c78 100644 --- a/eej_rate_limiter/docker-compose.yml +++ b/eej_rate_limiter/docker-compose.yml @@ -2,7 +2,7 @@ version: '3.8' services: redis: - image: arm64v8/redis:7.4-bookworm # ARM64-compatible Redis + image: redis:7.4-bookworm container_name: redis ports: - "6379:6379" diff --git a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/core/RateLimiterRuleService.java b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/core/RateLimiterRuleService.java index bd7a251..bcb091f 100644 --- a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/core/RateLimiterRuleService.java +++ b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/core/RateLimiterRuleService.java @@ -1,9 +1,8 @@ package com.enjoy.ds.ratelimiter.core; +import com.enjoy.ds.ratelimiter.core.model.APIRule; import java.util.Map; import java.util.concurrent.TimeUnit; - -import com.enjoy.ds.ratelimiter.core.model.APIRule; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import reactor.core.publisher.Mono; diff --git a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/model/User.java b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/model/User.java index 69175a6..f6d28e0 100644 --- a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/model/User.java +++ b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/model/User.java @@ -14,7 +14,10 @@ public class User { private String password; // Store hashed passwords! private String role; // e.g., "ROLE_USER", "ROLE_ADMIN" - public static User copy(User original) { + public User(UUID uuid, String admin, String s, String admin1) { + } + + public static User copy(User original) { return new User(original.id, original.username, original.password, original.role); } } diff --git a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/utils/SearchingUtil.java b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/utils/SearchingUtil.java index ed1bf80..40c33d7 100644 --- a/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/utils/SearchingUtil.java +++ b/eej_rate_limiter/src/main/java/com/enjoy/ds/ratelimiter/utils/SearchingUtil.java @@ -2,9 +2,7 @@ import java.util.List; import java.util.Objects; - import lombok.NonNull; -import org.springframework.security.core.parameters.P; public class SearchingUtil { public static int searchMaximumElementLowerThan( @@ -20,15 +18,15 @@ public static int searchMaximumElementLowerThan( while (left < right) { int mid = left + (right - left) / 2; - if(timestamps.get(mid) >= timestamp){ + if (timestamps.get(mid) >= timestamp) { right = mid; - } else if(timestamps.get(mid) < timestamp) { + } else if (timestamps.get(mid) < timestamp) { res = mid; left = mid + 1; } } - if(res != -1 && Objects.equals(timestamps.get(res), timestamp)){ + if (res != -1 && Objects.equals(timestamps.get(res), timestamp)) { return -1; } diff --git a/eej_rate_limiter/src/test/java/com/enjoy/ds/ratelimiter/PostControllerTest.java b/eej_rate_limiter/src/test/java/com/enjoy/ds/ratelimiter/PostControllerTest.java index a888e45..abbcbf5 100644 --- a/eej_rate_limiter/src/test/java/com/enjoy/ds/ratelimiter/PostControllerTest.java +++ b/eej_rate_limiter/src/test/java/com/enjoy/ds/ratelimiter/PostControllerTest.java @@ -4,8 +4,8 @@ import static org.mockito.Mockito.when; import com.enjoy.ds.ratelimiter.cache.RedisService; -import com.enjoy.ds.ratelimiter.core.model.APIRule; import com.enjoy.ds.ratelimiter.core.RateLimiterRuleService; +import com.enjoy.ds.ratelimiter.core.model.APIRule; import com.enjoy.ds.ratelimiter.model.Post; import java.time.Duration; import java.time.temporal.ChronoUnit; diff --git a/key_value/.gitignore b/key_value/.gitignore new file mode 100644 index 0000000..b63da45 --- /dev/null +++ b/key_value/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/key_value/New Text Document.txt b/key_value/New Text Document.txt new file mode 100644 index 0000000..e69de29 diff --git a/key_value/README.md b/key_value/README.md new file mode 100644 index 0000000..c071d78 --- /dev/null +++ b/key_value/README.md @@ -0,0 +1,40 @@ +Distributed Key-Value Store Project +This project implements a distributed key-value store inspired by Chapters 5 (Sharding) and 6 (Data Partitioning and Replication) of System Design Interview: An Insider's Guide by Alex Xu. It is designed as a hands-on learning tool for system design concepts, particularly for junior-level interview preparation. The system runs three nodes on ports 8080, 8081, and 8082, using sharding to distribute data and timestamp-based versioning for conflict resolution. +Overview +The application is built with Java 17, Spring Boot, and Gradle, featuring a web-based interface to interact with the distributed store. Users can add and delete key-value pairs, with the data dynamically displayed across the nodes. The project emphasizes scalability, availability, and eventual consistency, aligning with distributed system design principles. +Current Implementation +Key Features + +Sharding: Data is partitioned across three nodes using a simple hash-based sharding function (hash(key) % 3). +Versioning: Timestamps ensure last-write-wins conflict resolution for concurrent updates. +Distributed Architecture: Nodes communicate via HTTP to forward requests to the appropriate shard. + +File Purposes + +build.gradle.kts: Configures the Gradle build with Java 17 and Spring Boot dependencies. Ensures the project compiles and runs with the defined version (0.0.1-SNAPSHOT). +KeyValueStoreApplication.java: The main entry point that launches three nodes in separate threads on ports 8080, 8081, and 8082 (will do the dynamic node set-up later). Includes port availability checks and error handling for robust startup. +KeyValueEntry.java: Defines the data model for key-value pairs, including a timestamp for versioning. +NodeStorage.java: Manages in-memory storage for each node, providing methods to put, get, delete, and list key-value entries. +NodeConfig.java: Holds configuration details for each node (ID, port, and list of all nodes) for distributed communication. +KeyValueService.java: Implements the business logic, computing shard IDs, handling PUT, GET, and DELETE operations, and forwarding requests to the correct node. +KeyValueController.java: Exposes REST endpoints (/api/kv/put, /api/kv/get, /api/kv/delete, /api/kv/list) to interact with the service, with CORS support and detailed error handling. +index.html: + +Build and Run: +Run gradle build to compile. +Access the interface at http://localhost:8080/. + + +Usage: +Add a key-value pair (e.g., key: user123, value: Alice) via the Computer section. +Delete a key and observe updates in the node tables and log. +Check the action log for results or errors. + + + +Future Directions + +Replication: Implement data replication across nodes for fault tolerance (Chapter 6), ensuring data availability if a node fails. +Consistent Hashing: Replace the current modulo-based sharding with consistent hashing to reduce rehashing costs during node additions/removals (Chapter 5). +ance learning and interview readiness. +![img.png](img.png) \ No newline at end of file diff --git a/key_value/build.gradle.kts b/key_value/build.gradle.kts new file mode 100644 index 0000000..2cb0ef2 --- /dev/null +++ b/key_value/build.gradle.kts @@ -0,0 +1,34 @@ +plugins { + id("org.springframework.boot") version "3.2.5" + id("io.spring.dependency-management") version "1.1.4" + java + id("org.jetbrains.kotlin.jvm") version "1.9.22" apply false // Optional, for Kotlin compatibility +} + +group = "com.example" +version = "0.0.1-SNAPSHOT" + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("com.fasterxml.jackson.core:jackson-databind:2.15.2") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation(platform("org.junit:junit-bom:5.10.0")) + testImplementation("org.junit.jupiter:junit-jupiter") +} + +tasks.withType { + useJUnitPlatform() +} + +tasks.bootJar { + archiveFileName.set("distributed-key-value-store.jar") +} \ No newline at end of file diff --git a/key_value/gradle/wrapper/gradle-wrapper.jar b/key_value/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 Binary files /dev/null and b/key_value/gradle/wrapper/gradle-wrapper.jar differ diff --git a/key_value/gradle/wrapper/gradle-wrapper.properties b/key_value/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ae1d99d --- /dev/null +++ b/key_value/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Apr 28 21:55:28 ICT 2025 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/key_value/gradlew b/key_value/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/key_value/gradlew @@ -0,0 +1,234 @@ +#!/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. +# + +############################################################################## +# +# 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/master/subprojects/plugins/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 + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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='"-Xmx64m" "-Xms64m"' + +# 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=$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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + 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 + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# 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/key_value/gradlew.bat b/key_value/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/key_value/gradlew.bat @@ -0,0 +1,89 @@ +@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 + +@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 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%" == "0" goto execute + +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 execute + +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 + +: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 %* + +: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/key_value/img.png b/key_value/img.png new file mode 100644 index 0000000..e09d953 Binary files /dev/null and b/key_value/img.png differ diff --git a/key_value/index.html b/key_value/index.html new file mode 100644 index 0000000..cc35674 --- /dev/null +++ b/key_value/index.html @@ -0,0 +1,85 @@ + + + + + + Key-Value Store Demo + + + +

Distributed Key-Value Store

+ +
+

Put Key-Value Pair

+
+
+
+ +
+ +
+

Get Value

+
+ +
+ +
+

Delete Key

+
+ +
+ +
Response will appear here
+ + + + \ No newline at end of file diff --git a/key_value/settings.gradle.kts b/key_value/settings.gradle.kts new file mode 100644 index 0000000..413f0e7 --- /dev/null +++ b/key_value/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "key_value" \ No newline at end of file diff --git a/key_value/src/main/java/com/example/KeyValueStoreApplication.java b/key_value/src/main/java/com/example/KeyValueStoreApplication.java new file mode 100644 index 0000000..14e27f7 --- /dev/null +++ b/key_value/src/main/java/com/example/KeyValueStoreApplication.java @@ -0,0 +1,99 @@ +package com.example; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.web.client.RestTemplate; + +import java.net.BindException; +import java.net.ServerSocket; +import java.util.Arrays; +import java.util.List; + +@SpringBootApplication +public class KeyValueStoreApplication { + private static final Logger logger = LoggerFactory.getLogger(KeyValueStoreApplication.class); + + public static void main(String[] args) { + // Define node configurations + List nodeConfigs = Arrays.asList( + new NodeConfig(0, 8080), + new NodeConfig(1, 8081), + new NodeConfig(2, 8082) + ); + + // Check port availability before starting nodes + for (NodeConfig config : nodeConfigs) { + if (!isPortAvailable(config.port)) { + logger.error("Port {} is already in use. Cannot start node {}. Please free the port or change the configuration.", config.port, config.id); + System.exit(1); + } + } + + // Start each node in a separate thread with a delay + for (NodeConfig config : nodeConfigs) { + new Thread(() -> { + try { + logger.info("Starting node {} on port {}", config.id, config.port); + new SpringApplicationBuilder(KeyValueStoreApplication.class) + .properties( + "server.port=" + config.port, + "node.id=" + config.id, + "node.port=" + config.port, + "node.nodes[0].id=0", + "node.nodes[0].host=localhost", + "node.nodes[0].port=8080", + "node.nodes[1].id=1", + "node.nodes[1].host=localhost", + "node.nodes[1].port=8081", + "node.nodes[2].id=2", + "node.nodes[2].host=localhost", + "node.nodes[2].port=8082" + ) + .run(args); + logger.info("Node {} started on port {}", config.id, config.port); + } catch (Exception e) { + logger.error("Failed to start node {} on port {}: {}", config.id, config.port, e.getMessage(), e); + System.exit(1); + } + }).start(); + try { + Thread.sleep(1000); // Delay to avoid race conditions + } catch (InterruptedException e) { + logger.error("Interrupted while starting node {}", config.id, e); + System.exit(1); + } + } + } + + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + // Temporary class for node configuration + private static class NodeConfig { + int id; + int port; + + NodeConfig(int id, int port) { + this.id = id; + this.port = port; + } + } + + private static boolean isPortAvailable(int port) { + try (ServerSocket socket = new ServerSocket(port)) { + socket.setReuseAddress(true); + return true; + } catch (BindException e) { + return false; + } catch (Exception e) { + logger.error("Error checking port {} availability: {}", port, e.getMessage(), e); + return false; + } + } +} \ No newline at end of file diff --git a/key_value/src/main/java/com/example/keyvaluestore/config/NodeConfig.java b/key_value/src/main/java/com/example/keyvaluestore/config/NodeConfig.java new file mode 100644 index 0000000..5f628d6 --- /dev/null +++ b/key_value/src/main/java/com/example/keyvaluestore/config/NodeConfig.java @@ -0,0 +1,68 @@ +package com.example.keyvaluestore.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +@Configuration +@ConfigurationProperties(prefix = "node") +public class NodeConfig { + private int id; + private int port; + private List nodes; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public List getNodes() { + return nodes; + } + + public void setNodes(List nodes) { + this.nodes = nodes; + } + + public static class NodeInfo { + private int id; + private String host; + private int port; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getHost() { + return host; + } + + public void setHost(String host) { + this.host = host; + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + } +} \ No newline at end of file diff --git a/key_value/src/main/java/com/example/keyvaluestore/controller/KeyValueController.java b/key_value/src/main/java/com/example/keyvaluestore/controller/KeyValueController.java new file mode 100644 index 0000000..390e01a --- /dev/null +++ b/key_value/src/main/java/com/example/keyvaluestore/controller/KeyValueController.java @@ -0,0 +1,94 @@ +package com.example.keyvaluestore.controller; + +import com.example.keyvaluestore.model.KeyValueEntry; +import com.example.keyvaluestore.service.KeyValueService; +import com.example.keyvaluestore.storage.NodeStorage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +@RestController +@RequestMapping("/api/kv") +@CrossOrigin(origins = {"http://127.0.0.1:5500", "http://localhost:8080"}, methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.DELETE}) +public class KeyValueController { + + @Autowired + private KeyValueService keyValueService; + + @Autowired + private NodeStorage nodeStorage; + + @PostMapping("/put") + public ResponseEntity put(@RequestParam String key, @RequestParam String value, @RequestParam long timestamp) { + try { + return keyValueService.put(key, value, timestamp); + } catch (IllegalArgumentException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("timestamp", new java.util.Date().toString()); + errorResponse.put("status", 400); + errorResponse.put("error", "Bad Request"); + errorResponse.put("message", "Invalid timestamp value: " + e.getMessage()); + errorResponse.put("path", "/api/kv/put"); + return ResponseEntity.badRequest().body(errorResponse); + } + } + + @GetMapping("/get") + public ResponseEntity get(@RequestParam String key) { + try { + return keyValueService.get(key); + } catch (IllegalArgumentException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("timestamp", new java.util.Date().toString()); + errorResponse.put("status", 400); + errorResponse.put("error", "Bad Request"); + errorResponse.put("message", "Invalid key: " + e.getMessage()); + errorResponse.put("path", "/api/kv/get"); + return ResponseEntity.badRequest().body(errorResponse); + } + } + + @DeleteMapping("/delete") + public ResponseEntity delete(@RequestParam String key) { + try { + return keyValueService.delete(key); + } catch (IllegalArgumentException e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("timestamp", new java.util.Date().toString()); + errorResponse.put("status", 400); + errorResponse.put("error", "Bad Request"); + errorResponse.put("message", "Invalid key: " + e.getMessage()); + errorResponse.put("path", "/api/kv/delete"); + return ResponseEntity.badRequest().body(errorResponse); + } + } + + @GetMapping("/list") + public ResponseEntity list() { + try { + List> entries = nodeStorage.getStore().values().stream() + .map(entry -> { + Map map = new HashMap<>(); + map.put("key", entry.getKey()); + map.put("value", entry.getValue()); + map.put("timestamp", entry.getTimestamp()); + return map; + }) + .collect(Collectors.toList()); + return ResponseEntity.ok(entries); + } catch (Exception e) { + Map errorResponse = new HashMap<>(); + errorResponse.put("timestamp", new java.util.Date().toString()); + errorResponse.put("status", 500); + errorResponse.put("error", "Internal Server Error"); + errorResponse.put("message", "Failed to list entries: " + e.getMessage()); + errorResponse.put("path", "/api/kv/list"); + return ResponseEntity.status(500).body(errorResponse); + } + } +} \ No newline at end of file diff --git a/key_value/src/main/java/com/example/keyvaluestore/model/KeyValueEntry.java b/key_value/src/main/java/com/example/keyvaluestore/model/KeyValueEntry.java new file mode 100644 index 0000000..a589b6e --- /dev/null +++ b/key_value/src/main/java/com/example/keyvaluestore/model/KeyValueEntry.java @@ -0,0 +1,33 @@ +package com.example.keyvaluestore.model; + +public class KeyValueEntry { + private String key; + private String value; + private long timestamp; + + public KeyValueEntry(String key, String value, long timestamp) { + this.key = key; + this.value = value; + this.timestamp = timestamp; + } + + public String getKey() { + return key; + } + + public String getValue() { + return value; + } + + public long getTimestamp() { + return timestamp; + } + + public void setValue(String value) { + this.value = value; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } +} \ No newline at end of file diff --git a/key_value/src/main/java/com/example/keyvaluestore/service/KeyValueService.java b/key_value/src/main/java/com/example/keyvaluestore/service/KeyValueService.java new file mode 100644 index 0000000..264025d --- /dev/null +++ b/key_value/src/main/java/com/example/keyvaluestore/service/KeyValueService.java @@ -0,0 +1,102 @@ +package com.example.keyvaluestore.service; + +import com.example.keyvaluestore.config.NodeConfig; +import com.example.keyvaluestore.model.KeyValueEntry; +import com.example.keyvaluestore.storage.NodeStorage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestTemplate; + +@Service +public class KeyValueService { + private static final Logger logger = LoggerFactory.getLogger(KeyValueService.class); + + @Autowired + private NodeStorage nodeStorage; + + @Autowired + private NodeConfig nodeConfig; + + @Autowired + private RestTemplate restTemplate; + + public ResponseEntity put(String key, String value, long timestamp) { + int targetNodeId = computeShardId(key); + logger.info("Processing put for key {} on node {}", key, targetNodeId); + if (targetNodeId == nodeConfig.getId()) { + KeyValueEntry existing = nodeStorage.get(key); + if (existing == null || existing.getTimestamp() <= timestamp) { + nodeStorage.put(key, value, timestamp); + logger.info("Stored key {} on node {}", key, targetNodeId); + return ResponseEntity.ok("Stored successfully on node " + targetNodeId); + } + logger.warn("Rejected put for key {} due to older timestamp {}", key, timestamp); + return ResponseEntity.status(HttpStatus.CONFLICT).body("Older timestamp rejected"); + } else { + NodeConfig.NodeInfo targetNode = findNodeById(targetNodeId); + String url = String.format("http://%s:%d/api/kv/put?key=%s&value=%s×tamp=%d", + targetNode.getHost(), targetNode.getPort(), key, value, timestamp); + logger.info("Forwarding put for key {} to node {} at {}", key, targetNodeId, url); + return restTemplate.postForEntity(url, null, String.class); + } + } + + public ResponseEntity get(String key) { + int targetNodeId = computeShardId(key); + logger.info("Processing get for key {} on node {}", key, targetNodeId); + if (targetNodeId == nodeConfig.getId()) { + KeyValueEntry entry = nodeStorage.get(key); + if (entry != null) { + logger.info("Retrieved key {} from node {}", key, targetNodeId); + return ResponseEntity.ok(entry.getValue()); + } + logger.warn("Key {} not found on node {}", key, targetNodeId); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Key not found"); + } else { + NodeConfig.NodeInfo targetNode = findNodeById(targetNodeId); + String url = String.format("http://%s:%d/api/kv/get?key=%s", + targetNode.getHost(), targetNode.getPort(), key); + logger.info("Forwarding get for key {} to node {} at {}", key, targetNodeId, url); + return restTemplate.getForEntity(url, String.class); + } + } + + public ResponseEntity delete(String key) { + int targetNodeId = computeShardId(key); + logger.info("Processing delete for key {} on node {}", key, targetNodeId); + if (targetNodeId == nodeConfig.getId()) { + boolean deleted = nodeStorage.delete(key); + if (deleted) { + logger.info("Deleted key {} from node {}", key, targetNodeId); + return ResponseEntity.ok("Deleted successfully"); + } + logger.warn("Key {} not found on node {}", key, targetNodeId); + return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Key not found"); + } else { + NodeConfig.NodeInfo targetNode = findNodeById(targetNodeId); + String url = String.format("http://%s:%d/api/kv/delete?key=%s", + targetNode.getHost(), targetNode.getPort(), key); + logger.info("Forwarding delete for key {} to node {} at {}", key, targetNodeId, url); + restTemplate.delete(url); + return ResponseEntity.ok("Deleted successfully"); + } + } + + private int computeShardId(String key) { + return Math.abs(key.hashCode() % nodeConfig.getNodes().size()); + } + + private NodeConfig.NodeInfo findNodeById(int id) { + return nodeConfig.getNodes().stream() + .filter(node -> node.getId() == id) + .findFirst() + .orElseThrow(() -> { + logger.error("Node {} not found", id); + return new RuntimeException("Node not found"); + }); + } +} \ No newline at end of file diff --git a/key_value/src/main/java/com/example/keyvaluestore/storage/NodeStorage.java b/key_value/src/main/java/com/example/keyvaluestore/storage/NodeStorage.java new file mode 100644 index 0000000..731d153 --- /dev/null +++ b/key_value/src/main/java/com/example/keyvaluestore/storage/NodeStorage.java @@ -0,0 +1,28 @@ +package com.example.keyvaluestore.storage; + +import com.example.keyvaluestore.model.KeyValueEntry; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +@Component +public class NodeStorage { + private final Map store = new HashMap<>(); + + public void put(String key, String value, long timestamp) { + store.put(key, new KeyValueEntry(key, value, timestamp)); + } + + public KeyValueEntry get(String key) { + return store.get(key); + } + + public boolean delete(String key) { + return store.remove(key) != null; + } + + public Map getStore() { + return store; + } +} \ No newline at end of file diff --git a/key_value/src/main/resources/application-node1.yml b/key_value/src/main/resources/application-node1.yml new file mode 100644 index 0000000..d19d7b8 --- /dev/null +++ b/key_value/src/main/resources/application-node1.yml @@ -0,0 +1,15 @@ +server: + port: 8080 +node: + id: 0 + port: 8080 + nodes: + - id: 0 + host: localhost + port: 8080 + - id: 1 + host: localhost + port: 8081 + - id: 2 + host: localhost + port: 8082 \ No newline at end of file diff --git a/key_value/src/main/resources/application-node2.yml b/key_value/src/main/resources/application-node2.yml new file mode 100644 index 0000000..566568b --- /dev/null +++ b/key_value/src/main/resources/application-node2.yml @@ -0,0 +1,15 @@ +server: + port: 8081 +node: + id: 1 + port: 8081 + nodes: + - id: 0 + host: localhost + port: 8080 + - id: 1 + host: localhost + port: 8081 + - id: 2 + host: localhost + port: 8082 \ No newline at end of file diff --git a/key_value/src/main/resources/application-node3.yml b/key_value/src/main/resources/application-node3.yml new file mode 100644 index 0000000..a1d348e --- /dev/null +++ b/key_value/src/main/resources/application-node3.yml @@ -0,0 +1,15 @@ +server: + port: 8082 +node: + id: 2 + port: 8082 + nodes: + - id: 0 + host: localhost + port: 8080 + - id: 1 + host: localhost + port: 8081 + - id: 2 + host: localhost + port: 8082 \ No newline at end of file