asteri 1.0.0__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.
- asteri/__init__.py +0 -0
- asteri/__main__.py +199 -0
- asteri/arbiter.py +204 -0
- asteri/http.py +120 -0
- asteri/utils.py +93 -0
- asteri/uwsgi.py +50 -0
- asteri/workers/__init__.py +0 -0
- asteri/workers/asgi.py +74 -0
- asteri/workers/base.py +90 -0
- asteri/workers/gevent.py +29 -0
- asteri/workers/gthread.py +25 -0
- asteri/workers/sync.py +83 -0
- asteri-1.0.0.dist-info/METADATA +11 -0
- asteri-1.0.0.dist-info/RECORD +18 -0
- asteri-1.0.0.dist-info/WHEEL +5 -0
- asteri-1.0.0.dist-info/entry_points.txt +2 -0
- asteri-1.0.0.dist-info/licenses/LICENSE +21 -0
- asteri-1.0.0.dist-info/top_level.txt +1 -0
asteri/__init__.py
ADDED
|
File without changes
|
asteri/__main__.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import argparse
|
|
3
|
+
import sys
|
|
4
|
+
import os
|
|
5
|
+
from asteri.arbiter import Arbiter
|
|
6
|
+
from asteri.workers.sync import SyncWorker
|
|
7
|
+
from asteri.workers.gthread import GThreadWorker
|
|
8
|
+
from asteri.workers.asgi import ASGIWorker
|
|
9
|
+
try:
|
|
10
|
+
from asteri.workers.gevent import GeventWorker
|
|
11
|
+
except ImportError:
|
|
12
|
+
GeventWorker = None
|
|
13
|
+
from asteri.utils import logger, print_banner, Colors, setup_logging
|
|
14
|
+
|
|
15
|
+
def import_app(app_path):
|
|
16
|
+
"""Import application from string 'module:callable'."""
|
|
17
|
+
try:
|
|
18
|
+
module_path, app_name = app_path.split(":")
|
|
19
|
+
sys.path.insert(0, os.getcwd())
|
|
20
|
+
module = __import__(module_path)
|
|
21
|
+
return getattr(module, app_name)
|
|
22
|
+
except Exception as e:
|
|
23
|
+
logger.error(f"Could not import app '{Colors.BOLD}{app_path}{Colors.ENDC}': {e}")
|
|
24
|
+
sys.exit(1)
|
|
25
|
+
|
|
26
|
+
def main():
|
|
27
|
+
print_banner()
|
|
28
|
+
|
|
29
|
+
parser = argparse.ArgumentParser(
|
|
30
|
+
prog="asteri",
|
|
31
|
+
description=f"{Colors.BOLD}Asteri: High Performance Web Server{Colors.ENDC}",
|
|
32
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
33
|
+
add_help=True
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
# Positional Arguments
|
|
37
|
+
parser.add_argument("app", nargs="?", help="Application path (e.g., myapp:app)")
|
|
38
|
+
|
|
39
|
+
# Config Group
|
|
40
|
+
config_group = parser.add_argument_group("Config")
|
|
41
|
+
config_group.add_argument("-c", "--config", help="The Asteri config file.")
|
|
42
|
+
config_group.add_argument("-v", "--version", action="version", version="Asteri v1.0.0")
|
|
43
|
+
config_group.add_argument("--check-config", action="store_true", help="Check the configuration and exit.")
|
|
44
|
+
config_group.add_argument("--print-config", action="store_true", help="Print the configuration settings.")
|
|
45
|
+
|
|
46
|
+
# Network Group
|
|
47
|
+
net_group = parser.add_argument_group("Network")
|
|
48
|
+
net_group.add_argument("-b", "--bind", action="append", help="The socket to bind.")
|
|
49
|
+
net_group.add_argument("--backlog", type=int, default=2048, help="The maximum number of pending connections.")
|
|
50
|
+
net_group.add_argument("--reuse-port", action="store_true", help="Set the SO_REUSEPORT flag.")
|
|
51
|
+
|
|
52
|
+
# Worker Group
|
|
53
|
+
worker_group = parser.add_argument_group("Workers")
|
|
54
|
+
worker_group.add_argument("-w", "--workers", type=int, default=1, help="The number of worker processes.")
|
|
55
|
+
worker_group.add_argument("-k", "--worker-class", default="sync", choices=["sync", "gthread", "asgi", "gevent"],
|
|
56
|
+
help="The type of workers to use.")
|
|
57
|
+
worker_group.add_argument("--threads", type=int, default=1, help="The number of worker threads.")
|
|
58
|
+
worker_group.add_argument("--worker-connections", type=int, default=1000, help="Max simultaneous clients.")
|
|
59
|
+
worker_group.add_argument("--max-requests", type=int, default=0, help="Max requests before worker restart.")
|
|
60
|
+
worker_group.add_argument("--max-requests-jitter", type=int, default=0, help="Jitter for max-requests.")
|
|
61
|
+
worker_group.add_argument("-t", "--timeout", type=int, default=30, help="Worker timeout in seconds.")
|
|
62
|
+
worker_group.add_argument("--graceful-timeout", type=int, default=30, help="Timeout for graceful restart.")
|
|
63
|
+
worker_group.add_argument("--keep-alive", type=int, default=2, help="Keep-alive timeout.")
|
|
64
|
+
worker_group.add_argument("--preload", action="store_true", help="Load app code before forking.")
|
|
65
|
+
|
|
66
|
+
# Security/SSL Group
|
|
67
|
+
sec_group = parser.add_argument_group("Security")
|
|
68
|
+
sec_group.add_argument("--keyfile", help="SSL key file")
|
|
69
|
+
sec_group.add_argument("--certfile", help="SSL certificate file")
|
|
70
|
+
sec_group.add_argument("--ca-certs", help="CA certificates file")
|
|
71
|
+
sec_group.add_argument("--ssl-version", type=int, default=2, help="SSL version to use.")
|
|
72
|
+
sec_group.add_argument("--ciphers", help="SSL Cipher suite to use.")
|
|
73
|
+
sec_group.add_argument("-u", "--user", help="Switch worker processes to run as this user.")
|
|
74
|
+
sec_group.add_argument("-g", "--group", help="Switch worker process to run as this group.")
|
|
75
|
+
sec_group.add_argument("-m", "--umask", type=int, default=0, help="Bit mask for file mode.")
|
|
76
|
+
|
|
77
|
+
# Logging Group
|
|
78
|
+
log_group = parser.add_argument_group("Logging")
|
|
79
|
+
log_group.add_argument("--access-logfile", help="The Access log file.")
|
|
80
|
+
log_group.add_argument("--error-logfile", "--log-file", help="The Error log file.")
|
|
81
|
+
log_group.add_argument("--log-level", default="info", choices=["debug", "info", "warning", "error", "critical"])
|
|
82
|
+
log_group.add_argument("--capture-output", action="store_true", help="Redirect stdout/stderr to error log.")
|
|
83
|
+
log_group.add_argument("--access-logformat", help="The access log format.")
|
|
84
|
+
|
|
85
|
+
# Process Group
|
|
86
|
+
proc_group = parser.add_argument_group("Process")
|
|
87
|
+
proc_group.add_argument("-D", "--daemon", action="store_true", help="Daemonize the process.")
|
|
88
|
+
proc_group.add_argument("-p", "--pid", help="PID filename.")
|
|
89
|
+
proc_group.add_argument("--chdir", help="Change directory before loading apps.")
|
|
90
|
+
proc_group.add_argument("-e", "--env", action="append", help="Set environment variables.")
|
|
91
|
+
proc_group.add_argument("-n", "--name", help="Process name for setproctitle.")
|
|
92
|
+
proc_group.add_argument("--reload", action="store_true", help="Restart workers on code changes.")
|
|
93
|
+
|
|
94
|
+
# HTTP limits
|
|
95
|
+
http_group = parser.add_argument_group("HTTP Limits")
|
|
96
|
+
http_group.add_argument("--limit-request-line", type=int, default=4094)
|
|
97
|
+
http_group.add_argument("--limit-request-fields", type=int, default=100)
|
|
98
|
+
http_group.add_argument("--limit-request-field_size", type=int, default=8190)
|
|
99
|
+
|
|
100
|
+
# HTTP/2 Group
|
|
101
|
+
h2_group = parser.add_argument_group("HTTP/2")
|
|
102
|
+
h2_group.add_argument("--http-protocols", default="h1", help="HTTP protocols to support (e.g., h1,h2)")
|
|
103
|
+
h2_group.add_argument("--http2-max-concurrent-streams", type=int, default=100)
|
|
104
|
+
|
|
105
|
+
args = parser.parse_args()
|
|
106
|
+
|
|
107
|
+
# 1. Load Config File if provided
|
|
108
|
+
if args.config and os.path.exists(args.config):
|
|
109
|
+
config_namespace = {}
|
|
110
|
+
with open(args.config) as f:
|
|
111
|
+
exec(f.read(), config_namespace)
|
|
112
|
+
for key, value in config_namespace.items():
|
|
113
|
+
if hasattr(args, key.lower()):
|
|
114
|
+
setattr(args, key.lower(), value)
|
|
115
|
+
|
|
116
|
+
# Ensure bind is always a list
|
|
117
|
+
if args.bind and isinstance(args.bind, str):
|
|
118
|
+
args.bind = [args.bind]
|
|
119
|
+
elif not args.bind:
|
|
120
|
+
args.bind = ["127.0.0.1:8000"]
|
|
121
|
+
|
|
122
|
+
# 2. Check Config
|
|
123
|
+
if args.check_config or args.print_config:
|
|
124
|
+
if args.print_config:
|
|
125
|
+
print(f"{Colors.BOLD}Resolved Configuration:{Colors.ENDC}")
|
|
126
|
+
for arg in vars(args):
|
|
127
|
+
print(f" {arg}: {getattr(args, arg)}")
|
|
128
|
+
sys.exit(0)
|
|
129
|
+
|
|
130
|
+
# 3. Handle Chdir
|
|
131
|
+
if args.chdir:
|
|
132
|
+
os.chdir(args.chdir)
|
|
133
|
+
sys.path.insert(0, os.getcwd())
|
|
134
|
+
|
|
135
|
+
# 4. Handle Env
|
|
136
|
+
if args.env:
|
|
137
|
+
for env_var in args.env:
|
|
138
|
+
if "=" in env_var:
|
|
139
|
+
k, v = env_var.split("=", 1)
|
|
140
|
+
os.environ[k] = v
|
|
141
|
+
|
|
142
|
+
# 5. Logging setup
|
|
143
|
+
log_file = args.error_logfile
|
|
144
|
+
log_level_name = (args.log_level or "info").upper()
|
|
145
|
+
log_level = getattr(logging, log_level_name, logging.INFO)
|
|
146
|
+
setup_logging(log_file=log_file, level=log_level)
|
|
147
|
+
|
|
148
|
+
worker_map = {
|
|
149
|
+
"sync": SyncWorker,
|
|
150
|
+
"gthread": GThreadWorker,
|
|
151
|
+
"asgi": ASGIWorker,
|
|
152
|
+
"gevent": GeventWorker
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
worker_class = worker_map[args.worker_class]
|
|
156
|
+
if worker_class is None:
|
|
157
|
+
logger.error(f"Worker class '{args.worker_class}' is not available.")
|
|
158
|
+
sys.exit(1)
|
|
159
|
+
|
|
160
|
+
if not args.app:
|
|
161
|
+
parser.print_help()
|
|
162
|
+
sys.exit(1)
|
|
163
|
+
|
|
164
|
+
# Preload
|
|
165
|
+
if args.preload:
|
|
166
|
+
from asteri.utils import import_app
|
|
167
|
+
import_app(args.app)
|
|
168
|
+
|
|
169
|
+
# Setup binds
|
|
170
|
+
binds = args.bind if args.bind else ["127.0.0.1:8000"]
|
|
171
|
+
|
|
172
|
+
arbiter = Arbiter(
|
|
173
|
+
args.app, worker_class,
|
|
174
|
+
num_workers=args.workers,
|
|
175
|
+
bind=binds[0],
|
|
176
|
+
reload=args.reload,
|
|
177
|
+
certfile=args.certfile,
|
|
178
|
+
keyfile=args.keyfile,
|
|
179
|
+
daemon=args.daemon,
|
|
180
|
+
pidfile=args.pid,
|
|
181
|
+
user=args.user,
|
|
182
|
+
group=args.group,
|
|
183
|
+
umask=args.umask,
|
|
184
|
+
proc_name=args.name,
|
|
185
|
+
timeout=args.timeout
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
logger.info(f"Booting {Colors.CYAN}{args.worker_class}{Colors.ENDC} workers...")
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
arbiter.start()
|
|
192
|
+
except KeyboardInterrupt:
|
|
193
|
+
pass
|
|
194
|
+
except Exception as e:
|
|
195
|
+
logger.error(f"Fatal error: {e}")
|
|
196
|
+
sys.exit(1)
|
|
197
|
+
|
|
198
|
+
if __name__ == "__main__":
|
|
199
|
+
main()
|
asteri/arbiter.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import signal
|
|
3
|
+
import socket
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
from .utils import logger, set_proctitle, Colors
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
from watchdog.observers import Observer
|
|
10
|
+
from watchdog.events import FileSystemEventHandler
|
|
11
|
+
WATCHDOG_AVAILABLE = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
WATCHDOG_AVAILABLE = False
|
|
14
|
+
|
|
15
|
+
class Arbiter:
|
|
16
|
+
"""The Master process that manages workers."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, app_path, worker_class, num_workers=1, bind="0.0.0.0:8000", reload=False, certfile=None, keyfile=None,
|
|
19
|
+
daemon=False, pidfile=None, user=None, group=None, umask=0, proc_name=None, timeout=30):
|
|
20
|
+
self.app_path = app_path
|
|
21
|
+
self.worker_class = worker_class
|
|
22
|
+
self.num_workers = num_workers
|
|
23
|
+
self.bind = bind
|
|
24
|
+
self.reload = reload
|
|
25
|
+
self.certfile = certfile
|
|
26
|
+
self.keyfile = keyfile
|
|
27
|
+
self.daemon = daemon
|
|
28
|
+
self.pidfile = pidfile
|
|
29
|
+
self.user = user
|
|
30
|
+
self.group = group
|
|
31
|
+
self.umask = umask
|
|
32
|
+
self.proc_name = proc_name or "master"
|
|
33
|
+
self.timeout = timeout
|
|
34
|
+
self.workers = {} # pid -> worker_instance
|
|
35
|
+
self.sock = None
|
|
36
|
+
self.alive = True
|
|
37
|
+
self.pid = os.getpid()
|
|
38
|
+
self.reloader = None
|
|
39
|
+
|
|
40
|
+
def start(self):
|
|
41
|
+
if self.daemon:
|
|
42
|
+
self.daemonize()
|
|
43
|
+
|
|
44
|
+
if self.pidfile:
|
|
45
|
+
self.write_pid()
|
|
46
|
+
|
|
47
|
+
if self.umask:
|
|
48
|
+
os.umask(self.umask)
|
|
49
|
+
|
|
50
|
+
set_proctitle(self.proc_name)
|
|
51
|
+
logger.info(f"Starting Asteri Arbiter (pid: {Colors.BOLD}{os.getpid()}{Colors.ENDC})")
|
|
52
|
+
|
|
53
|
+
if self.reload and WATCHDOG_AVAILABLE:
|
|
54
|
+
self.setup_reloader()
|
|
55
|
+
elif self.reload:
|
|
56
|
+
logger.warning("Watchdog not available, falling back to manual reload.")
|
|
57
|
+
|
|
58
|
+
# Create listener socket
|
|
59
|
+
host, port = self.bind.split(":")
|
|
60
|
+
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
61
|
+
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
62
|
+
|
|
63
|
+
if self.certfile and self.keyfile:
|
|
64
|
+
import ssl
|
|
65
|
+
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
66
|
+
context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
|
|
67
|
+
self.sock = context.wrap_socket(self.sock, server_side=True)
|
|
68
|
+
logger.info(f"SSL {Colors.GREEN}enabled{Colors.ENDC} ({self.certfile})")
|
|
69
|
+
|
|
70
|
+
self.sock.bind((host, int(port)))
|
|
71
|
+
self.sock.listen(1024)
|
|
72
|
+
self.sock.setblocking(False)
|
|
73
|
+
|
|
74
|
+
scheme = "https" if self.certfile else "http"
|
|
75
|
+
logger.info(f"Listening on {Colors.UNDERLINE}{scheme}://{self.bind}{Colors.ENDC}")
|
|
76
|
+
|
|
77
|
+
self.setup_signals()
|
|
78
|
+
self.manage_workers()
|
|
79
|
+
|
|
80
|
+
def setup_reloader(self):
|
|
81
|
+
class ReloadHandler(FileSystemEventHandler):
|
|
82
|
+
def __init__(self, arbiter):
|
|
83
|
+
self.arbiter = arbiter
|
|
84
|
+
def on_modified(self, event):
|
|
85
|
+
if event.src_path.endswith('.py'):
|
|
86
|
+
logger.info(f"Change detected in {Colors.BOLD}{os.path.basename(event.src_path)}{Colors.ENDC}. Reloading...")
|
|
87
|
+
self.arbiter.stop_workers(signal.SIGTERM)
|
|
88
|
+
|
|
89
|
+
self.reloader = Observer()
|
|
90
|
+
self.reloader.schedule(ReloadHandler(self), os.getcwd(), recursive=True)
|
|
91
|
+
self.reloader.start()
|
|
92
|
+
logger.info(f"Auto-reload {Colors.GREEN}enabled{Colors.ENDC} (watchdog)")
|
|
93
|
+
|
|
94
|
+
def daemonize(self):
|
|
95
|
+
"""Standard double-fork daemonization."""
|
|
96
|
+
if os.fork() > 0: sys.exit(0)
|
|
97
|
+
os.setsid()
|
|
98
|
+
if os.fork() > 0: sys.exit(0)
|
|
99
|
+
|
|
100
|
+
# Redirect standard file descriptors
|
|
101
|
+
sys.stdout.flush()
|
|
102
|
+
sys.stderr.flush()
|
|
103
|
+
si = open(os.devnull, 'r')
|
|
104
|
+
so = open(os.devnull, 'a+')
|
|
105
|
+
se = open(os.devnull, 'a+')
|
|
106
|
+
os.dup2(si.fileno(), sys.stdin.fileno())
|
|
107
|
+
os.dup2(so.fileno(), sys.stdout.fileno())
|
|
108
|
+
os.dup2(se.fileno(), sys.stderr.fileno())
|
|
109
|
+
|
|
110
|
+
def write_pid(self):
|
|
111
|
+
with open(self.pidfile, 'w') as f:
|
|
112
|
+
f.write(str(os.getpid()))
|
|
113
|
+
|
|
114
|
+
def switch_user(self):
|
|
115
|
+
if not self.user and not self.group:
|
|
116
|
+
return
|
|
117
|
+
import pwd, grp
|
|
118
|
+
if self.group:
|
|
119
|
+
gid = grp.getgrnam(self.group).gr_gid
|
|
120
|
+
os.setgid(gid)
|
|
121
|
+
if self.user:
|
|
122
|
+
uid = pwd.getpwnam(self.user).pw_uid
|
|
123
|
+
os.setuid(uid)
|
|
124
|
+
|
|
125
|
+
def setup_signals(self):
|
|
126
|
+
signal.signal(signal.SIGCHLD, self.handle_chld)
|
|
127
|
+
signal.signal(signal.SIGTERM, self.handle_exit)
|
|
128
|
+
signal.signal(signal.SIGINT, self.handle_exit)
|
|
129
|
+
signal.signal(signal.SIGHUP, self.handle_hup)
|
|
130
|
+
signal.signal(signal.SIGQUIT, self.handle_quit)
|
|
131
|
+
|
|
132
|
+
def handle_chld(self, sig, frame):
|
|
133
|
+
"""Worker died."""
|
|
134
|
+
self.wakeup()
|
|
135
|
+
|
|
136
|
+
def handle_exit(self, sig, frame):
|
|
137
|
+
self.alive = False
|
|
138
|
+
self.stop_workers(signal.SIGTERM)
|
|
139
|
+
|
|
140
|
+
def handle_quit(self, sig, frame):
|
|
141
|
+
self.alive = False
|
|
142
|
+
self.stop_workers(signal.SIGQUIT)
|
|
143
|
+
|
|
144
|
+
def handle_hup(self, sig, frame):
|
|
145
|
+
"""Reload workers."""
|
|
146
|
+
logger.info("Reloading workers...")
|
|
147
|
+
self.stop_workers(signal.SIGTERM)
|
|
148
|
+
|
|
149
|
+
def wakeup(self):
|
|
150
|
+
"""Force loop to check workers."""
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
def stop_workers(self, sig):
|
|
154
|
+
import psutil
|
|
155
|
+
for pid in list(self.workers.keys()):
|
|
156
|
+
try:
|
|
157
|
+
p = psutil.Process(pid)
|
|
158
|
+
p.send_signal(sig)
|
|
159
|
+
except psutil.NoSuchProcess:
|
|
160
|
+
if pid in self.workers:
|
|
161
|
+
del self.workers[pid]
|
|
162
|
+
|
|
163
|
+
def spawn_worker(self):
|
|
164
|
+
worker = self.worker_class(0, self.pid, self.sock, self.app_path, self.timeout)
|
|
165
|
+
pid = os.fork()
|
|
166
|
+
|
|
167
|
+
if pid == 0: # Child
|
|
168
|
+
try:
|
|
169
|
+
self.switch_user()
|
|
170
|
+
worker.init_process()
|
|
171
|
+
worker.run()
|
|
172
|
+
sys.exit(0)
|
|
173
|
+
except Exception as e:
|
|
174
|
+
logger.error(f"Worker error: {e}")
|
|
175
|
+
sys.exit(1)
|
|
176
|
+
else: # Parent
|
|
177
|
+
self.workers[pid] = worker
|
|
178
|
+
return pid
|
|
179
|
+
|
|
180
|
+
def manage_workers(self):
|
|
181
|
+
while self.alive:
|
|
182
|
+
# Maintain worker count
|
|
183
|
+
while len(self.workers) < self.num_workers:
|
|
184
|
+
self.spawn_worker()
|
|
185
|
+
|
|
186
|
+
# Reaping dead children
|
|
187
|
+
try:
|
|
188
|
+
pid, status = os.waitpid(-1, os.WNOHANG)
|
|
189
|
+
while pid > 0:
|
|
190
|
+
if pid in self.workers:
|
|
191
|
+
del self.workers[pid]
|
|
192
|
+
pid, status = os.waitpid(-1, os.WNOHANG)
|
|
193
|
+
except ChildProcessError:
|
|
194
|
+
pass
|
|
195
|
+
|
|
196
|
+
time.sleep(1.0)
|
|
197
|
+
|
|
198
|
+
# Cleanup
|
|
199
|
+
if self.reloader:
|
|
200
|
+
self.reloader.stop()
|
|
201
|
+
self.reloader.join()
|
|
202
|
+
|
|
203
|
+
logger.info("Asteri shutting down.")
|
|
204
|
+
self.sock.close()
|
asteri/http.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import socket
|
|
2
|
+
import io
|
|
3
|
+
import http.client
|
|
4
|
+
from .utils import logger
|
|
5
|
+
|
|
6
|
+
class HTTPRequest:
|
|
7
|
+
def __init__(self, method, path, version, headers, body=None):
|
|
8
|
+
self.method = method
|
|
9
|
+
self.path = path
|
|
10
|
+
self.version = version
|
|
11
|
+
self.headers = headers
|
|
12
|
+
self.body = body
|
|
13
|
+
|
|
14
|
+
class HTTPParser:
|
|
15
|
+
@staticmethod
|
|
16
|
+
def parse(raw_data):
|
|
17
|
+
"""Simple HTTP/1.1 parser."""
|
|
18
|
+
try:
|
|
19
|
+
# Split headers and body
|
|
20
|
+
header_part, _, body = raw_data.partition(b"\r\n\r\n")
|
|
21
|
+
lines = header_part.split(b"\r\n")
|
|
22
|
+
|
|
23
|
+
if not lines or not lines[0]:
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
# Request line
|
|
27
|
+
request_line = lines[0].decode('ascii').split()
|
|
28
|
+
if len(request_line) < 3:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
method, path, version = request_line
|
|
32
|
+
|
|
33
|
+
# Headers
|
|
34
|
+
headers = {}
|
|
35
|
+
for line in lines[1:]:
|
|
36
|
+
if b":" in line:
|
|
37
|
+
key, value = line.split(b":", 1)
|
|
38
|
+
headers[key.decode('ascii').lower().strip()] = value.decode('ascii').strip()
|
|
39
|
+
|
|
40
|
+
return HTTPRequest(method, path, version, headers, body)
|
|
41
|
+
except Exception as e:
|
|
42
|
+
logger.error(f"Failed to parse HTTP request: {e}")
|
|
43
|
+
return None
|
|
44
|
+
|
|
45
|
+
try:
|
|
46
|
+
import h2.connection
|
|
47
|
+
import h2.events
|
|
48
|
+
H2_AVAILABLE = True
|
|
49
|
+
except ImportError:
|
|
50
|
+
H2_AVAILABLE = False
|
|
51
|
+
|
|
52
|
+
class HTTP2Handler:
|
|
53
|
+
"""Professional HTTP/2 handler using 'h2' library."""
|
|
54
|
+
PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
|
|
55
|
+
|
|
56
|
+
@staticmethod
|
|
57
|
+
def is_http2(data):
|
|
58
|
+
return data.startswith(HTTP2Handler.PREFACE)
|
|
59
|
+
|
|
60
|
+
def __init__(self, sock):
|
|
61
|
+
self.sock = sock
|
|
62
|
+
self.conn = h2.connection.H2Connection()
|
|
63
|
+
self.conn.initiate_connection()
|
|
64
|
+
self.sock.sendall(self.conn.data_to_send())
|
|
65
|
+
|
|
66
|
+
def handle(self):
|
|
67
|
+
"""Main HTTP/2 event loop for a connection."""
|
|
68
|
+
if not H2_AVAILABLE:
|
|
69
|
+
logger.error("HTTP/2 requested but 'h2' library is missing.")
|
|
70
|
+
return
|
|
71
|
+
|
|
72
|
+
while True:
|
|
73
|
+
try:
|
|
74
|
+
data = self.sock.recv(65535)
|
|
75
|
+
if not data: break
|
|
76
|
+
|
|
77
|
+
events = self.conn.receive_data(data)
|
|
78
|
+
for event in events:
|
|
79
|
+
if isinstance(event, h2.events.RequestReceived):
|
|
80
|
+
self.handle_request(event)
|
|
81
|
+
|
|
82
|
+
data_to_send = self.conn.data_to_send()
|
|
83
|
+
if data_to_send:
|
|
84
|
+
self.sock.sendall(data_to_send)
|
|
85
|
+
except Exception as e:
|
|
86
|
+
logger.debug(f"H2 Connection closed: {e}")
|
|
87
|
+
break
|
|
88
|
+
|
|
89
|
+
def handle_request(self, event):
|
|
90
|
+
# Convert H2 headers to dict
|
|
91
|
+
headers = dict(event.headers)
|
|
92
|
+
method = headers.get(':method')
|
|
93
|
+
path = headers.get(':path')
|
|
94
|
+
|
|
95
|
+
# This would then call the app... for now just logging
|
|
96
|
+
logger.info(f"H2 Request: {method} {path}")
|
|
97
|
+
|
|
98
|
+
# Simple H2 Response
|
|
99
|
+
response_headers = [
|
|
100
|
+
(':status', '200'),
|
|
101
|
+
('content-type', 'text/plain'),
|
|
102
|
+
('server', 'Asteri'),
|
|
103
|
+
]
|
|
104
|
+
self.conn.send_headers(event.stream_id, response_headers)
|
|
105
|
+
self.conn.send_data(event.stream_id, b"Hello from Asteri (HTTP/2)!", end_stream=True)
|
|
106
|
+
self.sock.sendall(self.conn.data_to_send())
|
|
107
|
+
|
|
108
|
+
def build_http_response(status_code, headers, body):
|
|
109
|
+
"""Build a standard HTTP/1.1 response."""
|
|
110
|
+
status_text = http.client.responses.get(status_code, "Unknown")
|
|
111
|
+
response = f"HTTP/1.1 {status_code} {status_text}\r\n"
|
|
112
|
+
|
|
113
|
+
if "Content-Length" not in headers and body:
|
|
114
|
+
headers["Content-Length"] = str(len(body))
|
|
115
|
+
|
|
116
|
+
for key, value in headers.items():
|
|
117
|
+
response += f"{key}: {value}\r\n"
|
|
118
|
+
|
|
119
|
+
response += "\r\n"
|
|
120
|
+
return response.encode('ascii') + (body if isinstance(body, bytes) else body.encode('utf-8'))
|
asteri/utils.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
class Colors:
|
|
6
|
+
PURPLE = '\033[95m'
|
|
7
|
+
BLUE = '\033[94m'
|
|
8
|
+
CYAN = '\033[96m'
|
|
9
|
+
GREEN = '\033[92m'
|
|
10
|
+
YELLOW = '\033[93m'
|
|
11
|
+
RED = '\033[91m'
|
|
12
|
+
WHITE = '\033[97m'
|
|
13
|
+
ENDC = '\033[0m'
|
|
14
|
+
BOLD = '\033[1m'
|
|
15
|
+
UNDERLINE = '\033[4m'
|
|
16
|
+
|
|
17
|
+
class PrettyFormatter(logging.Formatter):
|
|
18
|
+
def format(self, record):
|
|
19
|
+
level_color = {
|
|
20
|
+
logging.INFO: Colors.GREEN,
|
|
21
|
+
logging.WARNING: Colors.YELLOW,
|
|
22
|
+
logging.ERROR: Colors.RED,
|
|
23
|
+
logging.DEBUG: Colors.BLUE
|
|
24
|
+
}.get(record.levelno, Colors.ENDC)
|
|
25
|
+
|
|
26
|
+
timestamp = self.formatTime(record, self.datefmt)
|
|
27
|
+
msg = super().format(record)
|
|
28
|
+
# We only want to color the level and maybe the process ID
|
|
29
|
+
return f"{Colors.BLUE}[{timestamp}]{Colors.ENDC} {Colors.BOLD}[{record.process}]{Colors.ENDC} {level_color}[{record.levelname}]{Colors.ENDC} {record.getMessage()}"
|
|
30
|
+
|
|
31
|
+
def setup_logging(level=logging.INFO, log_file=None):
|
|
32
|
+
"""Set up the default logger for Asteri."""
|
|
33
|
+
logger = logging.getLogger("asteri")
|
|
34
|
+
logger.setLevel(level)
|
|
35
|
+
|
|
36
|
+
if logger.handlers:
|
|
37
|
+
for handler in list(logger.handlers):
|
|
38
|
+
logger.removeHandler(handler)
|
|
39
|
+
|
|
40
|
+
# Console handler
|
|
41
|
+
handler = logging.StreamHandler(sys.stdout)
|
|
42
|
+
formatter = PrettyFormatter(datefmt='%H:%M:%S')
|
|
43
|
+
handler.setFormatter(formatter)
|
|
44
|
+
logger.addHandler(handler)
|
|
45
|
+
|
|
46
|
+
# File handler if requested
|
|
47
|
+
if log_file:
|
|
48
|
+
file_handler = logging.FileHandler(log_file)
|
|
49
|
+
file_formatter = logging.Formatter(
|
|
50
|
+
'[%(asctime)s] [%(process)d] [%(levelname)s] %(message)s',
|
|
51
|
+
datefmt='%Y-%m-%d %H:%M:%S %z'
|
|
52
|
+
)
|
|
53
|
+
file_handler.setFormatter(file_formatter)
|
|
54
|
+
logger.addHandler(file_handler)
|
|
55
|
+
|
|
56
|
+
return logger
|
|
57
|
+
|
|
58
|
+
logger = setup_logging()
|
|
59
|
+
|
|
60
|
+
def print_banner():
|
|
61
|
+
banner = f"""
|
|
62
|
+
{Colors.BOLD}{Colors.PURPLE}*ASTERI*{Colors.ENDC}
|
|
63
|
+
{Colors.CYAN}v1.0.0{Colors.ENDC}
|
|
64
|
+
{Colors.BOLD}{Colors.CYAN}ASTERI{Colors.ENDC} {Colors.YELLOW}Web Server{Colors.ENDC}
|
|
65
|
+
"""
|
|
66
|
+
print(banner)
|
|
67
|
+
|
|
68
|
+
def set_proctitle(title):
|
|
69
|
+
"""Attempt to set the process title for better visibility in ps/top."""
|
|
70
|
+
try:
|
|
71
|
+
import setproctitle
|
|
72
|
+
setproctitle.setproctitle(f"asteri: {title}")
|
|
73
|
+
except ImportError:
|
|
74
|
+
# Fallback if setproctitle is not installed (dependency-free requirement)
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
def import_app(app_path):
|
|
78
|
+
"""Import application from string 'module:callable'."""
|
|
79
|
+
try:
|
|
80
|
+
module_path, app_name = app_path.split(":")
|
|
81
|
+
sys.path.insert(0, os.getcwd())
|
|
82
|
+
# Force re-import by removing from sys.modules if it exists
|
|
83
|
+
if module_path in sys.modules:
|
|
84
|
+
del sys.modules[module_path]
|
|
85
|
+
module = __import__(module_path)
|
|
86
|
+
return getattr(module, app_name)
|
|
87
|
+
except Exception as e:
|
|
88
|
+
logger.error(f"Could not import app '{Colors.BOLD}{app_path}{Colors.ENDC}': {e}")
|
|
89
|
+
raise e
|
|
90
|
+
|
|
91
|
+
def get_num_workers():
|
|
92
|
+
"""Returns a default number of workers based on CPU count."""
|
|
93
|
+
return os.cpu_count() * 2 + 1
|
asteri/uwsgi.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import struct
|
|
2
|
+
from .utils import logger
|
|
3
|
+
|
|
4
|
+
class UWSGIHandler:
|
|
5
|
+
"""Parser for the uWSGI binary protocol."""
|
|
6
|
+
|
|
7
|
+
@staticmethod
|
|
8
|
+
def parse(data):
|
|
9
|
+
"""
|
|
10
|
+
Parses uWSGI packet.
|
|
11
|
+
Header: 4 bytes [modifier1, size_low, size_high, modifier2]
|
|
12
|
+
"""
|
|
13
|
+
if len(data) < 4:
|
|
14
|
+
return None, None
|
|
15
|
+
|
|
16
|
+
modifier1, size, modifier2 = struct.unpack("<BHB", data[:4])
|
|
17
|
+
|
|
18
|
+
# Check if we have enough data
|
|
19
|
+
if len(data) < 4 + size:
|
|
20
|
+
return None, None
|
|
21
|
+
|
|
22
|
+
var_data = data[4:4+size]
|
|
23
|
+
vars_dict = {}
|
|
24
|
+
|
|
25
|
+
pos = 0
|
|
26
|
+
while pos < size:
|
|
27
|
+
if pos + 2 > size: break
|
|
28
|
+
key_len = struct.unpack("<H", var_data[pos:pos+2])[0]
|
|
29
|
+
pos += 2
|
|
30
|
+
if pos + key_len > size: break
|
|
31
|
+
key = var_data[pos:pos+key_len].decode('ascii')
|
|
32
|
+
pos += key_len
|
|
33
|
+
|
|
34
|
+
if pos + 2 > size: break
|
|
35
|
+
val_len = struct.unpack("<H", var_data[pos:pos+2])[0]
|
|
36
|
+
pos += 2
|
|
37
|
+
if pos + val_len > size: break
|
|
38
|
+
val = var_data[pos:pos+val_len].decode('ascii')
|
|
39
|
+
pos += val_len
|
|
40
|
+
|
|
41
|
+
vars_dict[key] = val
|
|
42
|
+
|
|
43
|
+
return vars_dict, modifier1
|
|
44
|
+
|
|
45
|
+
@staticmethod
|
|
46
|
+
def is_uwsgi(data):
|
|
47
|
+
"""Heuristic check for uWSGI protocol."""
|
|
48
|
+
if len(data) < 4: return False
|
|
49
|
+
# modifier1 is usually 0 for WSGI
|
|
50
|
+
return data[0] == 0
|
|
File without changes
|
asteri/workers/asgi.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import socket
|
|
3
|
+
import io
|
|
4
|
+
from .base import BaseWorker
|
|
5
|
+
from ..http import build_http_response
|
|
6
|
+
|
|
7
|
+
class ASGIWorker(BaseWorker):
|
|
8
|
+
def run(self):
|
|
9
|
+
self.init_process()
|
|
10
|
+
asyncio.run(self.main_loop())
|
|
11
|
+
|
|
12
|
+
async def main_loop(self):
|
|
13
|
+
self.socket.setblocking(False)
|
|
14
|
+
loop = asyncio.get_running_loop()
|
|
15
|
+
|
|
16
|
+
while self.alive:
|
|
17
|
+
try:
|
|
18
|
+
client, addr = await loop.sock_accept(self.socket)
|
|
19
|
+
asyncio.create_task(self.handle_asgi_request(client))
|
|
20
|
+
except Exception:
|
|
21
|
+
await asyncio.sleep(0.1)
|
|
22
|
+
|
|
23
|
+
async def handle_asgi_request(self, sock):
|
|
24
|
+
try:
|
|
25
|
+
data = await asyncio.get_running_loop().sock_recv(sock, 4096)
|
|
26
|
+
if not data: return
|
|
27
|
+
|
|
28
|
+
from ..http import HTTPParser
|
|
29
|
+
req = HTTPParser.parse(data)
|
|
30
|
+
if not req: return
|
|
31
|
+
|
|
32
|
+
scope = self.build_asgi_scope(req)
|
|
33
|
+
|
|
34
|
+
response_started = False
|
|
35
|
+
response_body = b""
|
|
36
|
+
status_code = 200
|
|
37
|
+
headers = []
|
|
38
|
+
|
|
39
|
+
async def receive():
|
|
40
|
+
return {'type': 'http.request', 'body': req.body or b"", 'more_body': False}
|
|
41
|
+
|
|
42
|
+
async def send(message):
|
|
43
|
+
nonlocal response_started, response_body, status_code, headers
|
|
44
|
+
if message['type'] == 'http.response.start':
|
|
45
|
+
status_code = message['status']
|
|
46
|
+
headers = {k.decode('ascii'): v.decode('ascii') for k, v in message.get('headers', [])}
|
|
47
|
+
response_started = True
|
|
48
|
+
elif message['type'] == 'http.response.body':
|
|
49
|
+
response_body += message.get('body', b"")
|
|
50
|
+
if not message.get('more_body', False):
|
|
51
|
+
await asyncio.get_running_loop().sock_sendall(
|
|
52
|
+
sock,
|
|
53
|
+
build_http_response(status_code, headers, response_body)
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
await self.app(scope, receive, send)
|
|
57
|
+
except Exception:
|
|
58
|
+
pass
|
|
59
|
+
finally:
|
|
60
|
+
sock.close()
|
|
61
|
+
|
|
62
|
+
def build_asgi_scope(self, req):
|
|
63
|
+
return {
|
|
64
|
+
'type': 'http',
|
|
65
|
+
'asgi': {'version': '3.0', 'spec_version': '2.0'},
|
|
66
|
+
'http_version': '1.1',
|
|
67
|
+
'method': req.method,
|
|
68
|
+
'scheme': 'http',
|
|
69
|
+
'path': req.path.split('?')[0],
|
|
70
|
+
'query_string': req.path.split('?')[1].encode('ascii') if '?' in req.path else b'',
|
|
71
|
+
'headers': [(k.encode('ascii'), v.encode('ascii')) for k, v in req.headers.items()],
|
|
72
|
+
'client': ('127.0.0.1', 0),
|
|
73
|
+
'server': ('127.0.0.1', 8000),
|
|
74
|
+
}
|
asteri/workers/base.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import signal
|
|
3
|
+
import socket
|
|
4
|
+
import time
|
|
5
|
+
from ..utils import logger, set_proctitle, Colors
|
|
6
|
+
|
|
7
|
+
class BaseWorker:
|
|
8
|
+
def __init__(self, age, ppid, socket, app_path, timeout):
|
|
9
|
+
self.age = age
|
|
10
|
+
self.ppid = ppid
|
|
11
|
+
self.socket = socket
|
|
12
|
+
self.app_path = app_path
|
|
13
|
+
self.app = None
|
|
14
|
+
self.timeout = timeout
|
|
15
|
+
self.alive = True
|
|
16
|
+
self.booted = False
|
|
17
|
+
|
|
18
|
+
def init_process(self):
|
|
19
|
+
"""Initialize worker process."""
|
|
20
|
+
from ..utils import import_app
|
|
21
|
+
self.app = import_app(self.app_path)
|
|
22
|
+
|
|
23
|
+
# Set up signals
|
|
24
|
+
signal.signal(signal.SIGQUIT, self.handle_quit)
|
|
25
|
+
signal.signal(signal.SIGTERM, self.handle_exit)
|
|
26
|
+
signal.signal(signal.SIGINT, self.handle_exit)
|
|
27
|
+
|
|
28
|
+
# Reset signals to default that might have been ignored in parent
|
|
29
|
+
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
|
|
30
|
+
|
|
31
|
+
self.booted = True
|
|
32
|
+
set_proctitle(f"worker [{self.__class__.__name__}]")
|
|
33
|
+
logger.info(f"Worker spawned (pid: {Colors.BOLD}{os.getpid()}{Colors.ENDC})")
|
|
34
|
+
|
|
35
|
+
def handle_quit(self, sig, frame):
|
|
36
|
+
self.alive = False
|
|
37
|
+
|
|
38
|
+
def handle_exit(self, sig, frame):
|
|
39
|
+
self.alive = False
|
|
40
|
+
os._exit(0)
|
|
41
|
+
|
|
42
|
+
def run(self):
|
|
43
|
+
raise NotImplementedError()
|
|
44
|
+
|
|
45
|
+
def handle_request(self, client_sock):
|
|
46
|
+
"""Common logic to determine protocol and dispatch."""
|
|
47
|
+
try:
|
|
48
|
+
data = client_sock.recv(4096)
|
|
49
|
+
if not data:
|
|
50
|
+
return
|
|
51
|
+
|
|
52
|
+
from ..http import HTTPParser, HTTP2Handler, build_http_response
|
|
53
|
+
from ..uwsgi import UWSGIHandler
|
|
54
|
+
|
|
55
|
+
# Internal Status Dashboard
|
|
56
|
+
if b"GET /asteri-status" in data:
|
|
57
|
+
status_body = f"Asteri Web Server Status\n"
|
|
58
|
+
status_body += f"Worker PID: {os.getpid()}\n"
|
|
59
|
+
status_body += f"Parent PID: {self.ppid}\n"
|
|
60
|
+
status_body += f"Worker Type: {self.__class__.__name__}\n"
|
|
61
|
+
client_sock.sendall(build_http_response(200, {"Content-Type": "text/plain"}, status_body))
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
if HTTP2Handler.is_http2(data):
|
|
65
|
+
h2_handler = HTTP2Handler(client_sock)
|
|
66
|
+
# We need to pass the initial data if it contains more than preface
|
|
67
|
+
# But for now, handle() will recv more data
|
|
68
|
+
h2_handler.handle()
|
|
69
|
+
return
|
|
70
|
+
elif UWSGIHandler.is_uwsgi(data):
|
|
71
|
+
vars, mod = UWSGIHandler.parse(data)
|
|
72
|
+
if vars:
|
|
73
|
+
self.handle_uwsgi(client_sock, vars)
|
|
74
|
+
else:
|
|
75
|
+
req = HTTPParser.parse(data)
|
|
76
|
+
if req:
|
|
77
|
+
self.handle_http(client_sock, req)
|
|
78
|
+
except Exception as e:
|
|
79
|
+
logger.error(f"Error handling request: {e}")
|
|
80
|
+
finally:
|
|
81
|
+
try:
|
|
82
|
+
client_sock.close()
|
|
83
|
+
except:
|
|
84
|
+
pass
|
|
85
|
+
|
|
86
|
+
def handle_http(self, sock, req):
|
|
87
|
+
raise NotImplementedError()
|
|
88
|
+
|
|
89
|
+
def handle_uwsgi(self, sock, env):
|
|
90
|
+
raise NotImplementedError()
|
asteri/workers/gevent.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import socket
|
|
3
|
+
from .sync import SyncWorker
|
|
4
|
+
from ..utils import logger
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
import gevent
|
|
8
|
+
import gevent.monkey
|
|
9
|
+
from gevent.server import StreamServer
|
|
10
|
+
GEVENT_AVAILABLE = True
|
|
11
|
+
except ImportError:
|
|
12
|
+
GEVENT_AVAILABLE = False
|
|
13
|
+
|
|
14
|
+
class GeventWorker(SyncWorker):
|
|
15
|
+
def run(self):
|
|
16
|
+
if not GEVENT_AVAILABLE:
|
|
17
|
+
logger.error("Gevent is not installed. Please install it with 'pip install gevent' to use this worker.")
|
|
18
|
+
return
|
|
19
|
+
|
|
20
|
+
# Monkey patch
|
|
21
|
+
gevent.monkey.patch_all()
|
|
22
|
+
|
|
23
|
+
self.init_process()
|
|
24
|
+
|
|
25
|
+
def handle(client_sock, address):
|
|
26
|
+
self.handle_request(client_sock)
|
|
27
|
+
|
|
28
|
+
server = StreamServer(self.socket, handle)
|
|
29
|
+
server.serve_forever()
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import socket
|
|
3
|
+
import threading
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
|
+
from .sync import SyncWorker
|
|
6
|
+
|
|
7
|
+
class GThreadWorker(SyncWorker):
|
|
8
|
+
def __init__(self, age, ppid, socket, app, timeout, threads=4):
|
|
9
|
+
super().__init__(age, ppid, socket, app, timeout)
|
|
10
|
+
self.threads = threads
|
|
11
|
+
|
|
12
|
+
def run(self):
|
|
13
|
+
self.init_process()
|
|
14
|
+
self.socket.settimeout(1.0)
|
|
15
|
+
|
|
16
|
+
with ThreadPoolExecutor(max_workers=self.threads) as executor:
|
|
17
|
+
while self.alive:
|
|
18
|
+
try:
|
|
19
|
+
client, addr = self.socket.accept()
|
|
20
|
+
executor.submit(self.handle_request, client)
|
|
21
|
+
except socket.timeout:
|
|
22
|
+
if os.getppid() != self.ppid:
|
|
23
|
+
self.alive = False
|
|
24
|
+
except Exception:
|
|
25
|
+
continue
|
asteri/workers/sync.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import socket
|
|
3
|
+
import sys
|
|
4
|
+
import io
|
|
5
|
+
from .base import BaseWorker
|
|
6
|
+
from ..http import build_http_response
|
|
7
|
+
|
|
8
|
+
class SyncWorker(BaseWorker):
|
|
9
|
+
def run(self):
|
|
10
|
+
self.init_process()
|
|
11
|
+
|
|
12
|
+
# Configure socket to be non-blocking with a timeout for select-like behavior
|
|
13
|
+
self.socket.settimeout(1.0)
|
|
14
|
+
|
|
15
|
+
while self.alive:
|
|
16
|
+
try:
|
|
17
|
+
client, addr = self.socket.accept()
|
|
18
|
+
self.handle_request(client)
|
|
19
|
+
except socket.timeout:
|
|
20
|
+
# Check parent process (Arbiter) is still alive
|
|
21
|
+
if sys.platform != 'win32' and os.getppid() != self.ppid:
|
|
22
|
+
self.alive = False
|
|
23
|
+
break
|
|
24
|
+
except Exception as e:
|
|
25
|
+
if self.alive:
|
|
26
|
+
pass # Log or handle accept errors
|
|
27
|
+
|
|
28
|
+
def handle_http(self, sock, req):
|
|
29
|
+
"""Standard WSGI handling for HTTP/1.1."""
|
|
30
|
+
env = self.build_wsgi_environ(req)
|
|
31
|
+
self.execute_wsgi(sock, env)
|
|
32
|
+
|
|
33
|
+
def handle_uwsgi(self, sock, env):
|
|
34
|
+
"""WSGI handling for uWSGI protocol."""
|
|
35
|
+
self.execute_wsgi(sock, env)
|
|
36
|
+
|
|
37
|
+
def build_wsgi_environ(self, req):
|
|
38
|
+
env = {
|
|
39
|
+
'REQUEST_METHOD': req.method,
|
|
40
|
+
'SCRIPT_NAME': '',
|
|
41
|
+
'PATH_INFO': req.path.split('?')[0],
|
|
42
|
+
'QUERY_STRING': req.path.split('?')[1] if '?' in req.path else '',
|
|
43
|
+
'SERVER_NAME': 'localhost',
|
|
44
|
+
'SERVER_PORT': '8000',
|
|
45
|
+
'SERVER_PROTOCOL': 'HTTP/1.1',
|
|
46
|
+
'wsgi.version': (1, 0),
|
|
47
|
+
'wsgi.url_scheme': 'http',
|
|
48
|
+
'wsgi.input': io.BytesIO(req.body or b""),
|
|
49
|
+
'wsgi.errors': sys.stderr,
|
|
50
|
+
'wsgi.multithread': False,
|
|
51
|
+
'wsgi.multiprocess': True,
|
|
52
|
+
'wsgi.run_once': False,
|
|
53
|
+
}
|
|
54
|
+
for k, v in req.headers.items():
|
|
55
|
+
env[f"HTTP_{k.upper().replace('-', '_')}"] = v
|
|
56
|
+
|
|
57
|
+
if 'content-type' in req.headers:
|
|
58
|
+
env['CONTENT_TYPE'] = req.headers['content-type']
|
|
59
|
+
if 'content-length' in req.headers:
|
|
60
|
+
env['CONTENT_LENGTH'] = req.headers['content-length']
|
|
61
|
+
|
|
62
|
+
return env
|
|
63
|
+
|
|
64
|
+
def execute_wsgi(self, sock, env):
|
|
65
|
+
response_data = []
|
|
66
|
+
headers_set = []
|
|
67
|
+
|
|
68
|
+
def start_response(status, headers, exc_info=None):
|
|
69
|
+
headers_set.extend([status, headers])
|
|
70
|
+
return response_data.append
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
result = self.app(env, start_response)
|
|
74
|
+
status_code = int(headers_set[0].split()[0])
|
|
75
|
+
headers = dict(headers_set[1])
|
|
76
|
+
|
|
77
|
+
body = b"".join(result) if hasattr(result, '__iter__') else result
|
|
78
|
+
if hasattr(result, 'close'):
|
|
79
|
+
result.close()
|
|
80
|
+
|
|
81
|
+
sock.sendall(build_http_response(status_code, headers, body))
|
|
82
|
+
except Exception as e:
|
|
83
|
+
sock.sendall(build_http_response(500, {}, f"WSGI Error: {e}"))
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: asteri
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
License-File: LICENSE
|
|
5
|
+
Requires-Dist: setproctitle>=1.3.3
|
|
6
|
+
Requires-Dist: watchdog>=3.0.0
|
|
7
|
+
Requires-Dist: h2>=4.1.0
|
|
8
|
+
Requires-Dist: gevent>=23.9.1
|
|
9
|
+
Requires-Dist: psutil>=5.9.0
|
|
10
|
+
Dynamic: license-file
|
|
11
|
+
Dynamic: requires-dist
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
asteri/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
asteri/__main__.py,sha256=cOPIBk7slyQaT-OjWoq4kBKtFv17Gv9a_F6rBH-VpfI,8382
|
|
3
|
+
asteri/arbiter.py,sha256=mhz_t8O_gwVLE7gchD5BvZm94cXtKak6O4_sdl5cpMs,6818
|
|
4
|
+
asteri/http.py,sha256=DiIXOyDrDoCGYURKXKD-bzjMEXHvygeCnLcSgjuXgSA,3961
|
|
5
|
+
asteri/utils.py,sha256=ahY7qJQJXaEAPzW-YsRi4gMmboNbtH9OCHra3wsw058,3069
|
|
6
|
+
asteri/uwsgi.py,sha256=hUdbDexLhQQ1sLtAK9IyMfsJEczQwLr-Odkx01ZK4dY,1462
|
|
7
|
+
asteri/workers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
asteri/workers/asgi.py,sha256=AOr1dTyzBk4VlPsGknO1t07A7vDvQI1fhpImHYH32uE,2683
|
|
9
|
+
asteri/workers/base.py,sha256=azd61dWYYOr7n47aH-vdQ4H9b_LR6K1R2TUOAhCF8Ww,3068
|
|
10
|
+
asteri/workers/gevent.py,sha256=KIciq--ml7wi6jv-XxGeO2RGa5dFhBNnO4q42dPBt3g,744
|
|
11
|
+
asteri/workers/gthread.py,sha256=VB32vibNpcT5xzFa-o9Q_iDHvGwncFzI3Z09ZOcrrdc,842
|
|
12
|
+
asteri/workers/sync.py,sha256=h8BQtt3RfC5AR0BtJ0Du_l2FBGvqklrQc6jTOJffWrY,2900
|
|
13
|
+
asteri-1.0.0.dist-info/licenses/LICENSE,sha256=O75LkbUP4RP8OKRx7RfZHXQ-qJjE_ipCCichMzulrRs,1068
|
|
14
|
+
asteri-1.0.0.dist-info/METADATA,sha256=hwiVZDCYxcX5jyuX2jMde332zd9Agf_9wp1nhzsOqcI,267
|
|
15
|
+
asteri-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
16
|
+
asteri-1.0.0.dist-info/entry_points.txt,sha256=e8zqH5clzgec97YjP_aVsdMMjzlT-Y_syrft5ZyT06Y,48
|
|
17
|
+
asteri-1.0.0.dist-info/top_level.txt,sha256=Q6UkJRR0ftchLXGRnD4mpQ4iZXrwDJRmoB23hxJhZKg,7
|
|
18
|
+
asteri-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 IshikawaUta
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
asteri
|