astreum 0.2.47__py3-none-any.whl → 0.2.49__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of astreum might be problematic. Click here for more details.

astreum/_node.py CHANGED
@@ -3,24 +3,27 @@ from typing import Dict, Optional
3
3
  import uuid
4
4
  import threading
5
5
 
6
- from ._storage.atom import Atom
7
- from ._lispeum import Env, Expr, Meter, low_eval, parse, tokenize, ParseError
8
-
9
- __all__ = [
10
- "Node",
11
- "Env",
12
- "Expr",
13
- "Meter",
14
- "parse",
15
- "tokenize",
16
- ]
17
-
18
- def bytes_touched(*vals: bytes) -> int:
6
+ from ._storage.atom import Atom
7
+ from ._lispeum import Env, Expr, Meter, low_eval, parse, tokenize, ParseError
8
+ from .utils.logging import logging_setup
9
+
10
+ __all__ = [
11
+ "Node",
12
+ "Env",
13
+ "Expr",
14
+ "Meter",
15
+ "parse",
16
+ "tokenize",
17
+ ]
18
+
19
+ def bytes_touched(*vals: bytes) -> int:
19
20
  """For metering: how many bytes were manipulated (max of operands)."""
20
21
  return max((len(v) for v in vals), default=1)
21
22
 
22
23
  class Node:
23
24
  def __init__(self, config: dict):
25
+ self.logger = logging_setup(config)
26
+ self.logger.info("Starting Astreum Node")
24
27
  # Storage Setup
25
28
  self.in_memory_storage: Dict[bytes, Atom] = {}
26
29
  self.in_memory_storage_lock = threading.RLock()
