-
Notifications
You must be signed in to change notification settings - Fork 1
refactor: improve SQL implementation and protocol handling #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| (ns chrondb.api.sql.connection.handler | ||
| "Functions for handling SQL client connections" | ||
| (:require [chrondb.util.logging :as log] | ||
| [chrondb.api.sql.protocol.core :as protocol] | ||
| [chrondb.api.sql.protocol.messages.reader :as reader] | ||
| [chrondb.api.sql.execution.query :as query]) | ||
| (:import [java.io InputStream OutputStream])) | ||
|
|
||
| (defn handle-query-message | ||
| "Handles a query message" | ||
| [storage index protocol-impl ^InputStream in ^OutputStream out] | ||
| (let [query-data (reader/read-query-message in)] | ||
| (if (:error query-data) | ||
| (do | ||
| (log/log-error (str "Error reading query: " (:error query-data))) | ||
| (-> protocol-impl | ||
| (.write-query-result out {:command "ERROR" :rows [] :data [] :columns []}))) | ||
|
|
||
| (let [query-text (:query query-data)] | ||
| (log/log-info (str "Executing SQL query: " query-text)) | ||
|
|
||
| (try | ||
| ;; Execute query and get results | ||
| (query/handle-query storage index out query-text) | ||
|
|
||
| ;; Retornamos true porque handle-query já envia as respostas diretamente para o output stream | ||
| true | ||
|
|
||
| (catch Exception e | ||
| (log/log-error (str "Error executing query: " (.getMessage e))) | ||
| (-> protocol-impl | ||
| (.write-query-result out {:command "ERROR" | ||
| :rows [] | ||
| :error (.getMessage e)})))))))) | ||
|
|
||
| (defn handle-terminate-message | ||
| "Handles a terminate message" | ||
| [] | ||
| (log/log-info "Client requested termination") | ||
| {:terminate true}) | ||
|
|
||
| (defn handle-message | ||
| "Handles a client message based on its type" | ||
| [storage index protocol-impl ^InputStream in ^OutputStream out message] | ||
| (let [type (:type message)] | ||
| (try | ||
| (case type | ||
| ;; 'Q' = Simple Query | ||
| 81 (handle-query-message storage index protocol-impl in out) | ||
| ;; 'X' = Terminate | ||
| 88 (handle-terminate-message) | ||
| ;; Unsupported message type | ||
| (do | ||
| (log/log-info (str "Unsupported command: " (char type))) | ||
| ;; Discard message content | ||
| (let [length (reader/read-int in) | ||
| content-length (- length 4) | ||
| discard-buffer (byte-array content-length)] | ||
| (.read in discard-buffer)) | ||
| ;; Send error response | ||
| (-> protocol-impl | ||
| (.write-query-result out | ||
| {:command "ERROR" | ||
| :rows [] | ||
| :error (str "Unsupported command: " (char type))})))) | ||
| (catch Exception e | ||
| (log/log-error (str "Error processing message: " (.getMessage e))) | ||
| (-> protocol-impl | ||
| (.write-query-result out | ||
| {:command "ERROR" | ||
| :rows [] | ||
| :error (str "Internal server error: " (.getMessage e))})))))) | ||
|
|
||
| (defn handle-client-connection | ||
| "Handles a new client connection" | ||
| [storage index ^InputStream in ^OutputStream out] | ||
| (try | ||
| (let [protocol-impl (protocol/create-protocol)] | ||
| ;; Handle startup sequence | ||
| (doseq [action (-> protocol-impl (.handle-startup in out))] | ||
| (action)) | ||
|
|
||
| ;; Process client messages until terminated or EOF | ||
| (loop [] | ||
| (let [message (-> protocol-impl (.read-message in))] | ||
| (if message | ||
| (let [result (handle-message storage index protocol-impl in out message)] | ||
| (if-not (:terminate result) | ||
| (recur) | ||
| (log/log-info "Client session terminated normally"))) | ||
| (log/log-info "Client disconnected"))))) | ||
|
|
||
| (catch Exception e | ||
| (log/log-error (str "Error in client connection handler: " (.getMessage e)))))) | ||
|
|
||
| (defn create-connection-handler | ||
| "Creates a handler function for new client connections" | ||
| [storage index] | ||
| (fn [client-socket] | ||
| (try | ||
| (with-open [in (.getInputStream client-socket) | ||
| out (.getOutputStream client-socket)] | ||
| (handle-client-connection storage index in out)) | ||
| (catch Exception e | ||
| (log/log-error (str "Error handling client socket: " (.getMessage e))))))) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,40 +1,82 @@ | ||
| (ns chrondb.api.sql.connection.server | ||
| "SQL server management" | ||
| (:require [clojure.core.async :as async] | ||
| [chrondb.api.sql.connection.client :as client] | ||
| [chrondb.util.logging :as log]) | ||
| (:import [java.net ServerSocket])) | ||
| "Servidor de conexão SQL para o ChronDB" | ||
| (:require [chrondb.util.logging :as log] | ||
| [chrondb.api.sql.connection.handler :as handler]) | ||
| (:import [java.net ServerSocket InetAddress] | ||
| [java.util.concurrent Executors])) | ||
|
|
||
| (defn start-sql-server | ||
| "Starts a SQL server for ChronDB. | ||
| Parameters: | ||
| - storage: The storage implementation | ||
| - index: The index implementation | ||
| - port: The port number to listen on | ||
| Returns: The server socket" | ||
| [storage index port] | ||
| (let [server-socket (ServerSocket. port)] | ||
| (log/log-info (str "Starting SQL server on port " port)) | ||
| (async/go | ||
| (defn- create-server-socket | ||
| "Cria um socket de servidor na porta especificada" | ||
| [port] | ||
| (let [addr (InetAddress/getByName "localhost") | ||
| server-socket (ServerSocket. port 50 addr)] | ||
| server-socket)) | ||
|
|
||
| (defn- accept-clients | ||
| "Aceita conexões de clientes e processa usando o thread pool" | ||
| [^ServerSocket server-socket thread-pool client-handler] | ||
| (loop [] | ||
| (when-not (.isClosed server-socket) | ||
| (try | ||
| (while (not (.isClosed server-socket)) | ||
| (try | ||
| (let [client-socket (.accept server-socket)] | ||
| (async/go | ||
| (client/handle-client storage index client-socket))) | ||
| (catch Exception e | ||
| (when-not (.isClosed server-socket) | ||
| (log/log-error (str "Error accepting SQL connection: " (.getMessage e))))))) | ||
| (let [socket (.accept server-socket)] | ||
| ;; Submit the client handling task to the thread pool | ||
| (.submit thread-pool ^Runnable #(client-handler socket))) | ||
| (catch java.net.SocketException e | ||
| (if (.isClosed server-socket) | ||
| (log/log-info "Server socket closed.") | ||
| (log/log-error (str "Socket error: " (.getMessage e))))) | ||
| (catch Exception e | ||
| (log/log-error (str "Error in SQL server: " (.getMessage e)))))) | ||
| server-socket)) | ||
| (log/log-error (str "Error accepting client: " (.getMessage e))))) | ||
| ;; Continue accepting connections (fora do try) | ||
| (recur)))) | ||
|
|
||
| (defn start-sql-server | ||
| "Inicia um servidor SQL" | ||
| [storage index port] | ||
| (let [server-socket (create-server-socket port) | ||
| actual-port (.getLocalPort server-socket) | ||
| thread-pool (Executors/newCachedThreadPool) | ||
| client-handler (handler/create-connection-handler storage index)] | ||
|
|
||
| (log/log-info (str "SQL server started on port " actual-port)) | ||
|
|
||
| ;; Start accepting connections in a separate thread | ||
| (let [accept-thread (Thread. #(accept-clients server-socket thread-pool client-handler))] | ||
| (.start accept-thread) | ||
|
|
||
| ;; Retornar o objeto ServerSocket para manter compatibilidade com testes | ||
| server-socket))) | ||
|
|
||
| (defn stop-sql-server | ||
| "Stops the SQL server. | ||
| Parameters: | ||
| - server-socket: The server socket to close | ||
| Returns: nil" | ||
| [^ServerSocket server-socket] | ||
| (log/log-info "Stopping SQL server") | ||
| (when (and server-socket (not (.isClosed server-socket))) | ||
| (.close server-socket))) | ||
| "Para o servidor SQL" | ||
| [server] | ||
| (when server | ||
| (log/log-info "Stopping SQL server...") | ||
|
|
||
| ;; Se o objeto for um servidor-socket (compatibilidade com testes antigos) | ||
| (if (instance? java.net.ServerSocket server) | ||
| (do | ||
| (.close server) | ||
| (log/log-info "Server socket closed.")) | ||
|
|
||
| ;; Se for um mapa com informações do servidor (nova implementação) | ||
| (let [{:keys [server-socket thread-pool]} server] | ||
| ;; Close the server socket to stop accepting new connections | ||
| (when server-socket | ||
| (.close server-socket) | ||
| (log/log-info "Server socket closed.")) | ||
|
|
||
| ;; Shutdown the thread pool | ||
| (when thread-pool | ||
| (.shutdown thread-pool) | ||
| ;; Wait a bit for tasks to complete | ||
| (try | ||
| (.awaitTermination thread-pool 5 java.util.concurrent.TimeUnit/SECONDS) | ||
| (catch InterruptedException _ | ||
| (log/log-warn "Interrupted while waiting for thread pool shutdown"))) | ||
|
|
||
| ;; Force shutdown if tasks are still running | ||
| (when-not (.isTerminated thread-pool) | ||
| (.shutdownNow thread-pool))))) | ||
|
|
||
| (log/log-info "SQL server stopped"))) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Concurrent client acceptance strategy with potential unbounded thread usage.
The code spawns a new thread per connection using
newCachedThreadPool, which can grow without limit. This may risk resource exhaustion under heavy load. Consider using a bounded thread pool or a more advanced concurrency approach to avoid potential DDoS scenarios.