pyAS4 0.1.25__tar.gz → 0.2.0__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.
- {pyas4-0.1.25 → pyas4-0.2.0}/PKG-INFO +68 -23
- {pyas4-0.1.25 → pyas4-0.2.0}/README.md +67 -22
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4/AS4Client.py +155 -67
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4/header.py +13 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4.egg-info/PKG-INFO +68 -23
- {pyas4-0.1.25 → pyas4-0.2.0}/pyproject.toml +1 -1
- {pyas4-0.1.25 → pyas4-0.2.0}/tests/test_AS4Client.py +229 -2
- {pyas4-0.1.25 → pyas4-0.2.0}/LICENSE +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4/__init__.py +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4/py.typed +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4.egg-info/SOURCES.txt +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4.egg-info/dependency_links.txt +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4.egg-info/requires.txt +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/pyAS4.egg-info/top_level.txt +0 -0
- {pyas4-0.1.25 → pyas4-0.2.0}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyAS4
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python бібліотека для роботи з AS4 (OASIS ebXML AS4) протоколом обміну повідомленнями
|
|
5
5
|
Author: Andriy Shapovalov
|
|
6
6
|
License-Expression: EUPL-1.2
|
|
@@ -68,13 +68,14 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
68
68
|
|
|
69
69
|
`AS4Send` і `AS4Receive` використовують однакові параметри інфраструктури:
|
|
70
70
|
|
|
71
|
-
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу.
|
|
71
|
+
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу. `AS4Send` також приймає вже розібраний
|
|
72
|
+
`zeep.wsdl.Document`.
|
|
72
73
|
|
|
73
|
-
- `transport` — транспорт Zeep. Для `AS4Send`
|
|
74
|
-
|
|
74
|
+
- `transport` — транспорт Zeep. Для `AS4Receive` це основний транспорт. Для `AS4Send` параметр необов'язковий і
|
|
75
|
+
залишений для сумісності (див. нижче).
|
|
75
76
|
|
|
76
|
-
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні,
|
|
77
|
-
список `[]
|
|
77
|
+
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні, можна передати
|
|
78
|
+
порожній список `[]` або нічого не передавати.
|
|
78
79
|
|
|
79
80
|
Різниця між клієнтами стосується лише даних AS4: для відправлення потрібен повний
|
|
80
81
|
`Header`, а для отримання достатньо `c4_party_id` (`finalRecipient`).
|
|
@@ -85,27 +86,52 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
85
86
|
|
|
86
87
|
```python
|
|
87
88
|
AS4Send(
|
|
88
|
-
wsdl: str,
|
|
89
|
-
transport:
|
|
90
|
-
plugins:
|
|
91
|
-
header: Header,
|
|
89
|
+
wsdl: str | zeep.wsdl.Document,
|
|
90
|
+
transport: zeep.Transport | None = None, # застарілий спосіб, див. нижче
|
|
91
|
+
plugins: Sequence[Plugin] | None = None,
|
|
92
|
+
header: Header | None = None, # заголовок за замовчуванням
|
|
93
|
+
*,
|
|
94
|
+
session: requests.Session | None = None,
|
|
95
|
+
cache: zeep.cache.Base | None = None, # кеш для завантаження WSDL
|
|
96
|
+
timeout: int = 300, # таймаут завантаження WSDL
|
|
97
|
+
operation_timeout: int | None = None, # таймаут виклику submitMessage
|
|
92
98
|
)
|
|
93
99
|
```
|
|
94
100
|
|
|
101
|
+
Рекомендований спосіб — **один екземпляр `AS4Send` на сервіс**, створений при старті:
|
|
102
|
+
|
|
103
|
+
- WSDL розбирається ліниво, лише один раз (під `threading.Lock`). Якщо завантаження впало, помилка не кешується:
|
|
104
|
+
наступний виклик пробує знову.
|
|
105
|
+
- HTTP-сесія спільна для всіх відправок.
|
|
106
|
+
- Кожен виклик `send_message()` створює власний `MtomTransport` лише з вкладеннями цього повідомлення та додає
|
|
107
|
+
`PartInfo` до **копії** заголовка. Ні заголовок із конструктора, ні заголовок, переданий у виклик, не змінюються.
|
|
108
|
+
|
|
109
|
+
Тому один екземпляр можна безпечно використовувати повторно, зокрема з кількох потоків
|
|
110
|
+
(`asyncio.to_thread`, `ThreadPoolExecutor`). Плагіни спільні для всіх викликів, тож вони теж мають бути
|
|
111
|
+
придатні для такого використання (наприклад, `HistoryPlugin` зберігатиме останні запити з усіх потоків).
|
|
112
|
+
|
|
95
113
|
Повний `Header` потрібен для формування ebMS-заголовка, включно з інформацією про сторони C1–C4, сервіс, дію,
|
|
96
114
|
conversation ID і вкладення.
|
|
97
115
|
|
|
98
116
|
```python
|
|
99
|
-
from
|
|
117
|
+
from requests import Session
|
|
100
118
|
from zeep.exceptions import Fault
|
|
101
119
|
from zeep.plugins import HistoryPlugin
|
|
102
120
|
|
|
103
121
|
from pyAS4.AS4Client import AS4Send
|
|
104
122
|
from pyAS4.header import Header
|
|
105
123
|
|
|
106
|
-
|
|
107
|
-
|
|
124
|
+
session = Session()
|
|
125
|
+
session.auth = ("domibus-user", "domibus-password")
|
|
126
|
+
|
|
127
|
+
# Один раз при старті сервісу.
|
|
128
|
+
sender = AS4Send(
|
|
129
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
130
|
+
session=session,
|
|
131
|
+
plugins=[HistoryPlugin()],
|
|
132
|
+
)
|
|
108
133
|
|
|
134
|
+
# На кожне повідомлення — власний заголовок і payload.
|
|
109
135
|
header = Header(
|
|
110
136
|
c1_party_id="original-sender",
|
|
111
137
|
c1_party_id_type="urn:example:identifier:sender",
|
|
@@ -124,13 +150,6 @@ header = Header(
|
|
|
124
150
|
header.add_message_property("requestId", "request-123")
|
|
125
151
|
header.add_message_property("trackingId", "tracking-456", property_type="urn:example:tracking")
|
|
126
152
|
|
|
127
|
-
sender = AS4Send(
|
|
128
|
-
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
129
|
-
transport=transport,
|
|
130
|
-
plugins=plugins,
|
|
131
|
-
header=header,
|
|
132
|
-
)
|
|
133
|
-
|
|
134
153
|
payloads = [
|
|
135
154
|
{
|
|
136
155
|
"content": b"<EvidenceRequest>...</EvidenceRequest>",
|
|
@@ -145,11 +164,36 @@ payloads = [
|
|
|
145
164
|
]
|
|
146
165
|
|
|
147
166
|
try:
|
|
148
|
-
response = sender.send_message(payloads)
|
|
167
|
+
response = sender.send_message(payloads, header=header)
|
|
168
|
+
# в asyncio: await asyncio.to_thread(sender.send_message, payloads, header=header)
|
|
149
169
|
except Fault as exc:
|
|
150
170
|
print(f"Domibus відхилив повідомлення: {exc}")
|
|
171
|
+
|
|
172
|
+
# При зупинці сервісу.
|
|
173
|
+
sender.close()
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`close()` закриває HTTP-сесію лише тоді, коли `AS4Send` створив її сам (не було передано ні `session`, ні
|
|
177
|
+
`transport`). `AS4Send` також можна використовувати як контекстний менеджер: `with AS4Send(...) as sender: ...`.
|
|
178
|
+
|
|
179
|
+
#### Сумісний (старий) спосіб
|
|
180
|
+
|
|
181
|
+
Старий виклик працює як раніше:
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
sender = AS4Send(
|
|
185
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
186
|
+
transport=MtomTransport(session=session),
|
|
187
|
+
plugins=[HistoryPlugin()],
|
|
188
|
+
header=header,
|
|
189
|
+
)
|
|
190
|
+
response = sender.send_message(payloads)
|
|
151
191
|
```
|
|
152
192
|
|
|
193
|
+
Якщо передано `transport`, з нього беруться `session`, `cache`, таймаути та додаткові HTTP-заголовки
|
|
194
|
+
`MtomTransport.headers`, але вкладення в нього більше не додаються, а `header` більше не змінюється. Якщо `header` не
|
|
195
|
+
передано ні в конструктор, ні у виклик, `send_message()` викидає `RuntimeError`.
|
|
196
|
+
|
|
153
197
|
Контракт одного елемента `payload`:
|
|
154
198
|
|
|
155
199
|
```python
|
|
@@ -165,7 +209,7 @@ class Payload(TypedDict):
|
|
|
165
209
|
Сигнатура методу:
|
|
166
210
|
|
|
167
211
|
```python
|
|
168
|
-
def send_message(self,
|
|
212
|
+
def send_message(self, payloads: Sequence[Payload], header: Header | None = None) -> Any:
|
|
169
213
|
...
|
|
170
214
|
```
|
|
171
215
|
|
|
@@ -176,7 +220,8 @@ def send_message(self, payload: Sequence[Payload]) -> Any:
|
|
|
176
220
|
|
|
177
221
|
- `cid` (`str`, необов'язковий) — Content-ID вкладення. Якщо значення не передано, бібліотека генерує UUID.
|
|
178
222
|
|
|
179
|
-
`send_message()`
|
|
223
|
+
`send_message()` створює MTOM-транспорт із вкладеннями цього виклику, формує `PayloadInfo` у копії заголовка,
|
|
224
|
+
викликає SOAP-операцію `submitMessage` і
|
|
180
225
|
повертає відповідь Zeep без додаткового перетворення. SOAP Fault та інші транспортні помилки логуються і передаються
|
|
181
226
|
виклику користувача.
|
|
182
227
|
|
|
@@ -45,13 +45,14 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
45
45
|
|
|
46
46
|
`AS4Send` і `AS4Receive` використовують однакові параметри інфраструктури:
|
|
47
47
|
|
|
48
|
-
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу.
|
|
48
|
+
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу. `AS4Send` також приймає вже розібраний
|
|
49
|
+
`zeep.wsdl.Document`.
|
|
49
50
|
|
|
50
|
-
- `transport` — транспорт Zeep. Для `AS4Send`
|
|
51
|
-
|
|
51
|
+
- `transport` — транспорт Zeep. Для `AS4Receive` це основний транспорт. Для `AS4Send` параметр необов'язковий і
|
|
52
|
+
залишений для сумісності (див. нижче).
|
|
52
53
|
|
|
53
|
-
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні,
|
|
54
|
-
список `[]
|
|
54
|
+
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні, можна передати
|
|
55
|
+
порожній список `[]` або нічого не передавати.
|
|
55
56
|
|
|
56
57
|
Різниця між клієнтами стосується лише даних AS4: для відправлення потрібен повний
|
|
57
58
|
`Header`, а для отримання достатньо `c4_party_id` (`finalRecipient`).
|
|
@@ -62,27 +63,52 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
62
63
|
|
|
63
64
|
```python
|
|
64
65
|
AS4Send(
|
|
65
|
-
wsdl: str,
|
|
66
|
-
transport:
|
|
67
|
-
plugins:
|
|
68
|
-
header: Header,
|
|
66
|
+
wsdl: str | zeep.wsdl.Document,
|
|
67
|
+
transport: zeep.Transport | None = None, # застарілий спосіб, див. нижче
|
|
68
|
+
plugins: Sequence[Plugin] | None = None,
|
|
69
|
+
header: Header | None = None, # заголовок за замовчуванням
|
|
70
|
+
*,
|
|
71
|
+
session: requests.Session | None = None,
|
|
72
|
+
cache: zeep.cache.Base | None = None, # кеш для завантаження WSDL
|
|
73
|
+
timeout: int = 300, # таймаут завантаження WSDL
|
|
74
|
+
operation_timeout: int | None = None, # таймаут виклику submitMessage
|
|
69
75
|
)
|
|
70
76
|
```
|
|
71
77
|
|
|
78
|
+
Рекомендований спосіб — **один екземпляр `AS4Send` на сервіс**, створений при старті:
|
|
79
|
+
|
|
80
|
+
- WSDL розбирається ліниво, лише один раз (під `threading.Lock`). Якщо завантаження впало, помилка не кешується:
|
|
81
|
+
наступний виклик пробує знову.
|
|
82
|
+
- HTTP-сесія спільна для всіх відправок.
|
|
83
|
+
- Кожен виклик `send_message()` створює власний `MtomTransport` лише з вкладеннями цього повідомлення та додає
|
|
84
|
+
`PartInfo` до **копії** заголовка. Ні заголовок із конструктора, ні заголовок, переданий у виклик, не змінюються.
|
|
85
|
+
|
|
86
|
+
Тому один екземпляр можна безпечно використовувати повторно, зокрема з кількох потоків
|
|
87
|
+
(`asyncio.to_thread`, `ThreadPoolExecutor`). Плагіни спільні для всіх викликів, тож вони теж мають бути
|
|
88
|
+
придатні для такого використання (наприклад, `HistoryPlugin` зберігатиме останні запити з усіх потоків).
|
|
89
|
+
|
|
72
90
|
Повний `Header` потрібен для формування ebMS-заголовка, включно з інформацією про сторони C1–C4, сервіс, дію,
|
|
73
91
|
conversation ID і вкладення.
|
|
74
92
|
|
|
75
93
|
```python
|
|
76
|
-
from
|
|
94
|
+
from requests import Session
|
|
77
95
|
from zeep.exceptions import Fault
|
|
78
96
|
from zeep.plugins import HistoryPlugin
|
|
79
97
|
|
|
80
98
|
from pyAS4.AS4Client import AS4Send
|
|
81
99
|
from pyAS4.header import Header
|
|
82
100
|
|
|
83
|
-
|
|
84
|
-
|
|
101
|
+
session = Session()
|
|
102
|
+
session.auth = ("domibus-user", "domibus-password")
|
|
103
|
+
|
|
104
|
+
# Один раз при старті сервісу.
|
|
105
|
+
sender = AS4Send(
|
|
106
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
107
|
+
session=session,
|
|
108
|
+
plugins=[HistoryPlugin()],
|
|
109
|
+
)
|
|
85
110
|
|
|
111
|
+
# На кожне повідомлення — власний заголовок і payload.
|
|
86
112
|
header = Header(
|
|
87
113
|
c1_party_id="original-sender",
|
|
88
114
|
c1_party_id_type="urn:example:identifier:sender",
|
|
@@ -101,13 +127,6 @@ header = Header(
|
|
|
101
127
|
header.add_message_property("requestId", "request-123")
|
|
102
128
|
header.add_message_property("trackingId", "tracking-456", property_type="urn:example:tracking")
|
|
103
129
|
|
|
104
|
-
sender = AS4Send(
|
|
105
|
-
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
106
|
-
transport=transport,
|
|
107
|
-
plugins=plugins,
|
|
108
|
-
header=header,
|
|
109
|
-
)
|
|
110
|
-
|
|
111
130
|
payloads = [
|
|
112
131
|
{
|
|
113
132
|
"content": b"<EvidenceRequest>...</EvidenceRequest>",
|
|
@@ -122,11 +141,36 @@ payloads = [
|
|
|
122
141
|
]
|
|
123
142
|
|
|
124
143
|
try:
|
|
125
|
-
response = sender.send_message(payloads)
|
|
144
|
+
response = sender.send_message(payloads, header=header)
|
|
145
|
+
# в asyncio: await asyncio.to_thread(sender.send_message, payloads, header=header)
|
|
126
146
|
except Fault as exc:
|
|
127
147
|
print(f"Domibus відхилив повідомлення: {exc}")
|
|
148
|
+
|
|
149
|
+
# При зупинці сервісу.
|
|
150
|
+
sender.close()
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`close()` закриває HTTP-сесію лише тоді, коли `AS4Send` створив її сам (не було передано ні `session`, ні
|
|
154
|
+
`transport`). `AS4Send` також можна використовувати як контекстний менеджер: `with AS4Send(...) as sender: ...`.
|
|
155
|
+
|
|
156
|
+
#### Сумісний (старий) спосіб
|
|
157
|
+
|
|
158
|
+
Старий виклик працює як раніше:
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
sender = AS4Send(
|
|
162
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
163
|
+
transport=MtomTransport(session=session),
|
|
164
|
+
plugins=[HistoryPlugin()],
|
|
165
|
+
header=header,
|
|
166
|
+
)
|
|
167
|
+
response = sender.send_message(payloads)
|
|
128
168
|
```
|
|
129
169
|
|
|
170
|
+
Якщо передано `transport`, з нього беруться `session`, `cache`, таймаути та додаткові HTTP-заголовки
|
|
171
|
+
`MtomTransport.headers`, але вкладення в нього більше не додаються, а `header` більше не змінюється. Якщо `header` не
|
|
172
|
+
передано ні в конструктор, ні у виклик, `send_message()` викидає `RuntimeError`.
|
|
173
|
+
|
|
130
174
|
Контракт одного елемента `payload`:
|
|
131
175
|
|
|
132
176
|
```python
|
|
@@ -142,7 +186,7 @@ class Payload(TypedDict):
|
|
|
142
186
|
Сигнатура методу:
|
|
143
187
|
|
|
144
188
|
```python
|
|
145
|
-
def send_message(self,
|
|
189
|
+
def send_message(self, payloads: Sequence[Payload], header: Header | None = None) -> Any:
|
|
146
190
|
...
|
|
147
191
|
```
|
|
148
192
|
|
|
@@ -153,7 +197,8 @@ def send_message(self, payload: Sequence[Payload]) -> Any:
|
|
|
153
197
|
|
|
154
198
|
- `cid` (`str`, необов'язковий) — Content-ID вкладення. Якщо значення не передано, бібліотека генерує UUID.
|
|
155
199
|
|
|
156
|
-
`send_message()`
|
|
200
|
+
`send_message()` створює MTOM-транспорт із вкладеннями цього виклику, формує `PayloadInfo` у копії заголовка,
|
|
201
|
+
викликає SOAP-операцію `submitMessage` і
|
|
157
202
|
повертає відповідь Zeep без додаткового перетворення. SOAP Fault та інші транспортні помилки логуються і передаються
|
|
158
203
|
виклику користувача.
|
|
159
204
|
|
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
import base64
|
|
2
2
|
import logging
|
|
3
|
+
import threading
|
|
3
4
|
import uuid
|
|
4
5
|
from collections.abc import Generator, Sequence
|
|
5
6
|
from io import BytesIO
|
|
6
|
-
from
|
|
7
|
+
from types import TracebackType
|
|
8
|
+
from typing import Any, NotRequired, Self, TypedDict
|
|
7
9
|
|
|
8
10
|
from pymtom_xop import MtomAttachment, MtomTransport
|
|
11
|
+
from requests import Session
|
|
9
12
|
from zeep import Client, Settings, Transport
|
|
13
|
+
from zeep.cache import Base as CacheBase
|
|
10
14
|
from zeep.exceptions import Fault
|
|
11
|
-
from zeep.plugins import HistoryPlugin
|
|
15
|
+
from zeep.plugins import HistoryPlugin, Plugin
|
|
16
|
+
from zeep.wsdl import Document
|
|
12
17
|
|
|
13
18
|
from pyAS4.header import Header, get_dict_header
|
|
14
19
|
|
|
15
20
|
_logger = logging.getLogger(__name__)
|
|
16
21
|
|
|
22
|
+
# Real class for isinstance checks; ``Document`` itself is what loads the WSDL.
|
|
23
|
+
_DocumentType = Document
|
|
24
|
+
|
|
17
25
|
|
|
18
26
|
class MessageData(TypedDict):
|
|
19
27
|
messageId: str
|
|
@@ -113,38 +121,25 @@ def get_payload(user_message: dict[str, Any], body: Any) -> list[dict[str, str]]
|
|
|
113
121
|
|
|
114
122
|
class AS4Client:
|
|
115
123
|
"""
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
The
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
:ivar wsdl: The URL or path to the WSDL describing the service. This is a
|
|
125
|
-
critical component for initializing the client.
|
|
126
|
-
:type wsdl: str
|
|
127
|
-
:ivar transport: The transport object that handles the communication layer for
|
|
128
|
-
the AS4 client.
|
|
129
|
-
:type transport: Transport
|
|
130
|
-
:ivar plugins: A list of plugins, such as HistoryPlugin, used for message
|
|
131
|
-
handling, logging, or other custom processing needs.
|
|
132
|
-
:type plugins: list[HistoryPlugin]
|
|
133
|
-
:ivar header: The AS4-specific header required for processing and transmitting
|
|
134
|
-
requests through the client.
|
|
135
|
-
:type header: Header
|
|
124
|
+
Base class for AS4 clients: keeps the WSDL location, transport, plugins and header.
|
|
125
|
+
|
|
126
|
+
:ivar wsdl: The URL or path to the WSDL (or an already parsed
|
|
127
|
+
:class:`zeep.wsdl.Document`).
|
|
128
|
+
:ivar transport: The transport object that handles the communication layer.
|
|
129
|
+
:ivar plugins: zeep plugins, such as HistoryPlugin.
|
|
130
|
+
:ivar header: The AS4 header used for outgoing messages (optional).
|
|
136
131
|
"""
|
|
137
132
|
|
|
138
133
|
def __init__(
|
|
139
134
|
self,
|
|
140
|
-
wsdl: str,
|
|
141
|
-
transport: Transport,
|
|
142
|
-
plugins:
|
|
135
|
+
wsdl: str | Document,
|
|
136
|
+
transport: Transport | None,
|
|
137
|
+
plugins: Sequence[Plugin] | None,
|
|
143
138
|
header: Header | None,
|
|
144
139
|
):
|
|
145
140
|
self.wsdl = wsdl
|
|
146
|
-
self.transport
|
|
147
|
-
self.plugins = plugins
|
|
141
|
+
self.transport = transport
|
|
142
|
+
self.plugins: list[Plugin] = list(plugins or [])
|
|
148
143
|
self.header = header
|
|
149
144
|
|
|
150
145
|
self.settings = Settings(strict=False, xml_huge_tree=True)
|
|
@@ -156,61 +151,138 @@ class MtomTransportProtocol(Transport):
|
|
|
156
151
|
|
|
157
152
|
|
|
158
153
|
class AS4Send(AS4Client):
|
|
154
|
+
"""
|
|
155
|
+
Reusable, thread-safe AS4 sender (Domibus ``submitMessage``).
|
|
156
|
+
|
|
157
|
+
Create one instance per service and call :meth:`send_message` as many times as
|
|
158
|
+
needed, also from several threads (for example via ``asyncio.to_thread``).
|
|
159
|
+
The WSDL is parsed once, lazily, and shared; the HTTP session is shared; every
|
|
160
|
+
call gets its own :class:`MtomTransport` with only its own attachments and its
|
|
161
|
+
own copy of the header.
|
|
162
|
+
|
|
163
|
+
Recommended::
|
|
164
|
+
|
|
165
|
+
sender = AS4Send(wsdl=WSDL_URL, session=session, plugins=[history])
|
|
166
|
+
sender.send_message(payloads, header=header)
|
|
167
|
+
|
|
168
|
+
The older form ``AS4Send(wsdl, transport=MtomTransport(...), plugins, header)``
|
|
169
|
+
followed by ``send_message(payloads)`` still works: ``session``, ``cache`` and
|
|
170
|
+
timeouts are taken from ``transport``, but attachments are no longer added to it.
|
|
171
|
+
"""
|
|
172
|
+
|
|
159
173
|
def __init__(
|
|
160
174
|
self,
|
|
161
|
-
wsdl: str,
|
|
162
|
-
transport:
|
|
163
|
-
plugins:
|
|
164
|
-
header: Header,
|
|
175
|
+
wsdl: str | Document,
|
|
176
|
+
transport: Transport | None = None,
|
|
177
|
+
plugins: Sequence[Plugin] | None = None,
|
|
178
|
+
header: Header | None = None,
|
|
179
|
+
*,
|
|
180
|
+
session: Session | None = None,
|
|
181
|
+
cache: CacheBase | None = None,
|
|
182
|
+
timeout: int = 300,
|
|
183
|
+
operation_timeout: int | None = None,
|
|
165
184
|
):
|
|
166
185
|
"""
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
:param
|
|
174
|
-
|
|
175
|
-
:param
|
|
176
|
-
|
|
177
|
-
:param
|
|
178
|
-
:
|
|
179
|
-
|
|
186
|
+
:param wsdl: WSDL URL, path, or an already parsed :class:`zeep.wsdl.Document`.
|
|
187
|
+
:param transport: (Legacy) a zeep ``Transport``/``MtomTransport`` used only as a
|
|
188
|
+
source of ``session``, ``cache`` and timeouts. Takes precedence over the
|
|
189
|
+
corresponding keyword arguments.
|
|
190
|
+
:param plugins: zeep plugins used for every call. They are shared between calls
|
|
191
|
+
(and threads), so they must be safe for that use.
|
|
192
|
+
:param header: Default header used when :meth:`send_message` gets none.
|
|
193
|
+
It is never modified.
|
|
194
|
+
:param session: Shared ``requests.Session``. If omitted (and no ``transport``),
|
|
195
|
+
the instance creates one and closes it in :meth:`close`.
|
|
196
|
+
:param cache: zeep cache used when loading the WSDL.
|
|
197
|
+
:param timeout: Timeout for loading the WSDL (``zeep.Transport`` ``timeout``).
|
|
198
|
+
:param operation_timeout: Timeout for the ``submitMessage`` POST.
|
|
199
|
+
:raises TypeError: If ``transport`` is not a zeep ``Transport``.
|
|
180
200
|
"""
|
|
181
|
-
if not isinstance(transport,
|
|
182
|
-
raise TypeError("Transport must be an instance of MtomTransport")
|
|
201
|
+
if transport is not None and not isinstance(transport, Transport):
|
|
202
|
+
raise TypeError("Transport must be an instance of zeep.Transport (e.g. MtomTransport)")
|
|
183
203
|
|
|
184
204
|
super().__init__(wsdl, transport, plugins, header)
|
|
185
|
-
self.transport = transport
|
|
186
|
-
self.header = header
|
|
187
205
|
|
|
188
|
-
|
|
206
|
+
self._extra_headers: dict[str, str] = {}
|
|
207
|
+
if transport is not None:
|
|
208
|
+
session = getattr(transport, "session", None)
|
|
209
|
+
cache = getattr(transport, "cache", None)
|
|
210
|
+
timeout = getattr(transport, "load_timeout", timeout)
|
|
211
|
+
operation_timeout = getattr(transport, "operation_timeout", None)
|
|
212
|
+
self._extra_headers = dict(getattr(transport, "headers", None) or {})
|
|
213
|
+
|
|
214
|
+
self._owns_session = session is None
|
|
215
|
+
self.session: Session = session if session is not None else Session()
|
|
216
|
+
self.cache = cache
|
|
217
|
+
self.timeout = timeout
|
|
218
|
+
self.operation_timeout = operation_timeout
|
|
219
|
+
|
|
220
|
+
# Creating a zeep Transport mounts the file:// adapter and sets User-Agent on the
|
|
221
|
+
# session. Do it once here, so later per-call transports only overwrite existing
|
|
222
|
+
# keys and never resize the session's dicts while another thread uses them.
|
|
223
|
+
self._loader = Transport(
|
|
224
|
+
cache=self.cache,
|
|
225
|
+
timeout=self.timeout,
|
|
226
|
+
operation_timeout=self.operation_timeout,
|
|
227
|
+
session=self.session,
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
self._wsdl_lock = threading.Lock()
|
|
231
|
+
self._document: Document | None = wsdl if isinstance(wsdl, _DocumentType) else None
|
|
232
|
+
|
|
233
|
+
def _get_document(self) -> Document:
|
|
234
|
+
"""Return the parsed WSDL, parsing it once. A failed load is not cached."""
|
|
235
|
+
document = self._document
|
|
236
|
+
if document is not None:
|
|
237
|
+
return document
|
|
238
|
+
with self._wsdl_lock:
|
|
239
|
+
if self._document is None:
|
|
240
|
+
_logger.debug("Loading WSDL %s", self.wsdl)
|
|
241
|
+
# zeep annotates `transport` as type[Transport], but it takes an instance.
|
|
242
|
+
self._document = Document(self.wsdl, self._loader, settings=self.settings) # type: ignore[arg-type]
|
|
243
|
+
return self._document
|
|
244
|
+
|
|
245
|
+
def _new_transport(self, files: list[MtomAttachment]) -> MtomTransport:
|
|
246
|
+
transport = MtomTransport(
|
|
247
|
+
cache=self.cache,
|
|
248
|
+
timeout=self.timeout,
|
|
249
|
+
operation_timeout=self.operation_timeout,
|
|
250
|
+
session=self.session,
|
|
251
|
+
)
|
|
252
|
+
if self._extra_headers:
|
|
253
|
+
transport.update_headers(dict(self._extra_headers))
|
|
254
|
+
transport.add_files(files=files)
|
|
255
|
+
return transport
|
|
256
|
+
|
|
257
|
+
def send_message(self, payloads: Sequence[Payload], header: Header | None = None) -> Any:
|
|
189
258
|
"""
|
|
190
|
-
|
|
191
|
-
initializing a SOAP client for further communication.
|
|
259
|
+
Send one AS4 message with the given payloads.
|
|
192
260
|
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
261
|
+
Builds the MTOM attachments, a fresh :class:`MtomTransport` on the shared session
|
|
262
|
+
and a zeep ``Client`` on the shared WSDL, adds PartInfo to a copy of the header
|
|
263
|
+
and calls ``submitMessage``. Neither ``header`` nor the default header is changed.
|
|
196
264
|
|
|
197
|
-
:param
|
|
198
|
-
|
|
199
|
-
:
|
|
265
|
+
:param payloads: Payloads of this message only.
|
|
266
|
+
:param header: Header for this message; defaults to the one given to the constructor.
|
|
267
|
+
:return: The ``submitMessage`` response.
|
|
268
|
+
:raises RuntimeError: If no header is given here or in the constructor.
|
|
200
269
|
"""
|
|
201
|
-
if
|
|
270
|
+
base_header = header if header is not None else self.header
|
|
271
|
+
if base_header is None:
|
|
202
272
|
raise RuntimeError("Header is required to send a message")
|
|
203
273
|
|
|
204
|
-
attach = attachment(
|
|
205
|
-
|
|
274
|
+
attach = attachment(payloads)
|
|
275
|
+
message_header = base_header.copy()
|
|
206
276
|
|
|
207
|
-
|
|
208
|
-
wsdl=self.
|
|
209
|
-
transport=self.
|
|
277
|
+
client = Client(
|
|
278
|
+
wsdl=self._get_document(),
|
|
279
|
+
transport=self._new_transport(attach),
|
|
210
280
|
settings=self.settings,
|
|
211
281
|
plugins=self.plugins,
|
|
212
282
|
)
|
|
213
|
-
|
|
283
|
+
self.client = client
|
|
284
|
+
|
|
285
|
+
PayloadType = client.get_type("ns0:LargePayloadType") # NOSONAR
|
|
214
286
|
bodyload_obj = None
|
|
215
287
|
payload_objs = []
|
|
216
288
|
|
|
@@ -222,11 +294,11 @@ class AS4Send(AS4Client):
|
|
|
222
294
|
payloadId=payload_id,
|
|
223
295
|
contentType=file.content_type,
|
|
224
296
|
)
|
|
225
|
-
|
|
297
|
+
message_header.payload_append([{"href": payload_id, "mimetype": file.content_type}])
|
|
226
298
|
payload_objs.append(obj)
|
|
227
299
|
try:
|
|
228
|
-
response =
|
|
229
|
-
_soapheaders=[
|
|
300
|
+
response = client.service.submitMessage(
|
|
301
|
+
_soapheaders=[message_header.element],
|
|
230
302
|
payload=payload_objs,
|
|
231
303
|
bodyload=bodyload_obj,
|
|
232
304
|
)
|
|
@@ -239,6 +311,22 @@ class AS4Send(AS4Client):
|
|
|
239
311
|
_logger.info("Message sent successfully: %s", response)
|
|
240
312
|
return response
|
|
241
313
|
|
|
314
|
+
def close(self) -> None:
|
|
315
|
+
"""Close the HTTP session if this instance created it."""
|
|
316
|
+
if self._owns_session:
|
|
317
|
+
self.session.close()
|
|
318
|
+
|
|
319
|
+
def __enter__(self) -> Self:
|
|
320
|
+
return self
|
|
321
|
+
|
|
322
|
+
def __exit__(
|
|
323
|
+
self,
|
|
324
|
+
exc_type: type[BaseException] | None,
|
|
325
|
+
exc: BaseException | None,
|
|
326
|
+
tb: TracebackType | None,
|
|
327
|
+
) -> None:
|
|
328
|
+
self.close()
|
|
329
|
+
|
|
242
330
|
|
|
243
331
|
class AS4Receive(AS4Client):
|
|
244
332
|
def __init__(
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import logging
|
|
2
2
|
import uuid
|
|
3
|
+
from copy import copy as _copy
|
|
4
|
+
from copy import deepcopy
|
|
3
5
|
|
|
4
6
|
from lxml import etree
|
|
5
7
|
|
|
@@ -224,6 +226,17 @@ class Header:
|
|
|
224
226
|
attrib={"name": "CompressionType"},
|
|
225
227
|
).text = payload["CompressionType"]
|
|
226
228
|
|
|
229
|
+
def copy(self) -> "Header":
|
|
230
|
+
"""Return an independent copy of this header, including its XML tree.
|
|
231
|
+
|
|
232
|
+
PartInfo or MessageProperties added to the copy do not change the original.
|
|
233
|
+
"""
|
|
234
|
+
new = _copy(self)
|
|
235
|
+
new._xml = deepcopy(self._xml)
|
|
236
|
+
new.pay_load_info = new._xml.find(f".//{_nsmap('eb3', 'PayloadInfo')}")
|
|
237
|
+
new._message_properties = new._xml.find(f".//{_nsmap('eb3', 'MessageProperties')}")
|
|
238
|
+
return new
|
|
239
|
+
|
|
227
240
|
@property
|
|
228
241
|
def element(self) -> etree._Element:
|
|
229
242
|
"""
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyAS4
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: Python бібліотека для роботи з AS4 (OASIS ebXML AS4) протоколом обміну повідомленнями
|
|
5
5
|
Author: Andriy Shapovalov
|
|
6
6
|
License-Expression: EUPL-1.2
|
|
@@ -68,13 +68,14 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
68
68
|
|
|
69
69
|
`AS4Send` і `AS4Receive` використовують однакові параметри інфраструктури:
|
|
70
70
|
|
|
71
|
-
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу.
|
|
71
|
+
- `wsdl` — URL або локальний шлях до WSDL AS4/Domibus-сервісу. `AS4Send` також приймає вже розібраний
|
|
72
|
+
`zeep.wsdl.Document`.
|
|
72
73
|
|
|
73
|
-
- `transport` — транспорт Zeep. Для `AS4Send`
|
|
74
|
-
|
|
74
|
+
- `transport` — транспорт Zeep. Для `AS4Receive` це основний транспорт. Для `AS4Send` параметр необов'язковий і
|
|
75
|
+
залишений для сумісності (див. нижче).
|
|
75
76
|
|
|
76
|
-
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні,
|
|
77
|
-
список `[]
|
|
77
|
+
- `plugins` — список плагінів Zeep, наприклад `[HistoryPlugin()]`. Якщо плагіни не потрібні, можна передати
|
|
78
|
+
порожній список `[]` або нічого не передавати.
|
|
78
79
|
|
|
79
80
|
Різниця між клієнтами стосується лише даних AS4: для відправлення потрібен повний
|
|
80
81
|
`Header`, а для отримання достатньо `c4_party_id` (`finalRecipient`).
|
|
@@ -85,27 +86,52 @@ pyAS4 надає удосконалений клієнт для роботи з
|
|
|
85
86
|
|
|
86
87
|
```python
|
|
87
88
|
AS4Send(
|
|
88
|
-
wsdl: str,
|
|
89
|
-
transport:
|
|
90
|
-
plugins:
|
|
91
|
-
header: Header,
|
|
89
|
+
wsdl: str | zeep.wsdl.Document,
|
|
90
|
+
transport: zeep.Transport | None = None, # застарілий спосіб, див. нижче
|
|
91
|
+
plugins: Sequence[Plugin] | None = None,
|
|
92
|
+
header: Header | None = None, # заголовок за замовчуванням
|
|
93
|
+
*,
|
|
94
|
+
session: requests.Session | None = None,
|
|
95
|
+
cache: zeep.cache.Base | None = None, # кеш для завантаження WSDL
|
|
96
|
+
timeout: int = 300, # таймаут завантаження WSDL
|
|
97
|
+
operation_timeout: int | None = None, # таймаут виклику submitMessage
|
|
92
98
|
)
|
|
93
99
|
```
|
|
94
100
|
|
|
101
|
+
Рекомендований спосіб — **один екземпляр `AS4Send` на сервіс**, створений при старті:
|
|
102
|
+
|
|
103
|
+
- WSDL розбирається ліниво, лише один раз (під `threading.Lock`). Якщо завантаження впало, помилка не кешується:
|
|
104
|
+
наступний виклик пробує знову.
|
|
105
|
+
- HTTP-сесія спільна для всіх відправок.
|
|
106
|
+
- Кожен виклик `send_message()` створює власний `MtomTransport` лише з вкладеннями цього повідомлення та додає
|
|
107
|
+
`PartInfo` до **копії** заголовка. Ні заголовок із конструктора, ні заголовок, переданий у виклик, не змінюються.
|
|
108
|
+
|
|
109
|
+
Тому один екземпляр можна безпечно використовувати повторно, зокрема з кількох потоків
|
|
110
|
+
(`asyncio.to_thread`, `ThreadPoolExecutor`). Плагіни спільні для всіх викликів, тож вони теж мають бути
|
|
111
|
+
придатні для такого використання (наприклад, `HistoryPlugin` зберігатиме останні запити з усіх потоків).
|
|
112
|
+
|
|
95
113
|
Повний `Header` потрібен для формування ebMS-заголовка, включно з інформацією про сторони C1–C4, сервіс, дію,
|
|
96
114
|
conversation ID і вкладення.
|
|
97
115
|
|
|
98
116
|
```python
|
|
99
|
-
from
|
|
117
|
+
from requests import Session
|
|
100
118
|
from zeep.exceptions import Fault
|
|
101
119
|
from zeep.plugins import HistoryPlugin
|
|
102
120
|
|
|
103
121
|
from pyAS4.AS4Client import AS4Send
|
|
104
122
|
from pyAS4.header import Header
|
|
105
123
|
|
|
106
|
-
|
|
107
|
-
|
|
124
|
+
session = Session()
|
|
125
|
+
session.auth = ("domibus-user", "domibus-password")
|
|
126
|
+
|
|
127
|
+
# Один раз при старті сервісу.
|
|
128
|
+
sender = AS4Send(
|
|
129
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
130
|
+
session=session,
|
|
131
|
+
plugins=[HistoryPlugin()],
|
|
132
|
+
)
|
|
108
133
|
|
|
134
|
+
# На кожне повідомлення — власний заголовок і payload.
|
|
109
135
|
header = Header(
|
|
110
136
|
c1_party_id="original-sender",
|
|
111
137
|
c1_party_id_type="urn:example:identifier:sender",
|
|
@@ -124,13 +150,6 @@ header = Header(
|
|
|
124
150
|
header.add_message_property("requestId", "request-123")
|
|
125
151
|
header.add_message_property("trackingId", "tracking-456", property_type="urn:example:tracking")
|
|
126
152
|
|
|
127
|
-
sender = AS4Send(
|
|
128
|
-
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
129
|
-
transport=transport,
|
|
130
|
-
plugins=plugins,
|
|
131
|
-
header=header,
|
|
132
|
-
)
|
|
133
|
-
|
|
134
153
|
payloads = [
|
|
135
154
|
{
|
|
136
155
|
"content": b"<EvidenceRequest>...</EvidenceRequest>",
|
|
@@ -145,11 +164,36 @@ payloads = [
|
|
|
145
164
|
]
|
|
146
165
|
|
|
147
166
|
try:
|
|
148
|
-
response = sender.send_message(payloads)
|
|
167
|
+
response = sender.send_message(payloads, header=header)
|
|
168
|
+
# в asyncio: await asyncio.to_thread(sender.send_message, payloads, header=header)
|
|
149
169
|
except Fault as exc:
|
|
150
170
|
print(f"Domibus відхилив повідомлення: {exc}")
|
|
171
|
+
|
|
172
|
+
# При зупинці сервісу.
|
|
173
|
+
sender.close()
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
`close()` закриває HTTP-сесію лише тоді, коли `AS4Send` створив її сам (не було передано ні `session`, ні
|
|
177
|
+
`transport`). `AS4Send` також можна використовувати як контекстний менеджер: `with AS4Send(...) as sender: ...`.
|
|
178
|
+
|
|
179
|
+
#### Сумісний (старий) спосіб
|
|
180
|
+
|
|
181
|
+
Старий виклик працює як раніше:
|
|
182
|
+
|
|
183
|
+
```python
|
|
184
|
+
sender = AS4Send(
|
|
185
|
+
wsdl="https://domibus.example.eu/services/backend?wsdl",
|
|
186
|
+
transport=MtomTransport(session=session),
|
|
187
|
+
plugins=[HistoryPlugin()],
|
|
188
|
+
header=header,
|
|
189
|
+
)
|
|
190
|
+
response = sender.send_message(payloads)
|
|
151
191
|
```
|
|
152
192
|
|
|
193
|
+
Якщо передано `transport`, з нього беруться `session`, `cache`, таймаути та додаткові HTTP-заголовки
|
|
194
|
+
`MtomTransport.headers`, але вкладення в нього більше не додаються, а `header` більше не змінюється. Якщо `header` не
|
|
195
|
+
передано ні в конструктор, ні у виклик, `send_message()` викидає `RuntimeError`.
|
|
196
|
+
|
|
153
197
|
Контракт одного елемента `payload`:
|
|
154
198
|
|
|
155
199
|
```python
|
|
@@ -165,7 +209,7 @@ class Payload(TypedDict):
|
|
|
165
209
|
Сигнатура методу:
|
|
166
210
|
|
|
167
211
|
```python
|
|
168
|
-
def send_message(self,
|
|
212
|
+
def send_message(self, payloads: Sequence[Payload], header: Header | None = None) -> Any:
|
|
169
213
|
...
|
|
170
214
|
```
|
|
171
215
|
|
|
@@ -176,7 +220,8 @@ def send_message(self, payload: Sequence[Payload]) -> Any:
|
|
|
176
220
|
|
|
177
221
|
- `cid` (`str`, необов'язковий) — Content-ID вкладення. Якщо значення не передано, бібліотека генерує UUID.
|
|
178
222
|
|
|
179
|
-
`send_message()`
|
|
223
|
+
`send_message()` створює MTOM-транспорт із вкладеннями цього виклику, формує `PayloadInfo` у копії заголовка,
|
|
224
|
+
викликає SOAP-операцію `submitMessage` і
|
|
180
225
|
повертає відповідь Zeep без додаткового перетворення. SOAP Fault та інші транспортні помилки логуються і передаються
|
|
181
226
|
виклику користувача.
|
|
182
227
|
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "pyAS4"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.2.0"
|
|
8
8
|
description = "Python бібліотека для роботи з AS4 (OASIS ebXML AS4) протоколом обміну повідомленнями"
|
|
9
9
|
authors = [{ name = "Andriy Shapovalov" }]
|
|
10
10
|
readme = "README.md"
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# pyrefly: ignore [missing-import]
|
|
2
2
|
|
|
3
3
|
import base64
|
|
4
|
+
import threading
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
4
6
|
from copy import deepcopy
|
|
5
7
|
from io import BytesIO
|
|
6
8
|
from types import SimpleNamespace
|
|
@@ -8,8 +10,10 @@ from unittest.mock import Mock, patch
|
|
|
8
10
|
|
|
9
11
|
import pytest
|
|
10
12
|
from pymtom_xop import MtomAttachment, MtomTransport
|
|
11
|
-
from
|
|
13
|
+
from requests import Session
|
|
14
|
+
from zeep import Client, Transport
|
|
12
15
|
from zeep.exceptions import Fault
|
|
16
|
+
from zeep.wsdl import Document
|
|
13
17
|
|
|
14
18
|
from pyAS4.AS4Client import AS4Client, AS4Receive, AS4Send, Payload, _norm_cid, _open_io, attachment, get_payload
|
|
15
19
|
from pyAS4.header import Header, _payload_info
|
|
@@ -209,14 +213,17 @@ class TestHeader:
|
|
|
209
213
|
|
|
210
214
|
|
|
211
215
|
class TestAS4Send:
|
|
216
|
+
@patch("pyAS4.AS4Client.Document")
|
|
212
217
|
@patch("pyAS4.AS4Client.Client")
|
|
213
218
|
@patch("pyAS4.AS4Client.attachment")
|
|
214
|
-
def test_as4send_send_message(self, mock_attachment_func, mock_client_class):
|
|
219
|
+
def test_as4send_send_message(self, mock_attachment_func, mock_client_class, _mock_document):
|
|
215
220
|
transport = Mock(spec=MtomTransport)
|
|
216
221
|
header = Mock(spec=Header)
|
|
217
222
|
header.element = Mock()
|
|
223
|
+
header.copy.return_value = header
|
|
218
224
|
mock_attach = Mock(spec=MtomAttachment)
|
|
219
225
|
mock_attach.get_cid.return_value = b"test-cid"
|
|
226
|
+
mock_attach.cid = "<test-cid>"
|
|
220
227
|
mock_attach.content_type = "text/plain"
|
|
221
228
|
mock_attachment_func.return_value = [mock_attach]
|
|
222
229
|
mock_zeep_client = Mock(spec=Client)
|
|
@@ -238,6 +245,226 @@ class TestAS4Send:
|
|
|
238
245
|
assert client.send_message([{"content": b"test", "content_type": "text/plain"}]) == "success"
|
|
239
246
|
|
|
240
247
|
|
|
248
|
+
_EB3 = "{http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/}"
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _real_header() -> Header:
|
|
252
|
+
return Header("c1", "type-1", "c2", "type-2", "c3", "type-3", "c4", "type-4")
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _part_hrefs(element) -> list[str]:
|
|
256
|
+
return [part.get("href") for part in element.iter(f"{_EB3}PartInfo")]
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class _FakeClient:
|
|
260
|
+
"""Stands in for zeep.Client and records what one send_message call submitted."""
|
|
261
|
+
|
|
262
|
+
instances: list["_FakeClient"] = []
|
|
263
|
+
lock = threading.Lock()
|
|
264
|
+
|
|
265
|
+
def __init__(self, wsdl, transport, settings, plugins):
|
|
266
|
+
self.wsdl = wsdl
|
|
267
|
+
self.transport = transport
|
|
268
|
+
self.settings = settings
|
|
269
|
+
self.plugins = plugins
|
|
270
|
+
self.submitted: dict = {}
|
|
271
|
+
self.service = SimpleNamespace(submitMessage=self._submit)
|
|
272
|
+
with self.lock:
|
|
273
|
+
self.instances.append(self)
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def get_type(_name):
|
|
277
|
+
return lambda **kwargs: SimpleNamespace(**kwargs)
|
|
278
|
+
|
|
279
|
+
def _submit(self, *, _soapheaders, payload, bodyload):
|
|
280
|
+
self.submitted = {
|
|
281
|
+
"hrefs": _part_hrefs(_soapheaders[0]),
|
|
282
|
+
"payload_ids": [p.payloadId for p in payload],
|
|
283
|
+
"transport_cids": [f"cid:{_norm_cid(f.get_cid())}" for f in self.transport.files],
|
|
284
|
+
}
|
|
285
|
+
return {"messageID": "id-" + "-".join(self.submitted["payload_ids"])}
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
@pytest.fixture
|
|
289
|
+
def fake_client():
|
|
290
|
+
_FakeClient.instances = []
|
|
291
|
+
with patch("pyAS4.AS4Client.Client", _FakeClient):
|
|
292
|
+
yield _FakeClient
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
@pytest.fixture
|
|
296
|
+
def fake_document():
|
|
297
|
+
with patch("pyAS4.AS4Client.Document") as document_class:
|
|
298
|
+
document_class.return_value = Mock(name="document")
|
|
299
|
+
yield document_class
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _payloads(*cids: str) -> list[Payload]:
|
|
303
|
+
return [{"content": f"<{cid}/>", "content_type": "application/xml", "cid": cid} for cid in cids]
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class TestReusableAS4Send:
|
|
307
|
+
def test_wsdl_parsed_once_for_several_calls(self, fake_client, fake_document):
|
|
308
|
+
sender = AS4Send("http://example.com/wsdl", header=_real_header())
|
|
309
|
+
|
|
310
|
+
sender.send_message(_payloads("a"))
|
|
311
|
+
sender.send_message(_payloads("b"))
|
|
312
|
+
|
|
313
|
+
fake_document.assert_called_once()
|
|
314
|
+
assert fake_document.call_args.args[0] == "http://example.com/wsdl"
|
|
315
|
+
assert fake_document.call_args.kwargs["settings"] is sender.settings
|
|
316
|
+
assert all(c.wsdl is fake_document.return_value for c in fake_client.instances)
|
|
317
|
+
|
|
318
|
+
def test_preparsed_document_is_used_as_is(self, fake_client, fake_document):
|
|
319
|
+
document = Mock(spec=Document)
|
|
320
|
+
sender = AS4Send(document, header=_real_header())
|
|
321
|
+
|
|
322
|
+
sender.send_message(_payloads("a"))
|
|
323
|
+
|
|
324
|
+
fake_document.assert_not_called()
|
|
325
|
+
assert fake_client.instances[0].wsdl is document
|
|
326
|
+
|
|
327
|
+
def test_attachments_and_part_info_are_isolated(self, fake_client, fake_document):
|
|
328
|
+
header = _real_header()
|
|
329
|
+
xml_before = header.xml
|
|
330
|
+
sender = AS4Send("http://example.com/wsdl", header=header)
|
|
331
|
+
|
|
332
|
+
sender.send_message(_payloads("first-1", "first-2"))
|
|
333
|
+
sender.send_message(_payloads("second"))
|
|
334
|
+
|
|
335
|
+
first, second = (c.submitted for c in fake_client.instances)
|
|
336
|
+
assert first["hrefs"] == ["cid:first-1", "cid:first-2"]
|
|
337
|
+
assert first["transport_cids"] == ["cid:first-1", "cid:first-2"]
|
|
338
|
+
assert second["hrefs"] == ["cid:second"]
|
|
339
|
+
assert second["payload_ids"] == ["cid:second"]
|
|
340
|
+
assert second["transport_cids"] == ["cid:second"]
|
|
341
|
+
assert header.xml == xml_before
|
|
342
|
+
assert _part_hrefs(header.element) == []
|
|
343
|
+
|
|
344
|
+
def test_header_per_call_is_not_modified(self, fake_client, fake_document):
|
|
345
|
+
sender = AS4Send("http://example.com/wsdl")
|
|
346
|
+
header = _real_header()
|
|
347
|
+
|
|
348
|
+
sender.send_message(_payloads("a"), header=header)
|
|
349
|
+
sender.send_message(_payloads("b"), header=header)
|
|
350
|
+
|
|
351
|
+
assert _part_hrefs(header.element) == []
|
|
352
|
+
assert [c.submitted["hrefs"] for c in fake_client.instances] == [["cid:a"], ["cid:b"]]
|
|
353
|
+
|
|
354
|
+
def test_header_required(self, fake_client, fake_document):
|
|
355
|
+
sender = AS4Send("http://example.com/wsdl")
|
|
356
|
+
|
|
357
|
+
with pytest.raises(RuntimeError, match="Header is required"):
|
|
358
|
+
sender.send_message(_payloads("a"))
|
|
359
|
+
fake_document.assert_not_called()
|
|
360
|
+
|
|
361
|
+
def test_new_transport_per_call_with_shared_session(self, fake_client, fake_document):
|
|
362
|
+
session = Session()
|
|
363
|
+
sender = AS4Send(
|
|
364
|
+
"http://example.com/wsdl",
|
|
365
|
+
header=_real_header(),
|
|
366
|
+
session=session,
|
|
367
|
+
operation_timeout=7,
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
sender.send_message(_payloads("a"))
|
|
371
|
+
sender.send_message(_payloads("b"))
|
|
372
|
+
|
|
373
|
+
first, second = (c.transport for c in fake_client.instances)
|
|
374
|
+
assert isinstance(first, MtomTransport) and isinstance(second, MtomTransport)
|
|
375
|
+
assert first is not second
|
|
376
|
+
assert first.session is session and second.session is session
|
|
377
|
+
assert first.operation_timeout == 7
|
|
378
|
+
|
|
379
|
+
def test_failed_wsdl_load_is_retried(self, fake_client, fake_document):
|
|
380
|
+
fake_document.side_effect = [ConnectionError("domibus down"), Mock(name="document")]
|
|
381
|
+
sender = AS4Send("http://example.com/wsdl", header=_real_header())
|
|
382
|
+
|
|
383
|
+
with pytest.raises(ConnectionError):
|
|
384
|
+
sender.send_message(_payloads("a"))
|
|
385
|
+
assert sender.send_message(_payloads("b")) == {"messageID": "id-cid:b"}
|
|
386
|
+
|
|
387
|
+
assert fake_document.call_count == 2
|
|
388
|
+
assert len(fake_client.instances) == 1
|
|
389
|
+
|
|
390
|
+
def test_parallel_calls_do_not_mix_attachments(self, fake_client, fake_document):
|
|
391
|
+
header = _real_header()
|
|
392
|
+
sender = AS4Send("http://example.com/wsdl", header=header)
|
|
393
|
+
jobs = [[f"m{i}-p{j}" for j in range(i % 3 + 1)] for i in range(40)]
|
|
394
|
+
|
|
395
|
+
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
396
|
+
results = list(pool.map(lambda cids: sender.send_message(_payloads(*cids)), jobs))
|
|
397
|
+
|
|
398
|
+
fake_document.assert_called_once()
|
|
399
|
+
assert results == [{"messageID": "id-" + "-".join(f"cid:{c}" for c in cids)} for cids in jobs]
|
|
400
|
+
submitted = sorted((c.submitted for c in fake_client.instances), key=lambda s: s["payload_ids"])
|
|
401
|
+
expected = sorted(([f"cid:{c}" for c in cids] for cids in jobs))
|
|
402
|
+
assert [s["hrefs"] for s in submitted] == expected
|
|
403
|
+
assert [s["transport_cids"] for s in submitted] == expected
|
|
404
|
+
assert _part_hrefs(header.element) == []
|
|
405
|
+
|
|
406
|
+
def test_legacy_call_with_external_transport(self, fake_client, fake_document):
|
|
407
|
+
session = Session()
|
|
408
|
+
cache = Mock()
|
|
409
|
+
legacy_transport = MtomTransport(cache=cache, timeout=11, operation_timeout=22, session=session)
|
|
410
|
+
legacy_transport.update_headers({"X-Custom": "1"})
|
|
411
|
+
header = _real_header()
|
|
412
|
+
sender = AS4Send("http://example.com/wsdl", legacy_transport, [], header)
|
|
413
|
+
|
|
414
|
+
assert sender.send_message(_payloads("a")) == {"messageID": "id-cid:a"}
|
|
415
|
+
sender.send_message(_payloads("b"))
|
|
416
|
+
|
|
417
|
+
assert legacy_transport.files == []
|
|
418
|
+
assert _part_hrefs(header.element) == []
|
|
419
|
+
transport = fake_client.instances[1].transport
|
|
420
|
+
assert transport is not legacy_transport
|
|
421
|
+
assert transport.session is session
|
|
422
|
+
assert transport.cache is cache
|
|
423
|
+
assert transport.load_timeout == 11
|
|
424
|
+
assert transport.operation_timeout == 22
|
|
425
|
+
assert transport.headers["X-Custom"] == "1"
|
|
426
|
+
assert fake_client.instances[1].submitted["transport_cids"] == ["cid:b"]
|
|
427
|
+
|
|
428
|
+
def test_rejects_non_transport(self):
|
|
429
|
+
with pytest.raises(TypeError):
|
|
430
|
+
AS4Send("http://example.com/wsdl", transport=object()) # type: ignore[arg-type]
|
|
431
|
+
|
|
432
|
+
def test_close_only_closes_own_session(self):
|
|
433
|
+
external = Mock(spec=Session)
|
|
434
|
+
external.adapters = {}
|
|
435
|
+
external.headers = {}
|
|
436
|
+
AS4Send("http://example.com/wsdl", session=external).close()
|
|
437
|
+
external.close.assert_not_called()
|
|
438
|
+
|
|
439
|
+
with patch("pyAS4.AS4Client.Session") as session_class:
|
|
440
|
+
session_class.return_value.adapters = {}
|
|
441
|
+
session_class.return_value.headers = {}
|
|
442
|
+
with AS4Send("http://example.com/wsdl"):
|
|
443
|
+
pass
|
|
444
|
+
session_class.return_value.close.assert_called_once()
|
|
445
|
+
|
|
446
|
+
def test_transport_session_is_not_closed(self):
|
|
447
|
+
session = Mock(spec=Session, adapters={}, headers={})
|
|
448
|
+
AS4Send("http://example.com/wsdl", transport=Transport(session=session)).close()
|
|
449
|
+
session.close.assert_not_called()
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
class TestHeaderCopy:
|
|
453
|
+
def test_copy_is_independent(self):
|
|
454
|
+
header = _real_header()
|
|
455
|
+
header.add_message_property("p1", "v1")
|
|
456
|
+
|
|
457
|
+
clone = header.copy()
|
|
458
|
+
clone.payload_append([{"href": "cid:x", "mimetype": "text/plain"}])
|
|
459
|
+
clone.add_message_property("p2", "v2")
|
|
460
|
+
|
|
461
|
+
assert _part_hrefs(clone.element) == ["cid:x"]
|
|
462
|
+
assert _part_hrefs(header.element) == []
|
|
463
|
+
assert b"p2" not in header.xml
|
|
464
|
+
assert b"p1" in clone.xml
|
|
465
|
+
assert clone.conversationid == header.conversationid
|
|
466
|
+
|
|
467
|
+
|
|
241
468
|
class TestAS4Receive:
|
|
242
469
|
@patch("pyAS4.AS4Client.Client")
|
|
243
470
|
def test_as4receive_can_use_recipient_id_without_header(self, mock_client_class):
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|