Skip to content

Commit ea484e0

Browse files
feat: cache system implemented
1 parent 135af0b commit ea484e0

File tree

8 files changed

+321
-213
lines changed

8 files changed

+321
-213
lines changed

squarecloud/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
from .client import Client, create_config_file
22
from .square import File
33
from .errors import *
4-
from .http import Routes
4+
from .http import Endpoint

squarecloud/app.py

Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
from .data import AppData
2+
from abc import ABC
3+
from typing import Literal, TYPE_CHECKING
4+
from .square import File
5+
from .data import StatusData, LogsData, FullLogsData, BackupData
6+
from .http import Response
7+
from .errors import SquareException
8+
9+
# avoid circular imports
10+
if TYPE_CHECKING:
11+
from .client import Client
12+
13+
14+
class AppCache:
15+
def __init__(self):
16+
self.status: StatusData | None = None
17+
self.logs: LogsData | None = None
18+
self.full_logs: FullLogsData | None = None
19+
self.backup: BackupData | None = None
20+
21+
def clear_cache(self):
22+
self.status = None
23+
self.logs = None
24+
self.full_logs = None
25+
26+
def update(self, *args):
27+
for arg in args:
28+
if isinstance(arg, StatusData):
29+
self.status = arg
30+
elif isinstance(arg, LogsData):
31+
self.logs = arg
32+
elif isinstance(arg, FullLogsData):
33+
self.full_logs = arg
34+
elif isinstance(arg, BackupData):
35+
self.status = arg
36+
else:
37+
types: list = [
38+
i.__name__ for i in [
39+
StatusData,
40+
LogsData,
41+
FullLogsData,
42+
BackupData,
43+
]
44+
]
45+
raise SquareException(
46+
f'you must provide stats of the following types:\n{types}')
47+
48+
49+
class AbstractApplication(ABC):
50+
"""Abstract application class"""
51+
52+
53+
class Application(AbstractApplication):
54+
"""Represents an application"""
55+
# pylint: disable=too-many-instance-attributes
56+
# nine arguments is available in this case
57+
# pylint: disable=invalid-name
58+
__slots__ = [
59+
'__client',
60+
'__id',
61+
'__tag',
62+
'__ram',
63+
'__lang',
64+
'__type',
65+
'__cluster',
66+
'__is_website',
67+
'__avatar',
68+
'cache'
69+
]
70+
71+
def __init__(self, client: 'Client', data: AppData):
72+
self.__client: Client = client
73+
self.__id: str = data.id
74+
self.__tag: str = data.tag
75+
self.__ram: int = data.ram
76+
self.__lang: Literal['javascript', 'typescript', 'python'] = data.lang
77+
self.__type: Literal['free', 'paid'] = data.type
78+
self.__cluster: str = data.cluster
79+
self.__is_website: bool = data.isWebsite
80+
self.__avatar: str = data.avatar
81+
self.cache: AppCache = AppCache()
82+
83+
def __repr__(self):
84+
return f'<{self.__class__.__name__} tag={self.tag} id={self.id}>'
85+
86+
@property
87+
def client(self):
88+
"""client instance"""
89+
return self.__client
90+
91+
@property
92+
def id(self):
93+
"""application's id"""
94+
return self.__id
95+
96+
@property
97+
def tag(self):
98+
"""application's tag"""
99+
return self.__tag
100+
101+
@property
102+
def ram(self):
103+
"""application's allocated ram"""
104+
return self.__ram
105+
106+
@property
107+
def lang(self):
108+
"""application's programing language"""
109+
return self.__lang
110+
111+
@property
112+
def type(self):
113+
"""application's type"""
114+
return self.__type
115+
116+
@property
117+
def cluster(self):
118+
"""application's cluster"""
119+
return self.__cluster
120+
121+
@property
122+
def is_website(self):
123+
"""whether the application is a website"""
124+
return self.__is_website
125+
126+
@property
127+
def avatar(self):
128+
"""application's avatar"""
129+
return self.__avatar
130+
131+
async def logs(self, update_cache: bool = True) -> LogsData:
132+
"""get application's logs"""
133+
logs: LogsData = await self.__client.get_logs(self.id)
134+
if update_cache:
135+
self.cache.logs = logs
136+
return logs
137+
138+
async def full_logs(self, update_cache: bool = True) -> FullLogsData:
139+
"""get application's full logs"""
140+
full_logs: FullLogsData = await self.__client.logs_complete(self.id)
141+
if update_cache:
142+
self.cache.full_logs = full_logs
143+
return full_logs
144+
145+
async def status(self, update_cache: bool = True) -> StatusData:
146+
"""get application's status"""
147+
status: StatusData = await self.__client.app_status(self.id)
148+
if update_cache:
149+
self.cache.status = status
150+
return status
151+
152+
async def backup(self, update_cache: bool = True) -> BackupData:
153+
"""make backup of this application"""
154+
backup: BackupData = await self.__client.backup(self.id)
155+
if update_cache:
156+
self.cache.backup = backup
157+
return backup
158+
159+
async def start(self, update_cache: bool = True) -> Response:
160+
"""start the application"""
161+
if update_cache:
162+
self.cache.status.running = True
163+
return await self.__client.start_app(self.id)
164+
165+
async def stop(self, update_cache: bool = True) -> Response:
166+
"""stop the application"""
167+
result = await self.__client.stop_app(self.id)
168+
if update_cache:
169+
self.cache.status.running = False
170+
return result
171+
172+
async def restart(self, update_cache: bool = True) -> Response:
173+
"""restart the application"""
174+
result = await self.__client.restart_app(self.id)
175+
if update_cache:
176+
self.cache.status.status = 'restarting'
177+
return result
178+
179+
async def delete(self) -> Response:
180+
"""delete the application"""
181+
return await self.__client.delete_app(self.id)
182+
183+
async def commit(self, file: File) -> Response:
184+
"""commit the application"""
185+
return await self.__client.commit(self.id, file=file)

