From 8e34f3f309a1c0e59140d87c2de9370ed006c87f Mon Sep 17 00:00:00 2001 From: Arnaud Date: Thu, 25 Sep 2025 09:06:25 +0200 Subject: [PATCH] Provide better logs (hopefully) --- library/codex_context.nim | 38 +++++++++++++------ .../codex_thread_request.nim | 2 +- .../requests/node_debug_request.nim | 14 +++---- .../requests/node_info_request.nim | 8 ++-- .../requests/node_lifecycle_request.nim | 23 +++++------ .../requests/node_p2p_request.nim | 16 ++++---- library/libcodex.nim | 6 +-- 7 files changed, 61 insertions(+), 46 deletions(-) diff --git a/library/codex_context.nim b/library/codex_context.nim index e983cd52..50670c4e 100644 --- a/library/codex_context.nim +++ b/library/codex_context.nim @@ -95,23 +95,28 @@ proc sendRequestToCodexThread*( let sentOk = ctx.reqChannel.trySend(req) if not sentOk: deallocShared(req) - return err("Couldn't send a request to the codex thread: " & $req[]) + return err("Failed to send request to the codex thread: " & $req[]) # Notify the Codex thread that a request is available let fireSyncRes = ctx.reqSignal.fireSync() if fireSyncRes.isErr(): deallocShared(req) - return err("failed fireSync: " & $fireSyncRes.error) + return err( + "Failed to send request to the codex thread: unable to fireSync: " & + $fireSyncRes.error + ) if fireSyncRes.get() == false: deallocShared(req) - return err("Couldn't fireSync in time") + return err("Failed to send request to the codex thread: fireSync timed out.") # Wait until the Codex Thread properly received the request let res = ctx.reqReceivedSignal.waitSync(timeout) if res.isErr(): deallocShared(req) - return err("Couldn't receive reqReceivedSignal signal") + return err( + "Failed to send request to the codex thread: unable to receive reqReceivedSignal signal." + ) ## Notice that in case of "ok", the deallocShared(req) is performed by the Codex Thread in the ## process proc. See the 'codex_thread_request.nim' module for more details. @@ -125,7 +130,7 @@ proc runCodex(ctx: ptr CodexContext) {.async: (raises: []).} = # Wait until a request is available await ctx.reqSignal.wait() except Exception as e: - error "codex thread error while waiting for reqSignal", error = e.msg + error "Failed to run codex thread while waiting for reqSignal.", error = e.msg continue # If codex_destroy was called, exit the loop @@ -137,7 +142,7 @@ proc runCodex(ctx: ptr CodexContext) {.async: (raises: []).} = # Pop a request from the channel let recvOk = ctx.reqChannel.tryRecv(request) if not recvOk: - error "codex thread could not receive a request" + error "Failed to run codex: unable to receive request in codex thread." continue # yield immediately to the event loop @@ -152,7 +157,8 @@ proc runCodex(ctx: ptr CodexContext) {.async: (raises: []).} = # Notify the main thread that we picked up the request let fireRes = ctx.reqReceivedSignal.fireSync() if fireRes.isErr(): - error "could not fireSync back to requester thread", error = fireRes.error + error "Failed to run codex: unable to fire back to requester thread.", + error = fireRes.error proc run(ctx: ptr CodexContext) {.thread.} = waitFor runCodex(ctx) @@ -167,12 +173,15 @@ proc createCodexContext*(): Result[ptr CodexContext, string] = # This signal is used by the main side to wake the Codex thread # when a new request is enqueued. ctx.reqSignal = ThreadSignalPtr.new().valueOr: - return err("couldn't create reqSignal ThreadSignalPtr") + return + err("Failed to create a context: unable to create reqSignal ThreadSignalPtr.") # Used to let the caller know that the Codex thread has # acknowledged / picked up a request (like a handshake). ctx.reqReceivedSignal = ThreadSignalPtr.new().valueOr: - return err("couldn't create reqReceivedSignal ThreadSignalPtr") + return err( + "Failed to create codex context: unable to create reqReceivedSignal ThreadSignalPtr." + ) # Protects shared state inside CodexContext ctx.lock.initLock() @@ -184,7 +193,10 @@ proc createCodexContext*(): Result[ptr CodexContext, string] = createThread(ctx.thread, run, ctx) except ValueError, ResourceExhaustedError: freeShared(ctx) - return err("failed to create the Codex thread: " & getCurrentExceptionMsg()) + return err( + "Failed to create codex context: unable to create thread: " & + getCurrentExceptionMsg() + ) return ok(ctx) @@ -194,10 +206,12 @@ proc destroyCodexContext*(ctx: ptr CodexContext): Result[void, string] = # Wake the worker up if it's waiting let signaledOnTime = ctx.reqSignal.fireSync().valueOr: - return err("error in destroyCodexContext: " & $error) + return err("Failed to destroy codex context: " & $error) if not signaledOnTime: - return err("failed to signal reqSignal on time in destroyCodexContext") + return err( + "Failed to destroy codex context: unable to get signal reqSignal on time in destroyCodexContext." + ) # Wait for the thread to finish joinThread(ctx.thread) diff --git a/library/codex_thread_requests/codex_thread_request.nim b/library/codex_thread_requests/codex_thread_request.nim index b0d789ab..1701a669 100644 --- a/library/codex_thread_requests/codex_thread_request.nim +++ b/library/codex_thread_requests/codex_thread_request.nim @@ -64,7 +64,7 @@ proc handleRes[T: string | void]( if res.isErr(): foreignThreadGc: - let msg = "libcodex error: handleRes fireSyncRes error: " & $res.error + let msg = $res.error request[].callback( RET_ERR, unsafeAddr msg[0], cast[csize_t](len(msg)), request[].userData ) diff --git a/library/codex_thread_requests/requests/node_debug_request.nim b/library/codex_thread_requests/requests/node_debug_request.nim index 2f492505..348c0d76 100644 --- a/library/codex_thread_requests/requests/node_debug_request.nim +++ b/library/codex_thread_requests/requests/node_debug_request.nim @@ -64,22 +64,22 @@ proc getPeer( let node = codex[].node let res = PeerId.init($peerId) if res.isErr: - return err("Invalid peer ID " & $peerId & ": " & $res.error()) + return err("Failed to get peer: invalid peer ID " & $peerId & ": " & $res.error()) let id = res.get() try: let peerRecord = await node.findPeer(id) if peerRecord.isNone: - return err("Peer not found") + return err("Failed to get peer: peer not found") return ok($ %RestPeerRecord.init(peerRecord.get())) except CancelledError: - return err("Operation cancelled") + return err("Failed to get peer: operation cancelled") except CatchableError as e: - return err("Error when finding peer: " & e.msg) + return err("Failed to get peer: " & e.msg) else: - return err("Peer debug API is disabled") + return err("Failed to get peer: peer debug API is disabled") proc process*( self: ptr NodeDebugRequest, codex: ptr CodexServer @@ -91,13 +91,13 @@ proc process*( of NodeDebugMsgType.DEBUG: let res = (await getDebug(codex)) if res.isErr: - error "DEBUG failed", error = res.error + error "Failed to get DEBUG.", error = res.error return err($res.error) return res of NodeDebugMsgType.PEER: let res = (await getPeer(codex, self.peerId)) if res.isErr: - error "PEER failed", error = res.error + error "Failed to get PEER.", error = res.error return err($res.error) return res diff --git a/library/codex_thread_requests/requests/node_info_request.nim b/library/codex_thread_requests/requests/node_info_request.nim index 167a3094..18e478cb 100644 --- a/library/codex_thread_requests/requests/node_info_request.nim +++ b/library/codex_thread_requests/requests/node_info_request.nim @@ -40,7 +40,7 @@ proc getSpr( ): Future[Result[string, string]] {.async: (raises: []).} = let spr = codex[].node.discovery.dhtRecord if spr.isNone: - return err("No SPR record found") + return err("Failed to get SPR: no SPR record found.") return ok(spr.get.toURI) @@ -59,19 +59,19 @@ proc process*( of REPO: let res = (await getRepo(codex)) if res.isErr: - error "REPO failed", error = res.error + error "Failed to get REPO.", error = res.error return err($res.error) return res of SPR: let res = (await getSpr(codex)) if res.isErr: - error "SPR failed", error = res.error + error "Failed to get SPR.", error = res.error return err($res.error) return res of PEERID: let res = (await getPeerId(codex)) if res.isErr: - error "PEERID failed", error = res.error + error "Failed to get PEERID.", error = res.error return err($res.error) return res diff --git a/library/codex_thread_requests/requests/node_lifecycle_request.nim b/library/codex_thread_requests/requests/node_lifecycle_request.nim index c6d06f48..53fa9ec9 100644 --- a/library/codex_thread_requests/requests/node_lifecycle_request.nim +++ b/library/codex_thread_requests/requests/node_lifecycle_request.nim @@ -112,7 +112,7 @@ proc createCodex( , ) except ConfigurationError as e: - return err("Failed to load configuration: " & e.msg) + return err("Failed to create codex: unable to load configuration: " & e.msg) conf.setupLogging() conf.setupMetrics() @@ -121,30 +121,31 @@ proc createCodex( # We are unable to access/create data folder or data folder's # permissions are insecure. return err( - "Unable to access/create data folder or data folder's permissions are insecure." + "Failed to create codex: unable to access/create data folder or data folder's permissions are insecure." ) if not (checkAndCreateDataDir((conf.dataDir / "repo"))): # We are unable to access/create data folder or data folder's # permissions are insecure. return err( - "Unable to access/create data folder or data folder's permissions are insecure." + "Failed to create codex: unable to access/create data folder or data folder's permissions are insecure." ) - debug "Repo dir initialized", dir = conf.dataDir / "repo" - let keyPath = if isAbsolute(conf.netPrivKeyFile): conf.netPrivKeyFile else: conf.dataDir / conf.netPrivKeyFile - let privateKey = setupKey(keyPath).expect("Should setup private key!") + let privateKey = setupKey(keyPath) + if privateKey.isErr: + return err("Failed to create codex: unable to get the private key.") + let pk = privateKey.get() let server = try: - CodexServer.new(conf, privateKey) + CodexServer.new(conf, pk) except Exception as exc: - return err("Failed to start Codex: " & exc.msg) + return err("Failed to create codex: " & exc.msg) return ok(server) @@ -161,19 +162,19 @@ proc process*( self.configJson # , self.appCallbacks ) ).valueOr: - error "CREATE_NODE failed", error = error + error "Failed to CREATE_NODE.", error = error return err($error) of START_NODE: try: await codex[].start() except Exception as e: - error "START_NODE failed", error = e.msg + error "Failed to START_NODE.", error = e.msg return err(e.msg) of STOP_NODE: try: await codex[].stop() except Exception as e: - error "STOP_NODE failed", error = e.msg + error "Failed to STOP_NODE.", error = e.msg return err(e.msg) return ok("") diff --git a/library/codex_thread_requests/requests/node_p2p_request.nim b/library/codex_thread_requests/requests/node_p2p_request.nim index 46790070..96f70c15 100644 --- a/library/codex_thread_requests/requests/node_p2p_request.nim +++ b/library/codex_thread_requests/requests/node_p2p_request.nim @@ -45,7 +45,7 @@ proc connect( let node = codex[].node let res = PeerId.init($peerId) if res.isErr: - return err("Invalid peer ID: " & $res.error()) + return err("Failed to connect to peer: invalid peer ID: " & $res.error()) let id = res.get() @@ -57,26 +57,26 @@ proc connect( if res.isOk: addrs.add(res[]) else: - return err("Invalid address: " & $addrStr) + return err("Failed to connect to peer: invalid address: " & $addrStr) addrs else: try: let peerRecord = await node.findPeer(id) if peerRecord.isNone: - return err("Peer not found") + return err("Failed to connect to peer: peer not found.") peerRecord.get().addresses.mapIt(it.address) except CancelledError as e: - return err("Operation cancelled") + return err("Failed to connect to peer: operation cancelled.") except CatchableError as e: - return err("Error finding peer: " & $e.msg) + return err("Failed to connect to peer: " & $e.msg) try: await node.connect(id, addresses) except CancelledError as e: - return err("Operation cancelled") + return err("Failed to connect to peer: operation cancelled.") except CatchableError as e: - return err("Connection failed: " & $e.msg) + return err("Failed to connect to peer: " & $e.msg) return ok("") @@ -90,7 +90,7 @@ proc process*( of NodeP2PMsgType.CONNECT: let res = (await connect(codex, self.peerId)) if res.isErr: - error "CONNECT failed", error = res.error + error "Failed to CONNECT.", error = res.error return err($res.error) return res diff --git a/library/libcodex.nim b/library/libcodex.nim index b537707e..05bfc3e9 100644 --- a/library/libcodex.nim +++ b/library/libcodex.nim @@ -85,11 +85,11 @@ proc codex_new( initializeLibrary() if isNil(callback): - error "Missing callback in codex_new" + error "Failed to create codex instance: the callback is missing." return nil var ctx = codex_context.createCodexContext().valueOr: - let msg = "Error in createCodexContext: " & $error + let msg = $error callback(RET_ERR, unsafeAddr msg[0], cast[csize_t](len(msg)), userData) return nil @@ -101,7 +101,7 @@ proc codex_new( codex_context.sendRequestToCodexThread( ctx, RequestType.LIFECYCLE, reqContent, callback, userData ).isOkOr: - let msg = "libcodex error: " & $error + let msg = $error callback(RET_ERR, unsafeAddr msg[0], cast[csize_t](len(msg)), userData) return nil