Blazeio 0.0.0.9__tar.gz

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.
@@ -0,0 +1,208 @@
1
+ # Blazeio.Client
2
+ from asyncio import Protocol, get_event_loop, sleep
3
+ from time import perf_counter
4
+ from ssl import create_default_context, SSLError
5
+ from ujson import loads, dumps
6
+ from collections import deque, defaultdict
7
+
8
+ p = print
9
+
10
+ class Err(Exception):
11
+ def __init__(app, message=None):
12
+ super().__init__(message)
13
+ app.message = str(message)
14
+
15
+ def __str__(app) -> str:
16
+ return app.message
17
+
18
+ class BlazeioClientProtocol(Protocol):
19
+ def __init__(app):
20
+ app.buffer = deque()
21
+ app.response_headers = defaultdict(str)
22
+ app.remaining = bytearray()
23
+ app.__is_at_eof__ = False
24
+ app.__is_connection_lost__ = False
25
+ app.__pulled_length__ = 0
26
+ app.__perf_counter__ = perf_counter()
27
+ app.__all__ = bytearray()
28
+
29
+ def connection_made(app, transport):
30
+ app.transport = transport
31
+
32
+ def data_received(app, data):
33
+ app.buffer.append(data)
34
+
35
+ def eof_received(app):
36
+ app.__is_at_eof__ = True
37
+
38
+ def connection_lost(app, exc):
39
+ app.__is_connection_lost__ = True
40
+
41
+ async def push(app, chunk):
42
+ if not isinstance(chunk, (bytes, bytearray)):
43
+ chunk = chunk.encode()
44
+
45
+ if not app.__is_connection_lost__:
46
+ app.transport.write(chunk)
47
+
48
+ async def pull(app, all=False, timeout=2):
49
+ if all:
50
+ yield b"" + app.__all__
51
+
52
+ else:
53
+ if app.remaining:
54
+ chunk = b"" + app.remaining
55
+ yield chunk
56
+ app.__pulled_length__ += len(app.remaining)
57
+
58
+ endl = b"\r\n0\r\n\r\n"
59
+
60
+ while True:
61
+ await sleep(0)
62
+
63
+ while app.buffer:
64
+ await sleep(0)
65
+ chunk = app.buffer.popleft()
66
+ yield chunk
67
+
68
+ if endl in chunk:
69
+ app.__is_at_eof__ = True
70
+
71
+ if app.__is_connection_lost__:
72
+ break
73
+ if app.__is_at_eof__:
74
+ break
75
+
76
+ if perf_counter() - app.__perf_counter__ >= float(timeout):
77
+ break
78
+ yield None
79
+
80
+ async def fetch_headers(app):
81
+ tmp = bytearray()
82
+ sepr = b"\r\n\r\n"
83
+
84
+ async for data in app.pull():
85
+ if data:
86
+ tmp.extend(data)
87
+ app.__all__.extend(data)
88
+ if sepr in tmp:
89
+ _ = tmp.split(sepr)
90
+ app.remaining.extend(sepr.join(_[1:]))
91
+
92
+ if (i := b'\r\n') in app.remaining:
93
+ app.remaining = i.join(app.remaining.split(i)[1:])
94
+
95
+ tmp = _[0]
96
+ break
97
+
98
+ other_parts = tmp.decode("utf-8")
99
+
100
+ if '\r\n' in other_parts:
101
+ sepr = ': '
102
+ for header in other_parts.split('\r\n'):
103
+ await sleep(0)
104
+ if sepr in header:
105
+ key, val = header.split(sepr, 1)
106
+ app.response_headers[key.strip()] = val.strip()
107
+
108
+ app.response_headers = dict(app.response_headers)
109
+ else:
110
+ return
111
+
112
+ loop = get_event_loop()
113
+
114
+ class Session:
115
+ def __init__(app, url: str, method: str = "GET", headers: dict = {}, port:int = 80, connect_only=False, params=None, body=None, **kwargs):
116
+ app.__dict__.update(locals())
117
+ app.host = app.url
118
+
119
+ async def __aenter__(app):
120
+ if app.params:
121
+ prms = ""
122
+ if not (i := "?") in url:
123
+ prms += i
124
+ else:
125
+ prms += "&"
126
+
127
+ for key, val in app.params.items():
128
+ await sleep(0)
129
+ data = "%s=%s" % (str(key), str(val))
130
+ if "=" in prms:
131
+ prms += "&"
132
+
133
+ prms += data
134
+
135
+ app.url += prms
136
+
137
+ await app.url_to_host()
138
+
139
+ if app.port == 443:
140
+ app.ssl_context = create_default_context()
141
+
142
+ protocol = BlazeioClientProtocol()
143
+ app.protocol = protocol
144
+
145
+ transport, protocol_instance = await loop.create_connection(
146
+ lambda: protocol,
147
+ app.host, app.port, ssl=app.ssl_context if app.port == 443 else None
148
+ )
149
+
150
+ await app.protocol.push(f"{app.method} {app.path} HTTP/1.1\r\n".encode())
151
+
152
+ if not "Host" in app.headers:
153
+ app.headers["Host"] = app.host
154
+
155
+ if app.body:
156
+ app.headers["Content-Length"] = len(app.body)
157
+
158
+ for key, val in app.headers.items():
159
+ await app.protocol.push(f"{key}: {val}\r\n".encode())
160
+ await sleep(0)
161
+
162
+ await app.protocol.push("\r\n".encode())
163
+
164
+ if app.connect_only: return app.protocol
165
+
166
+ if app.method in ["GET", "HEAD", "OPTIONS"]:
167
+ await app.protocol.fetch_headers()
168
+ else:
169
+ if app.body:
170
+ await app.protocol.push(app.body)
171
+
172
+ await app.protocol.fetch_headers()
173
+
174
+ return app.protocol
175
+
176
+ async def url_to_host(app):
177
+ sepr = "://"
178
+ sepr2 = ":"
179
+ sepr3 = "/"
180
+
181
+ if "https" in app.host:
182
+ if app.port == 80: app.port = 443
183
+
184
+ if sepr in app.host:
185
+ app.host = app.host.split(sepr)[-1]
186
+
187
+ if sepr2 in app.host:
188
+ app.host, app.port = app.host.split(sepr2)
189
+ if sepr3 in app.port:
190
+ app.port = app.port.split(sepr3)
191
+ try:app.port = int(app.port[0])
192
+ except: pass
193
+
194
+ if sepr3 in app.host:
195
+ app.host = app.host.split(sepr3)[0]
196
+
197
+ if sepr3 in app.url and len((_ := app.url.split(sepr3))) >= 3:
198
+ app.path = sepr3 + sepr3.join(_[3:])
199
+ else:
200
+ app.path = sepr3
201
+
202
+ async def __aexit__(app, exc_type, exc_val, exc_tb):
203
+ try:
204
+ app.protocol.transport.close()
205
+ except SSLError as e:
206
+ return
207
+ except Exception as e:
208
+ p("Exception: " + str(e))
@@ -0,0 +1,38 @@
1
+ from Client import Session
2
+ from time import perf_counter
3
+ from asyncio import run, sleep, gather, create_task
4
+
5
+ class Test:
6
+ async def test(app, url="http://example.com"):
7
+ try:
8
+ async with Session(url) as r:
9
+ async for data in r.get_data():
10
+ #p(data)
11
+ p("\n\n")
12
+
13
+ return r.response_headers
14
+
15
+ except Exception as e:
16
+ p("Test Exception: " + str(e))
17
+
18
+ async def main(app):
19
+ urls = ["https://example.com", "https://www.google.com", "https://ipify.org", "https://youtube.com"]
20
+ queue = []
21
+
22
+ start = perf_counter()
23
+
24
+ for url in urls:
25
+ task = create_task(app.test(url))
26
+ queue.append(task)
27
+ await sleep(0)
28
+
29
+ result = await gather(*queue)
30
+ p(result)
31
+
32
+ p(f"Duration: {perf_counter() - start:.4f} seconds")
33
+
34
+
35
+ if __name__ == "__main__":
36
+ #run(Test().test())
37
+ run(Test().main())
38
+
@@ -0,0 +1,68 @@
1
+ async def text(app, chunk_size = 1024, decode = True):
2
+ sepr = b"\r\n\r\n"
3
+ chunks = b""
4
+ headers = b""
5
+ app.resp_headers = None
6
+
7
+ async for chunk in app.stream(chunk_size):
8
+ chunks += chunk
9
+ if not app.resp_headers and chunks.rfind(sepr) != -1:
10
+ headers = chunks.split(sepr)[0]
11
+ if b"\r\n" in headers:
12
+ app.resp_headers = {}
13
+
14
+ for h in headers.split(b"\r\n"):
15
+ h = h.decode("utf-8")
16
+ if ": " in h:
17
+ _ = h.split(": ")
18
+ key, val = _[0], ": ".join(_[1:])
19
+
20
+ app.resp_headers[key] = val
21
+
22
+ if chunks.rfind(sepr) == -1:
23
+ return chunks
24
+
25
+ text = sepr.join(chunks.split(sepr)[1:])
26
+
27
+ if decode:
28
+ text = text.decode("utf-8")
29
+
30
+ return text
31
+
32
+ async def json(app, chunk_size = 1024, decode = True):
33
+ sepr = b"\r\n\r\n"
34
+ chunks = b""
35
+ headers = b""
36
+ app.resp_headers = None
37
+
38
+ async for chunk in app.stream(chunk_size):
39
+ chunks += chunk
40
+ if not app.resp_headers and chunks.rfind(sepr) != -1:
41
+ headers = chunks.split(sepr)[0]
42
+ if b"\r\n" in headers:
43
+ app.resp_headers = {}
44
+
45
+ for h in headers.split(b"\r\n"):
46
+ h = h.decode("utf-8")
47
+ if ": " in h:
48
+ _ = h.split(": ")
49
+ key, val = _[0], ": ".join(_[1:])
50
+
51
+ app.resp_headers[key] = val
52
+
53
+ if chunks.rfind(sepr) == -1:
54
+ return chunks
55
+
56
+ text = sepr.join(chunks.split(sepr)[1:])
57
+
58
+ text = b"{".join(text.split(b"{")[1:])
59
+ text = b"{" + text
60
+
61
+ text = b"}".join(text.split(b"}")[:-1])
62
+ text += b"}"
63
+
64
+ text = text.decode("utf-8")
65
+
66
+ text = loads(text)
67
+
68
+ return text
@@ -0,0 +1,40 @@
1
+ from . import Session
2
+ from time import perf_counter
3
+ from asyncio import run, sleep, gather, create_task
4
+
5
+ p = print
6
+
7
+ class Test:
8
+ async def test(app, url="http://example.com"):
9
+ try:
10
+ async with Session(url) as r:
11
+ async for data in r.get_data():
12
+ #p(data)
13
+ p("\n\n")
14
+
15
+ return r.response_headers
16
+
17
+ except Exception as e:
18
+ p("Test Exception: " + str(e))
19
+
20
+ async def main(app):
21
+ urls = ["https://example.com", "https://www.google.com", "https://ipify.org", "https://youtube.com"]
22
+ queue = []
23
+
24
+ start = perf_counter()
25
+
26
+ for url in urls:
27
+ task = create_task(app.test(url))
28
+ queue.append(task)
29
+ await sleep(0)
30
+
31
+ result = await gather(*queue)
32
+ p(result)
33
+
34
+ p(f"Duration: {perf_counter() - start:.4f} seconds")
35
+
36
+
37
+ if __name__ == "__main__":
38
+ #run(Test().test())
39
+ run(Test().main())
40
+
@@ -0,0 +1,214 @@
1
+ # Dependencies.__init___.py
2
+ from asyncio import new_event_loop, run as io_run, CancelledError, get_event_loop, current_task, all_tasks, to_thread, sleep, gather, Protocol as asyncProtocol, run, create_subprocess_shell
3
+
4
+ from collections import deque, defaultdict, OrderedDict
5
+ from types import MappingProxyType
6
+
7
+ from ujson import dumps, loads, JSONDecodeError
8
+
9
+ from sys import exit
10
+ from datetime import datetime as dt
11
+ from inspect import signature as sig, stack
12
+ from typing import Callable
13
+
14
+ """File serving"""
15
+ from aiofile import async_open as iopen
16
+ from mimetypes import guess_type
17
+ from os.path import basename, getsize, exists, join
18
+ from gzip import compress as gzip_compress
19
+
20
+ """logging"""
21
+ from aiologger import Logger
22
+
23
+ """analytics"""
24
+ from time import perf_counter
25
+
26
+ try:
27
+ import uvloop
28
+ uvloop.install()
29
+ except:
30
+ pass
31
+
32
+ logger = Logger.with_default_handlers(name='BlazeioLogger')
33
+
34
+ class Err(Exception):
35
+ def __init__(app, message=None):
36
+ super().__init__(message)
37
+ app.message = str(message)
38
+
39
+ def __str__(app) -> str:
40
+ return app.message
41
+
42
+ class ServerGotInTrouble(Exception):
43
+ def __init__(app, message=None):
44
+ super().__init__(message)
45
+ app.message = str(message)
46
+
47
+ def __str__(app) -> str:
48
+ return app.message
49
+
50
+ class Packdata:
51
+ @classmethod
52
+ async def add(app, **kwargs):
53
+ app = app()
54
+ app.__dict__.update(**kwargs)
55
+ return app
56
+
57
+ @classmethod
58
+ def add_sync(app, **kwargs):
59
+ app = app()
60
+ app.__dict__.update(**kwargs)
61
+ return app
62
+
63
+ loop = get_event_loop()
64
+
65
+ class Log:
66
+ known_exceptions = [
67
+ "[Errno 104] Connection reset by peer",
68
+ "Client has disconnected.",
69
+ "Connection lost",
70
+ ]
71
+
72
+ colors = {
73
+ 'info': '\033[32m',
74
+ 'error': '\033[31m',
75
+ 'warning': '\033[33m',
76
+ 'critical': '\033[38;5;1m',
77
+ 'debug': '\033[34m',
78
+ 'reset': '\033[32m'
79
+ }
80
+
81
+ @classmethod
82
+ async def __log__(app, r=None, message=None, logger_=logger.info):
83
+
84
+ log_level = logger_.__name__.split('.')[-1]
85
+
86
+ color = app.colors.get(log_level, app.colors['reset'])
87
+
88
+ if "BlazeioPayload" in str(r):
89
+ message = str(message).strip()
90
+
91
+ if message in app.known_exceptions:
92
+ return
93
+
94
+ message = f"{color}{message}{app.colors['reset']}"
95
+
96
+ await logger_(
97
+ "%s•%s | [%s:%s] %s" % (
98
+ r.identifier,
99
+ str(dt.now()),
100
+ r.ip_host,
101
+ str(r.ip_port),
102
+ message
103
+ )
104
+ )
105
+ else:
106
+ _ = str(r).strip()
107
+ if message:
108
+ _ += message
109
+
110
+ message = _
111
+
112
+ if message in app.known_exceptions:
113
+ return
114
+
115
+ msg = message
116
+ message = f"{color}{message}{app.colors['reset']}"
117
+
118
+ if msg == "":
119
+ await logger_(message)
120
+ return
121
+
122
+ await logger_(
123
+ "%s•%s | %s" % (
124
+ "",
125
+ str(dt.now()),
126
+ message
127
+ )
128
+ )
129
+
130
+ @classmethod
131
+ async def info(app, *args): await app.__log__(*args, logger_=logger.info)
132
+
133
+ @classmethod
134
+ async def error(app, *args): await app.__log__(*args, logger_=logger.error)
135
+
136
+ @classmethod
137
+ async def warning(app, *args): await app.__log__(*args, logger_=logger.warning)
138
+
139
+ @classmethod
140
+ async def critical(app, *args): await app.__log__(*args, logger_=logger.critical)
141
+
142
+ @classmethod
143
+ async def debug(app, *args): await app.__log__(*args, logger_=logger.debug)
144
+
145
+ @classmethod
146
+ async def m(app, *args): await app.__log__(*args, logger_=logger.error)
147
+
148
+ @classmethod
149
+ async def bench(app):
150
+ start_time = dt.now().timestamp()
151
+
152
+ async def w(task):
153
+ for method in dir(app):
154
+ method = getattr(app, method)
155
+
156
+ if isinstance(method, Callable) and not (name := method.__name__).startswith((sepr := "__")) and not name.endswith(sepr) and method != app.bench and not name in ["type"]:
157
+
158
+ await method(None, name)
159
+
160
+ await app.info("Task %s completed successfully in %s seconds" % (task, dt.now().timestamp() - start_time))
161
+
162
+ tasks = []
163
+
164
+ while len(tasks) < 500:
165
+ task = loop.create_task( w(len(tasks) +1 ) )
166
+ tasks.append(task)
167
+
168
+ await gather(*tasks)
169
+
170
+ exit()
171
+
172
+ class VersionControlla:
173
+ @classmethod
174
+ async def control(app, ins, HOME, HOST, PORT, **kwargs):
175
+ async def runner():
176
+ process = await create_subprocess_shell(
177
+ cmd=f'python -m Blazeio --path "{HOME}" --host "{HOST}" --port "{PORT}"',
178
+ stdout=None,
179
+ stderr=None,
180
+ )
181
+ try:
182
+ await process.wait()
183
+ except CancelledError:
184
+ process.terminate()
185
+ await process.wait()
186
+ raise
187
+
188
+ while True:
189
+ size = getsize(HOME)
190
+ task = loop.create_task(runner())
191
+
192
+ while True:
193
+ if task.done():
194
+ break
195
+
196
+ if getsize(HOME) == size:
197
+ await sleep(1)
198
+ else:
199
+ await Log.warning(f"version change detected in {HOME}, reloading server...")
200
+ break
201
+
202
+ if not task.done():
203
+ try:
204
+ task.cancel()
205
+ await task
206
+ except CancelledError:
207
+ pass
208
+
209
+ else:
210
+ break
211
+
212
+
213
+ p = Log.info
214
+ loop.run_until_complete(Log.debug(""))