Skip to content

Commit 0d0e6d3

Browse files
committed
fix: corrected small errors on caching
1 parent 8510070 commit 0d0e6d3

14 files changed

Lines changed: 143 additions & 74 deletions

File tree

.github/workflows/pypi.yml

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,40 @@
11
name: 'Package Publish'
22
on:
3-
- push
3+
push:
4+
pull_request:
45

56
jobs:
67
packagepublish:
78
runs-on: ubuntu-latest
89
steps:
9-
- uses: https://git.yusufali.ca/actions/commit@main
10-
1110
- name: Check out code
12-
uses: actions/checkout@v2
11+
uses: actions/checkout@v4
1312
with:
1413
submodules: true
15-
fetch-depth: 0
14+
fetch-depth: 100
15+
16+
- name: Use Node.js
17+
uses: actions/setup-node@v4
18+
with:
19+
node-version: 'latest'
20+
21+
- name: Install lint
22+
shell: bash
23+
run: |
24+
npm install -g @commitlint/cli @commitlint/config-conventional
25+
if [ ! -f "commitlint.config.js" ]; then
26+
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
27+
fi
28+
29+
- name: Lint Commit Message
30+
if: github.event_name == 'push'
31+
shell: bash
32+
run: commitlint --from=HEAD~2 --verbose || true
33+
34+
- name: Lint Pull Request
35+
if: github.event_name == 'pull_request'
36+
shell: bash
37+
run: commitlint --from ${{ github.event.pull_request.base.sha }} --to ${{ github.event.pull_request.head.sha }} --verbose
1638

1739
- uses: actions/setup-python@v5
1840
with:

.github/workflows/servc.yml

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ jobs:
1313
matrix:
1414
python-version:
1515
- 3.13
16+
test:
17+
- service/test_config
18+
- service/test_h
19+
- service/test_p
20+
- service/test_simple_metho
21+
- config/
1622