squarecloud/client.py

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,19 @@
1111
UserData,
1212
LogsData,
1313
BackupData,
14-
CompleteLogsData,
14+
FullLogsData,
1515
)
16-
from .http import HTTPClient, Response, Routes
16+
from .http import HTTPClient, Response, Endpoint
1717
from .logs import logger
18-
from .square import File, Application
18+
from .square import File
19+
from .app import Application
1920
from .errors import ApplicationNotFound, InvalidFile
2021
from .types import (
2122
UserPayload,
2223
StatusPayload,
2324
LogsPayload,
2425
BackupPayload,
25-
CompleteLogsPayload,
26+
FullLogsPayload,
2627
)
2728

2829

@@ -36,11 +37,11 @@ def api_key(self):
3637

3738

3839
def create_config_file(
40+
path: str,
3941
display_name: str,
4042
main: str,
4143
memory: int,
4244
version: Literal['recommended', 'latest'],
43-
path: str,
4445
avatar: str | None = None,
4546
description: str | None = None,
4647
subdomain: str | None = None,
@@ -79,9 +80,9 @@ def create_config_file(
7980
if value is not None:
8081
string: str = f'{key}={value}\n'
8182
content += string
82-
with open(f'./{path}/squarecloud.app', 'w') as f:
83-
f.write(content)
84-
return f
83+
with open(f'./{path}/squarecloud.app', 'w', encoding='utf-8') as file:
84+
file.write(content)
85+
return file
8586

8687

8788
class Client(AbstractClient):
@@ -98,7 +99,7 @@ def __init__(self, api_key: str, debug: bool = True) -> None:
9899
self.debug = debug
99100
self._api_key = api_key
100101
self.__http = HTTPClient(api_key=api_key)
101-
self._listeners: dict[Routes, Callable]
102+
self._listeners: dict[Endpoint, Callable]
102103
if self.debug:
103104
logger.setLevel(logging.DEBUG)
104105

@@ -139,19 +140,19 @@ async def get_logs(self, app_id: str) -> LogsData:
139140
logs_data: LogsData = LogsData(**payload)
140141
return logs_data
141142

142-
async def logs_complete(self, app_id: str) -> CompleteLogsData:
143+
async def logs_complete(self, app_id: str) -> FullLogsData:
143144
"""
144145
Get logs for an application'
145146
146147
Args:
147148
app_id: the application ID
148149
149150
Returns:
150-
CompleteLogsData
151+
FullLogsData
151152
"""
152153
result: Response = await self.__http.fetch_logs_complete(app_id)
153-
payload: CompleteLogsPayload = result.response
154-
logs_data: CompleteLogsData = CompleteLogsData(**payload)
154+
payload: FullLogsPayload = result.response
155+
logs_data: FullLogsData = FullLogsData(**payload)
155156
return logs_data
156157

157158
async def app_status(self, app_id: str) -> StatusData:
@@ -169,32 +170,32 @@ async def app_status(self, app_id: str) -> StatusData:
169170
status: StatusData = StatusData(**payload)
170171
return status
171172

172-
async def start_app(self, app_id: str) -> None:
173+
async def start_app(self, app_id: str) -> Response:
173174
"""
174175
Start an application
175176
176177
Args:
177178
app_id: the application ID
178179
"""
179-
await self.__http.start_application(app_id)
180+
return await self.__http.start_application(app_id)
180181

181-
async def stop_app(self, app_id: str) -> None:
182+
async def stop_app(self, app_id: str) -> Response:
182183
"""
183184
Stop an application
184185
185186
Args:
186187
app_id: the application ID
187188
"""
188-
await self.__http.stop_application(app_id)
189+
return await self.__http.stop_application(app_id)
189190

190-
async def restart_app(self, app_id: str) -> None:
191+
async def restart_app(self, app_id: str) -> Response:
191192
"""
192193
Restart an application
193194
194195
Args:
195196
app_id: the application ID
196197
"""
197-
await self.__http.restart_application(app_id)
198+
return await self.__http.restart_application(app_id)
198199

199200
async def backup(self, app_id: str) -> BackupData:
200201
"""
@@ -210,24 +211,24 @@ async def backup(self, app_id: str) -> BackupData:
210211
backup: BackupData = BackupData(**payload)
211212
return backup
212213

213-
async def delete_app(self, app_id: str) -> None:
214+
async def delete_app(self, app_id: str) -> Response:
214215
"""
215216
Delete an application
216217
217218
Args:
218219
app_id: the application ID
219220
"""
220-
await self.__http.delete_application(app_id)
221+
return await self.__http.delete_application(app_id)
221222

222-
async def commit(self, app_id: str, file: File) -> None:
223+
async def commit(self, app_id: str, file: File) -> Response:
223224
"""
224225
Commit an application
225226
226227
Args:
227228
app_id: the application ID
228229
file: the file object to be committed
229230
"""
230-
await self.__http.commit(app_id, file)
231+
return await self.__http.commit(app_id, file)
231232

232233
async def app(self, app_id: str) -> Application:
233234
"""
@@ -263,12 +264,12 @@ async def all_apps(self) -> List[Application]:
263264
in apps_data]
264265
return apps
265266

266-
async def upload_app(self, zip: File, check_zip: bool = True):
267-
if not isinstance(zip, File):
267+
async def upload_app(self, file: File) -> Response:
268+
if not isinstance(file, File):
268269
raise InvalidFile(
269270
f'you need provide an {File.__name__} object')
270-
elif zip.name.split('.')[-1] != 'zip':
271+
if file.name.split('.')[-1] != 'zip':
271272
raise InvalidFile('the file must be a .zip file')
272-
await self.__http.upload(zip)
273+
return await self.__http.upload(file)
273274

274275
# async def on_request(self):

squarecloud/data.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from dataclasses import dataclass
4-
from typing import Dict, Literal, Any, Optional
4+
from typing import Dict, Literal, Any
55

66

77
# pylint: disable=too-many-instance-attributes
@@ -27,7 +27,7 @@ class StatusData:
2727
network: Dict[str, Any]
2828
requests: int
2929
uptime: int
30-
time: Optional[int] = None
30+
time: int | None = None
3131

3232

3333
@dataclass
@@ -60,7 +60,7 @@ class LogsData:
6060

6161

6262
@dataclass
63-
class CompleteLogsData:
63+
class FullLogsData:
6464
"""complete logs data class"""
6565
logs: str
6666

0 commit comments

Comments
 (0)