Skip to content
This repository was archived by the owner on Jun 5, 2025. It is now read-only.

Commit 868f294

Browse files
committed
Fix Unit Tests
1 parent 7969483 commit 868f294

File tree

8 files changed

+908
-605
lines changed

8 files changed

+908
-605
lines changed

cert_gen.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def generate_certificates(cert_dir="certs"):
156156
print("\nOn Windows (PowerShell as Admin):")
157157
print(
158158
'Import-Certificate -FilePath "certs\\server.crt" '
159-
'-CertStoreLocation Cert:\\LocalMachine\\Root'
159+
"-CertStoreLocation Cert:\\LocalMachine\\Root"
160160
)
161161
print("\nOn Linux:")
162162
print("sudo cp certs/server.crt /usr/local/share/ca-certificates/proxy-pilot.crt")

src/codegate/ca/codegate_ca.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,6 @@ def generate_certificates(self) -> Tuple[str, str]:
349349
algorithm=hashes.SHA256(),
350350
)
351351

352-
# os.path.join(Config.get_config().server_key)
353352
with open(
354353
os.path.join(Config.get_config().certs_dir, Config.get_config().server_cert), "wb"
355354
) as f:
@@ -379,7 +378,7 @@ def generate_certificates(self) -> Tuple[str, str]:
379378
print("\nOn Windows (PowerShell as Admin):")
380379
print(
381380
'Import-Certificate -FilePath "certs\\ca.crt" '
382-
'-CertStoreLocation Cert:\\LocalMachine\\Root'
381+
"-CertStoreLocation Cert:\\LocalMachine\\Root"
383382
)
384383
print("\nOn Linux:")
385384
print("sudo cp certs/ca.crt /usr/local/share/ca-certificates/codegate.crt")

src/codegate/cli.py

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Command-line interface for codegate."""
22

33
import asyncio
4+
import signal
45
import sys
56
from pathlib import Path
67
from typing import Dict, Optional
@@ -18,8 +19,6 @@
1819
from codegate.server import init_app
1920
from codegate.storage.utils import restore_storage_backup
2021

21-
logger = structlog.get_logger("codegate")
22-
2322

2423
class UvicornServer:
2524
def __init__(self, config: UvicornConfig, server: Server):
@@ -32,10 +31,16 @@ def __init__(self, config: UvicornConfig, server: Server):
3231
self._startup_complete = asyncio.Event()
3332
self._shutdown_event = asyncio.Event()
3433
self._should_exit = False
34+
self.logger = structlog.get_logger("codegate")
3535

3636
async def serve(self) -> None:
3737
"""Start the uvicorn server and handle shutdown gracefully."""
38-
logger.debug(f"Starting server on {self.host}:{self.port}")
38+
self.logger.debug(f"Starting server on {self.host}:{self.port}")
39+
40+
# Set up signal handlers
41+
loop = asyncio.get_running_loop()
42+
loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.create_task(self.cleanup()))
43+
loop.add_signal_handler(signal.SIGINT, lambda: asyncio.create_task(self.cleanup()))
3944

4045
self.server = Server(config=self.config)
4146
self.server.force_exit = True
@@ -44,40 +49,41 @@ async def serve(self) -> None:
4449
self._startup_complete.set()
4550
await self.server.serve()
4651
except asyncio.CancelledError:
47-
logger.info("Server received cancellation")
52+
self.logger.info("Server received cancellation")
4853
except Exception as e:
49-
logger.exception("Unexpected error occurred during server execution", exc_info=e)
54+
self.logger.exception("Unexpected error occurred during server execution", exc_info=e)
5055
finally:
5156
await self.cleanup()
5257

5358
async def wait_startup_complete(self) -> None:
5459
"""Wait for the server to complete startup."""
55-
logger.debug("Waiting for server startup to complete")
60+
self.logger.debug("Waiting for server startup to complete")
5661
await self._startup_complete.wait()
5762

5863
async def cleanup(self) -> None:
5964
"""Cleanup server resources and ensure graceful shutdown."""
60-
logger.debug("Cleaning up server resources")
65+
self.logger.debug("Cleaning up server resources")
6166
if not self._should_exit:
6267
self._should_exit = True
63-
logger.debug("Initiating server shutdown")
68+
self.logger.debug("Initiating server shutdown")
6469
self._shutdown_event.set()
6570

6671
if hasattr(self.server, "shutdown"):
67-
logger.debug("Shutting down server")
72+
self.logger.debug("Shutting down server")
6873
await self.server.shutdown()
6974

7075
# Ensure all connections are closed
7176
tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task()]
7277
[task.cancel() for task in tasks]
7378

7479
await asyncio.gather(*tasks, return_exceptions=True)
75-
logger.debug("Server shutdown complete")
80+
self.logger.debug("Server shutdown complete")
7681

7782

7883
def validate_port(ctx: click.Context, param: click.Parameter, value: int) -> int:
79-
logger.debug(f"Validating port number: {value}")
8084
"""Validate the port number is in valid range."""
85+
logger = structlog.get_logger("codegate")
86+
logger.debug(f"Validating port number: {value}")
8187
if value is not None and not (1 <= value <= 65535):
8288
raise click.BadParameter("Port must be between 1 and 65535")
8389
return value
@@ -286,10 +292,14 @@ def serve(
286292
db_path=db_path,
287293
)
288294

295+
# Set up logging first
296+
setup_logging(cfg.log_level, cfg.log_format)
297+
logger = structlog.get_logger("codegate")
298+
289299
init_db_sync(cfg.db_path)
290300

291301
# Check certificates and create CA if necessary
292-
logger.info("Checking certificates and creating CA our created")
302+
logger.info("Checking certificates and creating CA if needed")
293303
ca = CertificateAuthority.get_instance()
294304
ca.ensure_certificates_exist()
295305

@@ -311,16 +321,15 @@ def serve(
311321
click.echo(f"Configuration error: {e}", err=True)
312322
sys.exit(1)
313323
except Exception as e:
314-
if logger:
315-
logger.exception("Unexpected error occurred")
324+
logger = structlog.get_logger("codegate")
325+
logger.exception("Unexpected error occurred")
316326
click.echo(f"Error: {e}", err=True)
317327
sys.exit(1)
318328

319329

320330
async def run_servers(cfg: Config, app) -> None:
321331
"""Run the codegate server."""
322332
try:
323-
setup_logging(cfg.log_level, cfg.log_format)
324333
logger = structlog.get_logger("codegate")
325334
logger.info(
326335
"Starting server",

src/codegate/pipeline/secrets/secrets.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ def _find_complete_redaction(self, text: str) -> tuple[Optional[re.Match[str]],
239239

240240
# Get the first complete match
241241
match = matches[0]
242-
return match, text[match.end():]
242+
return match, text[match.end() :]
243243

244244
async def process_chunk(
245245
self,

0 commit comments

Comments
 (0)