1723
services:
1824
rabbitmq:
@@ -53,13 +59,12 @@ jobs:
5359
- name: Set Environment Variables
5460
run: |
5561
echo "CURRENT_PATH=$(pwd)" >> $GITHUB_ENV
56-
chmod +x start.sh
5762
5863
- name: Checkout Serv-C
5964
uses: actions/checkout@v4
6065
with:
6166
repository: serv-c/docs
62-
ref: 0.3.2
67+
ref: 0.3.3
6368
path: servc-docs
6469
sparse-checkout: |
6570
tests
@@ -75,7 +80,7 @@ jobs:
7580
shell: bash
7681
working-directory: servc-docs
7782
env:
78-
START_SCRIPT: ${{ env.CURRENT_PATH }}/start.sh
83+
START_SCRIPT: ${{ env.CURRENT_PATH }}/main.py
7984
CACHE_URL: redis://redis
8085
BUS_URL: amqp://guest:guest@rabbitmq
81-
run: python -m unittest tests/**/*.py
86+
run: python -m unittest tests/${{ matrix.test }}*.py

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ Here is the most simple example of use, starting a server to handle requests at
1212
```python
1313
from servc.server import start_server
1414

15-
def inputProcessor(messageId, bus, cache, payload, components):
15+
def inputProcessor(messageId, bus, cache, payload, components, emitEvent):
1616
pass
1717

1818
# the method 'methodA' will be resolved by inputProcessor

main.py

100644100755
Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,52 @@
1+
#!/usr/bin/env python
2+
3+
import os
4+
15
from servc.server import start_server
6+
from servc.svc.client.send import sendMessage
7+
from servc.svc.idgen.simple import simple
8+
from servc.svc.io.input import InputType
29

310

4-
def test_resolver(id, bus, cache, payload, _c):
11+
def test_resolver(id, bus, cache, payload: str | list[str], _c, emitEvent):
512
if not isinstance(payload, list):
13+
sendMessage(
14+
{
15+
"type": InputType.INPUT.value,
16+
"id": "",
17+
"route": os.getenv("SEND_ROUTE", "my-response-queue"),
18+
"force": True,
19+
"argumentId": "",
20+
"argument": {
21+
"method": "test",
22+
"inputs": payload,
23+
},
24+
},
25+
bus,
26+
cache,
27+
simple,
28+
)
629
return False
730
for x in payload:
831
if not isinstance(x, str):
932
return False
33+
34+
emitEvent(
35+
os.getenv("EVENT", "my-event"),
36+
payload,
37+
)
1038
return True
1139

1240

41+
def fail(id, _b, _c, _p, _ch, _e):
42+
raise Exception("This is a test exception")
43+
44+
1345
def main():
1446
return start_server(
1547
resolver={
1648
"test": test_resolver,
49+
"fail": fail,
1750
},
1851
# route="test",
1952
)

servc/server.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ def start_server(
8989
onConsuming,
9090
components,
9191
),
92+
daemon=True,
9293
)
9394
consumer.start()
9495

servc/svc/client/send.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,9 @@ def sendMessage(
2727
if "id" not in message or message["id"] in ["", None]
2828
else message["id"]
2929
)
30-
response = cache.getKey(id)
31-
32-
if force:
30+
if force or message.get("force", False):
3331
cache.deleteKey(id)
32+
response = cache.getKey(id)
3433

3534
if (
3635
response

servc/svc/com/bus/rabbitmq.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
import pika.channel # type: ignore
88
import pika.exceptions # type: ignore
99
import simplejson
10-
from pika.adapters.blocking_connection import BlockingConnection # type: ignore
1110
from pika.adapters.asyncio_connection import AsyncioConnection # type: ignore
11+
from pika.adapters.blocking_connection import BlockingConnection # type: ignore
1212

1313
from servc.svc.com.bus import BusComponent, InputProcessor, OnConsuming
1414
from servc.svc.com.cache.redis import decimal_default
@@ -40,13 +40,12 @@ class BusRabbitMQ(BusComponent):
4040
@property
4141
def isReady(self) -> bool:
4242
return (
43-
self._conn is not None and self._conn.is_open and (
44-
self.isBlockingConnection() or
45-
not self._conn.is_closing
46-
)
43+
self._conn is not None
44+
and self._conn.is_open
45+
and (self.isBlockingConnection() or not self._conn.is_closing)
4746
)
4847

49-
@ property
48+
@property
5049
def isOpen(self) -> bool:
5150
return self.isReady
5251

@@ -67,9 +66,10 @@ def _connect(self, method=None | Callable, args=None | Tuple, blocking=True):
6766

6867
def _close(self):
6968
if self.isOpen or self.isReady:
70-
if self._conn and not self._conn.is_closed and (
71-
self.isBlockingConnection() or
72-
not self._conn.is_closing
69+
if (
70+
self._conn
71+
and not self._conn.is_closed
72+
and (self.isBlockingConnection() or not self._conn.is_closing)
7373
):
7474
self._conn.close()
7575
self._conn = None
@@ -117,8 +117,7 @@ def publishMessage( # type: ignore
117117
exchange=exchangeName,
118118
routing_key=self.getRoute(route),
119119
properties=None,
120-
body=simplejson.dumps(
121-
message, default=decimal_default, ignore_nan=True),
120+
body=simplejson.dumps(message, default=decimal_default, ignore_nan=True),
122121
)
123122
channel.close()
124123

@@ -135,18 +134,16 @@ def subscribe( # type: ignore
135134
if not self.isReady:
136135
self._connect(
137136
self.subscribe,
138-
(route, inputProcessor,
139-
onConsuming, bindEventExchange),
140-
blocking=False
137+
(route, inputProcessor, onConsuming, bindEventExchange),
138+
blocking=False,
141139
)
142140
self._conn.ioloop.run_forever() # type: ignore
143141
elif self.isBlockingConnection():
144142
self.close()
145143
return self.subscribe(route, inputProcessor, onConsuming, bindEventExchange)
146144
if not channel:
147145
return self.get_channel(
148-
self.subscribe, (route, inputProcessor,
149-
onConsuming, bindEventExchange)
146+
self.subscribe, (route, inputProcessor, onConsuming, bindEventExchange)
150147
)
151148
channel.add_on_close_callback(lambda _c, _r: self.close())
152149
channel.add_on_cancel_callback(lambda _c: self.close())

servc/svc/com/cache/redis.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,7 @@ def setKey(self, id: str, value: Any) -> str:
4545
self.connect()
4646
return self.setKey(id, value)
4747
self._redisClient.set(
48-
id, simplejson.dumps(
49-
value, default=decimal_default, ignore_nan=True)
48+
id, simplejson.dumps(value, default=decimal_default, ignore_nan=True)
5049
)
5150
return id
5251

servc/svc/com/http/__init__.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,7 @@ def _postMessage(self):
141141
body["instanceId"] if "instanceId" in body else self._instanceId
142142
)
143143

144-
id = self._bus.emitEvent(
145-
body["event"], instanceId, body["details"])
144+
id = self._bus.emitEvent(body["event"], instanceId, body["details"])
146145
return id
147146
elif body["type"] == InputType.INPUT.value:
148147
must_have_keys = ("route", "argument")
@@ -156,6 +155,8 @@ def _postMessage(self):
156155
"id": body["id"] if "id" in body else "",
157156
"argument": body["argument"],
158157
}
158+
if "instanceId" in body:
159+
payload["instanceId"] = body["instanceId"]
159160

160161
id = sendMessage(
161162
payload,
@@ -175,12 +176,9 @@ def _getInformation(self):
175176
return jsonify(self._info)
176177

177178
def bindRoutes(self):
178-
self._server.add_url_rule(
179-
"/healthz", "healthz", self._health, methods=["GET"])
180-
self._server.add_url_rule(
181-
"/readyz", "readyz", self._health, methods=["GET"])
179+
self._server.add_url_rule("/healthz", "healthz", self._health, methods=["GET"])
180+
self._server.add_url_rule("/readyz", "readyz", self._health, methods=["GET"])
182181
self._server.add_url_rule(
183182
"/id/<id>", "_getResponse", self._getResponse, methods=["GET"]
184183
)
185-
self._server.add_url_rule(
186-
"/", "", self._postMessage, methods=["POST", "GET"])
184+
self._server.add_url_rule("/", "", self._postMessage, methods=["POST", "GET"])

servc/svc/com/worker/__init__.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
11
from typing import Any, Callable, Dict, List, Union
22

33
from servc.svc import ComponentType, Middleware
4+
from servc.svc.client.send import sendMessage
45
from servc.svc.com.bus import BusComponent, OnConsuming
56
from servc.svc.com.cache import CacheComponent
67
from servc.svc.config import Config
7-
from servc.svc.io.input import EventPayload, InputPayload, InputType, ArgumentArtifact
8+
from servc.svc.idgen.simple import simple as idGenerator
9+
from servc.svc.io.input import ArgumentArtifact, InputPayload, InputType
810
from servc.svc.io.output import StatusCode
911
from servc.svc.io.response import getAnswerArtifact, getErrorArtifact
10-
from servc.svc.client.send import sendMessage
11-
from servc.svc.idgen.simple import simple as idGenerator
12+
13+
EMIT_EVENT = Callable[[str, Any], None]
1214

1315
RESOLVER = Callable[
14-
[str, BusComponent, CacheComponent, Any, List[Middleware]],
16+
[str, BusComponent, CacheComponent, Any, List[Middleware], EMIT_EVENT],
1517
Union[StatusCode, Any, None],
1618
]
1719

@@ -111,18 +113,12 @@ def connect(self):
111113
bindEventExchange=self._bindToEventExchange,
112114
)
113115

114-
def emitEvent(self, eventName: str, details: Any):
115-
eventMessage: EventPayload = {
116-
"type": InputType.EVENT.value,
117-
"event": eventName,
118-
"details": details,
119-
"route": self._route,
120-
"instanceId": self._instanceId,
121-
}
122-
123-
self._bus.publishMessage(self._route, eventMessage)
116+
def emitEvent(self, bus: BusComponent, eventName: str, details: Any):
117+
bus.emitEvent(eventName, self._instanceId, details)
124118

125-
def processPostHooks(self, bus: BusComponent, message: InputPayload, artifact: ArgumentArtifact):
119+
def processPostHooks(
120+
self, bus: BusComponent, message: InputPayload, artifact: ArgumentArtifact
121+
):
126122
# print(artifact)
127123
if "hooks" in artifact and "on_complete" in artifact["hooks"]:
128124
for hook in artifact["hooks"]["on_complete"]:
@@ -139,9 +135,9 @@ def processPostHooks(self, bus: BusComponent, message: InputPayload, artifact: A
139135
"inputs": {
140136
"id": message["id"],
141137
"method": artifact["method"],
142-
"inputs": artifact["inputs"]
138+
"inputs": artifact["inputs"],
143139
},
144-
}
140+
},
145141
}
146142
sendMessage(payload, bus, self._cache, idGenerator)
147143
except Exception as e:
@@ -155,6 +151,7 @@ def inputProcessor(self, message: Any) -> StatusCode:
155151
self._config.get("conf.bus.prefix"),
156152
)
157153
cache = self._cache
154+
emitEvent: EMIT_EVENT = lambda x, y: self.emitEvent(bus, x, y)
158155

159156
if "type" not in message or "route" not in message:
160157
return StatusCode.INVALID_INPUTS
@@ -174,6 +171,7 @@ def inputProcessor(self, message: Any) -> StatusCode:
174171
cache,
175172
{**message},
176173
self._children,
174+
emitEvent,
177175
)
178176
return StatusCode.OK
179177

@@ -223,16 +221,15 @@ def inputProcessor(self, message: Any) -> StatusCode:
223221
cache,
224222
artifact["inputs"],
225223
self._children,
224+
emitEvent,
226225
)
227-
cache.setKey(message["id"], getAnswerArtifact(
228-
message["id"], response))
226+
cache.setKey(message["id"], getAnswerArtifact(message["id"], response))
229227
self.processPostHooks(bus, message, artifact)
230228
return StatusCode.OK
231229
except Exception as e:
232230
cache.setKey(
233231
message["id"],
234-
getErrorArtifact(message["id"], str(
235-
e), StatusCode.SERVER_ERROR),
232+
getErrorArtifact(message["id"], str(e), StatusCode.SERVER_ERROR),
236233
)
237234
self.processPostHooks(bus, message, artifact)
238235
return StatusCode.SERVER_ERROR

0 commit comments

Comments
 (0)