@@ -0,0 +1,219 @@
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import inspect
5
+ import gzip
6
+ import json
7
+ import logging
8
+ import logging.handlers
9
+ import os
10
+ import pathlib
11
+ import platform
12
+ import queue
13
+ import shutil
14
+ from datetime import datetime, timezone
15
+ from typing import Any, Dict, Optional
16
+
17
+ from blake3 import blake3
18
+
19
+ # Fixed identity for all loggers in this library
20
+ _ORG_NAME = "Astreum"
21
+ _PRODUCT_NAME = "lib-py"
22
+
23
+
24
+ def _safe_path(path_str: str) -> Optional[pathlib.Path]:
25
+ try:
26
+ return pathlib.Path(path_str).resolve()
27
+ except Exception:
28
+ try:
29
+ return pathlib.Path(path_str).absolute()
30
+ except Exception:
31
+ return None
32
+
33
+
34
+ def _hash_path(path: pathlib.Path) -> str:
35
+ try:
36
+ data = str(path).encode("utf-8", errors="ignore")
37
+ except Exception:
38
+ data = repr(path).encode("utf-8", errors="ignore")
39
+ return blake3(data).hexdigest()
40
+
41
+
42
+ def _find_caller_path() -> pathlib.Path:
43
+ stack = inspect.stack()
44
+ candidates: list[pathlib.Path] = []
45
+ for frame_info in stack[2:]:
46
+ filename = frame_info.filename
47
+ if not filename:
48
+ continue
49
+ path = _safe_path(filename)
50
+ if path is None:
51
+ continue
52
+ candidates.append(path)
53
+ if "astreum" not in path.parts:
54
+ return path
55
+
56
+ if candidates:
57
+ return candidates[0]
58
+ return pathlib.Path.cwd()
59
+
60
+
61
+ def _derive_instance_id() -> str:
62
+ return _hash_path(_find_caller_path())[:16]
63
+
64
+
65
+ def _log_root(org: str, product: str, instance_id: str) -> pathlib.Path:
66
+ """Resolve the base directory for logs using platform defaults."""
67
+ if platform.system() == "Windows":
68
+ base = os.getenv("LOCALAPPDATA") or str(pathlib.Path.home())
69
+ return pathlib.Path(base) / org / product / "logs" / instance_id
70
+
71
+ xdg_state = os.getenv("XDG_STATE_HOME")
72
+ base_path = pathlib.Path(xdg_state) if xdg_state else pathlib.Path.home() / ".local" / "state"
73
+ return base_path / org / product / "logs" / instance_id
74
+
75
+
76
+ class JSONFormatter(logging.Formatter):
77
+ """Log record formatter that emits JSON objects per line."""
78
+
79
+ def format(self, record: logging.LogRecord) -> str: # type: ignore[override]
80
+ payload: Dict[str, Any] = {
81
+ "ts": datetime.fromtimestamp(record.created, tz=timezone.utc).isoformat(),
82
+ "level": record.levelname,
83
+ "logger": record.name,
84
+ "msg": record.getMessage(),
85
+ "pid": record.process,
86
+ "thread": record.threadName,
87
+ "module": record.module,
88
+ "func": record.funcName,
89
+ "instance_id": getattr(record, "instance_id", None),
90
+ }
91
+
92
+ for key, value in record.__dict__.items():
93
+ if key in payload or key.startswith(("_", "msecs", "relativeCreated")):
94
+ continue
95
+ try:
96
+ json.dumps(value)
97
+ except Exception:
98
+ continue
99
+ payload[key] = value
100
+
101
+ return json.dumps(payload, ensure_ascii=False)
102
+
103
+
104
+ def _gzip_rotator(src: str, dst: str) -> None:
105
+ """Rotate the log file by gzipping it and removing the original."""
106
+ with open(src, "rb") as source, gzip.open(f"{dst}.gz", "wb") as target:
107
+ shutil.copyfileobj(source, target)
108
+ os.remove(src)
109
+
110
+
111
+ def _namer(default_name: str) -> str:
112
+ """Custom name for rotated logs: node-YYYY-MM-DD.log."""
113
+ path = pathlib.Path(default_name)
114
+ parent = path.parent
115
+ name = path.name
116
+ fragments = name.split(".log.")
117
+ if len(fragments) != 2:
118
+ return default_name
119
+ stem, date_part = fragments
120
+ return str(parent / f"{stem}-{date_part}.log")
121
+
122
+
123
+ def _human_line(record: logging.LogRecord) -> str:
124
+ """Format a record as a concise human-readable line."""
125
+ dt = datetime.fromtimestamp(record.created, tz=timezone.utc)
126
+ stamp = f"{dt:%Y-%m-%d}-{dt:%S}-{dt:%M}"
127
+ return f"[{stamp}] [{record.levelname.lower()}] {record.getMessage()}"
128
+
129
+
130
+ class HumanFormatter(logging.Formatter):
131
+ """Simple formatter for optional verbose console output."""
132
+
133
+ def format(self, record: logging.LogRecord) -> str: # type: ignore[override]
134
+ return _human_line(record)
135
+
136
+
137
+ def _shutdown_listener(listener: logging.handlers.QueueListener, handlers: list[logging.Handler]) -> None:
138
+ """Stop the queue listener and close handlers on interpreter exit."""
139
+ try:
140
+ listener.stop()
141
+ except Exception:
142
+ pass
143
+ finally:
144
+ for handler in handlers:
145
+ try:
146
+ handler.close()
147
+ except Exception:
148
+ pass
149
+
150
+
151
+ def logging_setup(config: dict) -> logging.LoggerAdapter:
152
+ """Configure logging according to the runtime config and return an adapter."""
153
+ if config is None:
154
+ config = {}
155
+ elif not isinstance(config, dict):
156
+ config = dict(config)
157
+
158
+ org = _ORG_NAME
159
+ product = _PRODUCT_NAME
160
+ instance_id = _derive_instance_id()
161
+
162
+ retention_value = config.get("retention_days")
163
+ retention_days = int(retention_value) if retention_value is not None else 90
164
+
165
+ verbose = bool(config.get("verbose", False))
166
+
167
+ log_dir = _log_root(org, product, instance_id)
168
+ log_dir.mkdir(parents=True, exist_ok=True)
169
+
170
+ base_file = log_dir / "node.log"
171
+ file_handler = logging.handlers.TimedRotatingFileHandler(
172
+ filename=str(base_file),
173
+ when="midnight",
174
+ interval=1,
175
+ backupCount=max(retention_days, 0),
176
+ utc=True,
177
+ encoding="utf-8",
178
+ delay=True,
179
+ )
180
+ file_handler.setFormatter(JSONFormatter())
181
+ file_handler.rotator = _gzip_rotator
182
+ file_handler.namer = _namer
183
+
184
+ handler_list: list[logging.Handler] = [file_handler]
185
+
186
+ if verbose:
187
+ console_handler = logging.StreamHandler()
188
+ console_handler.setLevel(logging.INFO)
189
+ console_handler.setFormatter(HumanFormatter())
190
+ handler_list.append(console_handler)
191
+
192
+ log_queue: queue.Queue[logging.LogRecord] = queue.Queue(-1)
193
+ queue_handler = logging.handlers.QueueHandler(log_queue)
194
+
195
+ base_logger = logging.getLogger(f"{product}.{instance_id}")
196
+ base_logger.setLevel(logging.INFO)
197
+ base_logger.handlers.clear()
198
+ base_logger.propagate = False
199
+ base_logger.addHandler(queue_handler)
200
+
201
+ listener = logging.handlers.QueueListener(
202
+ log_queue, *handler_list, respect_handler_level=True
203
+ )
204
+ listener.daemon = True
205
+ listener.start()
206
+ atexit.register(_shutdown_listener, listener, handler_list)
207
+
208
+ adapter = logging.LoggerAdapter(base_logger, {"instance_id": instance_id})
209
+ setattr(adapter, "_queue_listener", listener)
210
+ setattr(adapter, "_handlers", handler_list)
211
+
212
+ return adapter
213
+
214
+
215
+ __all__ = [
216
+ "HumanFormatter",
217
+ "JSONFormatter",
218
+ "logging_setup",
219
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: astreum
3
- Version: 0.2.47
3
+ Version: 0.2.49
4
4
  Summary: Python library to interact with the Astreum blockchain and its Lispeum virtual machine.
5
5
  Author-email: "Roy R. O. Okello" <roy@stelar.xyz>
6
6
  Project-URL: Homepage, https://github.com/astreum/lib
@@ -35,6 +35,8 @@ When initializing an `astreum.Node`, pass a dictionary with any of the options b
35
35
  | `validation_secret_key` | hex string | `None` | X25519 private key that lets the node participate in the validation route. Leave unset for a non‑validator node. |
36
36
  | `storage_path` | string | `None` | Directory where objects are persisted. If *None*, the node uses an in‑memory store. |
37
37
  | `storage_get_relay_timeout` | float | `5` | Seconds to wait for an object requested from peers before timing‑out. |
38
+ | `logging_retention` | int | `90` | Number of days to keep rotated log files (daily gzip). |
39
+ | `verbose` | bool | `False` | When **True**, also mirror JSON logs to stdout with a human-readable format. |
38
40
 
39
41
  ### Networking
40
42
 
@@ -136,6 +138,17 @@ except ParseError as e:
136
138
 
137
139
  ---
138
140
 
141
+
142
+ ## Logging
143
+
144
+ Every `Node` instance wires up structured logging automatically:
145
+
146
+ - Logs land in per-instance files named `node.log` under `%LOCALAPPDATA%\Astreum\lib-py\logs/<instance_id>` on Windows and `$XDG_STATE_HOME` (or `~/.local/state`)/`Astreum/lib-py/logs/<instance_id>` on other platforms. The `<instance_id>` is the first 16 hex characters of a BLAKE3 hash of the caller's file path, so running the node from different entry points keeps their logs isolated.
147
+ - Files rotate at midnight UTC with gzip compression (`node-YYYY-MM-DD.log.gz`) and retain 90 days by default. Override via `config["logging_retention"]`.
148
+ - Each event is a single JSON line containing timestamp, level, logger, message, process/thread info, module/function, and the derived `instance_id`.
149
+ - Set `config["verbose"] = True` to mirror logs to stdout in a human-friendly format like `[2025-04-13-42-59] [info] Starting Astreum Node`.
150
+ - The very first entry emitted is the banner `Starting Astreum Node`, signalling that the logging pipeline is live before other subsystems spin up.
151
+
139
152
  ## Testing
140
153
 
141
154
  ```bash
@@ -1,5 +1,5 @@
1
1
  astreum/__init__.py,sha256=9tzA27B_eG5wRF1SAWJIV7xTmCcR1QFc123b_cvFOa4,345
2
- astreum/_node.py,sha256=f_4t0U0YyZhIrkFy6GNzWp_flMXDH8ES5GywUe56H7Q,3891
2
+ astreum/_node.py,sha256=ZUeBsvF9C8c8Cnjbpwpsnd-ItdQrgnqRkYlX99-JaZs,4040
3
3
  astreum/format.py,sha256=X4tG5GGPweNCE54bHYkLFiuLTbmpy5upO_s1Cef-MGA,2711
4
4
  astreum/node.py,sha256=MmlK3jaANTMB3ZAxR8IaSc82OS9meJmVawYIVURADbg,39689
5
5
  astreum/_communication/__init__.py,sha256=XJui0yOcfAur4HKt-8sSRlwB-MSU1rchkuOAY-nKDOE,207
@@ -48,8 +48,9 @@ astreum/storage/object.py,sha256=knFlvw_tpcC4twSu1DGNpHX31wlANN8E5dgEqIfU--Q,204
48
48
  astreum/storage/setup.py,sha256=1-9ztEFI_BvRDvAA0lAn4mFya8iq65THTArlj--M3Hg,626
49
49
  astreum/utils/bytes.py,sha256=9QTWC2JCdwWLB5R2mPtmjPro0IUzE58DL3uEul4AheE,846
50
50
  astreum/utils/integer.py,sha256=iQt-klWOYVghu_NOT341MmHbOle4FDT3by4PNKNXscg,736
51
- astreum-0.2.47.dist-info/licenses/LICENSE,sha256=gYBvRDP-cPLmTyJhvZ346QkrYW_eleke4Z2Yyyu43eQ,1089
52
- astreum-0.2.47.dist-info/METADATA,sha256=uTOobOKSzgiMyBbZTWOIOt7N4JpG448VpWrJNJq7OF0,6181
53
- astreum-0.2.47.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
54
- astreum-0.2.47.dist-info/top_level.txt,sha256=1EG1GmkOk3NPmUA98FZNdKouhRyget-KiFiMk0i2Uz0,8
55
- astreum-0.2.47.dist-info/RECORD,,
51
+ astreum/utils/logging.py,sha256=mRDtWSCj8vKt58WGKLNSkK9Oa0graNVSoS8URby4Q9g,6684
52
+ astreum-0.2.49.dist-info/licenses/LICENSE,sha256=gYBvRDP-cPLmTyJhvZ346QkrYW_eleke4Z2Yyyu43eQ,1089
53
+ astreum-0.2.49.dist-info/METADATA,sha256=izBxY2NXmhbWm57Tz8cBvH3XajjootIv7IUtqmwdsm4,7726
54
+ astreum-0.2.49.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
55
+ astreum-0.2.49.dist-info/top_level.txt,sha256=1EG1GmkOk3NPmUA98FZNdKouhRyget-KiFiMk0i2Uz0,8
56
+ astreum-0.2.49.dist-info/RECORD,,