jsocket 1.9.6__tar.gz → 2.0.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.
Files changed (27) hide show
  1. jsocket-2.0.0/PKG-INFO +369 -0
  2. {jsocket-1.9.6 → jsocket-2.0.0}/README.md +3 -1
  3. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket/_version.py +1 -1
  4. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket/jsocket_base.py +87 -19
  5. jsocket-2.0.0/jsocket.egg-info/PKG-INFO +369 -0
  6. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket.egg-info/SOURCES.txt +2 -1
  7. {jsocket-1.9.6 → jsocket-2.0.0}/pyproject.toml +2 -2
  8. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_integration_failures.py +105 -2
  9. jsocket-2.0.0/tests/test_unit_coverage.py +563 -0
  10. jsocket-1.9.6/PKG-INFO +0 -166
  11. jsocket-1.9.6/jsocket.egg-info/PKG-INFO +0 -166
  12. {jsocket-1.9.6 → jsocket-2.0.0}/LICENSE +0 -0
  13. {jsocket-1.9.6 → jsocket-2.0.0}/MANIFEST.in +0 -0
  14. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket/__init__.py +0 -0
  15. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket/tserver.py +0 -0
  16. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket.egg-info/dependency_links.txt +0 -0
  17. {jsocket-1.9.6 → jsocket-2.0.0}/jsocket.egg-info/top_level.txt +0 -0
  18. {jsocket-1.9.6 → jsocket-2.0.0}/setup.cfg +0 -0
  19. {jsocket-1.9.6 → jsocket-2.0.0}/setup.py +0 -0
  20. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_additional_coverage.py +0 -0
  21. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_e2e.py +0 -0
  22. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_listener_persistence.py +0 -0
  23. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_reconnect_perf.py +0 -0
  24. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_reconnect_restart.py +0 -0
  25. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_server_stats.py +0 -0
  26. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_serverfactory_concurrent.py +0 -0
  27. {jsocket-1.9.6 → jsocket-2.0.0}/tests/test_serverfactory_serialization.py +0 -0
jsocket-2.0.0/PKG-INFO ADDED
@@ -0,0 +1,369 @@
1
+ Metadata-Version: 2.4
2
+ Name: jsocket
3
+ Version: 2.0.0
4
+ Summary: Python JSON Server & Client
5
+ Author-email: Christopher Piekarski <chris@cpiekarski.com>
6
+ Maintainer-email: Christopher Piekarski <chris@cpiekarski.com>
7
+ License: Apache License
8
+ Version 2.0, January 2004
9
+ http://www.apache.org/licenses/
10
+
11
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
12
+
13
+ 1. Definitions.
14
+
15
+ "License" shall mean the terms and conditions for use, reproduction,
16
+ and distribution as defined by Sections 1 through 9 of this document.
17
+
18
+ "Licensor" shall mean the copyright owner or entity authorized by
19
+ the copyright owner that is granting the License.
20
+
21
+ "Legal Entity" shall mean the union of the acting entity and all
22
+ other entities that control, are controlled by, or are under common
23
+ control with that entity. For the purposes of this definition,
24
+ "control" means (i) the power, direct or indirect, to cause the
25
+ direction or management of such entity, whether by contract or
26
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
27
+ outstanding shares, or (iii) beneficial ownership of such entity.
28
+
29
+ "You" (or "Your") shall mean an individual or Legal Entity
30
+ exercising permissions granted by this License.
31
+
32
+ "Source" form shall mean the preferred form for making modifications,
33
+ including but not limited to software source code, documentation
34
+ source, and configuration files.
35
+
36
+ "Object" form shall mean any form resulting from mechanical
37
+ transformation or translation of a Source form, including but
38
+ not limited to compiled object code, generated documentation,
39
+ and conversions to other media types.
40
+
41
+ "Work" shall mean the work of authorship, whether in Source or
42
+ Object form, made available under the License, as indicated by a
43
+ copyright notice that is included in or attached to the work
44
+ (an example is provided in the Appendix below).
45
+
46
+ "Derivative Works" shall mean any work, whether in Source or Object
47
+ form, that is based on (or derived from) the Work and for which the
48
+ editorial revisions, annotations, elaborations, or other modifications
49
+ represent, as a whole, an original work of authorship. For the purposes
50
+ of this License, Derivative Works shall not include works that remain
51
+ separable from, or merely link (or bind by name) to the interfaces of,
52
+ the Work and Derivative Works thereof.
53
+
54
+ "Contribution" shall mean any work of authorship, including
55
+ the original version of the Work and any modifications or additions
56
+ to that Work or Derivative Works thereof, that is intentionally
57
+ submitted to Licensor for inclusion in the Work by the copyright owner
58
+ or by an individual or Legal Entity authorized to submit on behalf of
59
+ the copyright owner. For the purposes of this definition, "submitted"
60
+ means any form of electronic, verbal, or written communication sent
61
+ to the Licensor or its representatives, including but not limited to
62
+ communication on electronic mailing lists, source code control systems,
63
+ and issue tracking systems that are managed by, or on behalf of, the
64
+ Licensor for the purpose of discussing and improving the Work, but
65
+ excluding communication that is conspicuously marked or otherwise
66
+ designated in writing by the copyright owner as "Not a Contribution."
67
+
68
+ "Contributor" shall mean Licensor and any individual or Legal Entity
69
+ on behalf of whom a Contribution has been received by Licensor and
70
+ subsequently incorporated within the Work.
71
+
72
+ 2. Grant of Copyright License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ copyright license to reproduce, prepare Derivative Works of,
76
+ publicly display, publicly perform, sublicense, and distribute the
77
+ Work and such Derivative Works in Source or Object form.
78
+
79
+ 3. Grant of Patent License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ (except as stated in this section) patent license to make, have made,
83
+ use, offer to sell, sell, import, and otherwise transfer the Work,
84
+ where such license applies only to those patent claims licensable
85
+ by such Contributor that are necessarily infringed by their
86
+ Contribution(s) alone or by combination of their Contribution(s)
87
+ with the Work to which such Contribution(s) was submitted. If You
88
+ institute patent litigation against any entity (including a
89
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
90
+ or a Contribution incorporated within the Work constitutes direct
91
+ or contributory patent infringement, then any patent licenses
92
+ granted to You under this License for that Work shall terminate
93
+ as of the date such litigation is filed.
94
+
95
+ 4. Redistribution. You may reproduce and distribute copies of the
96
+ Work or Derivative Works thereof in any medium, with or without
97
+ modifications, and in Source or Object form, provided that You
98
+ meet the following conditions:
99
+
100
+ (a) You must give any other recipients of the Work or
101
+ Derivative Works a copy of this License; and
102
+
103
+ (b) You must cause any modified files to carry prominent notices
104
+ stating that You changed the files; and
105
+
106
+ (c) You must retain, in the Source form of any Derivative Works
107
+ that You distribute, all copyright, patent, trademark, and
108
+ attribution notices from the Source form of the Work,
109
+ excluding those notices that do not pertain to any part of
110
+ the Derivative Works; and
111
+
112
+ (d) If the Work includes a "NOTICE" text file as part of its
113
+ distribution, then any Derivative Works that You distribute must
114
+ include a readable copy of the attribution notices contained
115
+ within such NOTICE file, excluding those notices that do not
116
+ pertain to any part of the Derivative Works, in at least one
117
+ of the following places: within a NOTICE text file distributed
118
+ as part of the Derivative Works; within the Source form or
119
+ documentation, if provided along with the Derivative Works; or,
120
+ within a display generated by the Derivative Works, if and
121
+ wherever such third-party notices normally appear. The contents
122
+ of the NOTICE file are for informational purposes only and
123
+ do not modify the License. You may add Your own attribution
124
+ notices within Derivative Works that You distribute, alongside
125
+ or as an addendum to the NOTICE text from the Work, provided
126
+ that such additional attribution notices cannot be construed
127
+ as modifying the License.
128
+
129
+ You may add Your own copyright statement to Your modifications and
130
+ may provide additional or different license terms and conditions
131
+ for use, reproduction, or distribution of Your modifications, or
132
+ for any such Derivative Works as a whole, provided Your use,
133
+ reproduction, and distribution of the Work otherwise complies with
134
+ the conditions stated in this License.
135
+
136
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
137
+ any Contribution intentionally submitted for inclusion in the Work
138
+ by You to the Licensor shall be under the terms and conditions of
139
+ this License, without any additional terms or conditions.
140
+ Notwithstanding the above, nothing herein shall supersede or modify
141
+ the terms of any separate license agreement you may have executed
142
+ with Licensor regarding such Contributions.
143
+
144
+ 6. Trademarks. This License does not grant permission to use the trade
145
+ names, trademarks, service marks, or product names of the Licensor,
146
+ except as required for reasonable and customary use in describing the
147
+ origin of the Work and reproducing the content of the NOTICE file.
148
+
149
+ 7. Disclaimer of Warranty. Unless required by applicable law or
150
+ agreed to in writing, Licensor provides the Work (and each
151
+ Contributor provides its Contributions) on an "AS IS" BASIS,
152
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
153
+ implied, including, without limitation, any warranties or conditions
154
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
155
+ PARTICULAR PURPOSE. You are solely responsible for determining the
156
+ appropriateness of using or redistributing the Work and assume any
157
+ risks associated with Your exercise of permissions under this License.
158
+
159
+ 8. Limitation of Liability. In no event and under no legal theory,
160
+ whether in tort (including negligence), contract, or otherwise,
161
+ unless required by applicable law (such as deliberate and grossly
162
+ negligent acts) or agreed to in writing, shall any Contributor be
163
+ liable to You for damages, including any direct, indirect, special,
164
+ incidental, or consequential damages of any character arising as a
165
+ result of this License or out of the use or inability to use the
166
+ Work (including but not limited to damages for loss of goodwill,
167
+ work stoppage, computer failure or malfunction, or any and all
168
+ other commercial damages or losses), even if such Contributor
169
+ has been advised of the possibility of such damages.
170
+
171
+ 9. Accepting Warranty or Additional Liability. While redistributing
172
+ the Work or Derivative Works thereof, You may choose to offer,
173
+ and charge a fee for, acceptance of support, warranty, indemnity,
174
+ or other liability obligations and/or rights consistent with this
175
+ License. However, in accepting such obligations, You may act only
176
+ on Your own behalf and on Your sole responsibility, not on behalf
177
+ of any other Contributor, and only if You agree to indemnify,
178
+ defend, and hold each Contributor harmless for any liability
179
+ incurred by, or claims asserted against, such Contributor by reason
180
+ of your accepting any such warranty or additional liability.
181
+
182
+ END OF TERMS AND CONDITIONS
183
+
184
+ APPENDIX: How to apply the Apache License to your work.
185
+
186
+ To apply the Apache License to your work, attach the following
187
+ boilerplate notice, with the fields enclosed by brackets "[]"
188
+ replaced with your own identifying information. (Don't include
189
+ the brackets!) The text should be enclosed in the appropriate
190
+ comment syntax for the file format. We also recommend that a
191
+ file or class name and description of purpose be included on the
192
+ same "printed page" as the copyright notice for easier
193
+ identification within third-party archives.
194
+
195
+ Copyright [2011] [Christopher Piekarski]
196
+
197
+ Licensed under the Apache License, Version 2.0 (the "License");
198
+ you may not use this file except in compliance with the License.
199
+ You may obtain a copy of the License at
200
+
201
+ http://www.apache.org/licenses/LICENSE-2.0
202
+
203
+ Unless required by applicable law or agreed to in writing, software
204
+ distributed under the License is distributed on an "AS IS" BASIS,
205
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
206
+ See the License for the specific language governing permissions and
207
+ limitations under the License.
208
+
209
+ Project-URL: Homepage, https://cpiekarski.com/2012/01/25/python-json-client-server-redux/
210
+ Keywords: json,socket,server,client
211
+ Classifier: Intended Audience :: Developers
212
+ Classifier: Programming Language :: Python :: 3.9
213
+ Classifier: Operating System :: OS Independent
214
+ Classifier: Development Status :: 5 - Production/Stable
215
+ Classifier: Topic :: System :: Networking
216
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
217
+ Classifier: Topic :: System :: Distributed Computing
218
+ Classifier: Topic :: System :: Hardware :: Symmetric Multi-processing
219
+ Requires-Python: >=3.8
220
+ Description-Content-Type: text/markdown
221
+ License-File: LICENSE
222
+ Dynamic: license-file
223
+
224
+ python-json-socket (jsocket)
225
+ ============================
226
+
227
+ [![CI](https://github.com/chris-piekarski/python-json-socket/actions/workflows/ci.yml/badge.svg)](https://github.com/chris-piekarski/python-json-socket/actions/workflows/ci.yml)
228
+ ![PyPI](https://img.shields.io/pypi/v/jsocket.svg)
229
+ ![Python Versions](https://img.shields.io/pypi/pyversions/jsocket.svg)
230
+ ![License](https://img.shields.io/pypi/l/jsocket.svg)
231
+
232
+ Simple JSON-over-TCP sockets for Python. This library provides:
233
+
234
+ - JsonClient/JsonServer: length‑prefixed JSON message framing over TCP
235
+ - ThreadedServer: a single-connection server running in its own thread
236
+ - ServerFactory/ServerFactoryThread: a per‑connection worker model for multiple clients
237
+
238
+ It aims to be small, predictable, and easy to integrate in tests or small services.
239
+
240
+
241
+ Install
242
+ -------
243
+
244
+ ```
245
+ pip install jsocket
246
+ ```
247
+
248
+ Requires Python 3.8+.
249
+
250
+
251
+ Quickstart
252
+ ----------
253
+
254
+ Echo server with `ThreadedServer` and a client:
255
+
256
+ ```python
257
+ import time
258
+ import jsocket
259
+
260
+ class Echo(jsocket.ThreadedServer):
261
+ def __init__(self, **kwargs):
262
+ super().__init__(**kwargs)
263
+ self.timeout = 2.0
264
+
265
+ # Return a dict to send a response back to the client
266
+ def _process_message(self, obj):
267
+ if isinstance(obj, dict) and 'echo' in obj:
268
+ return obj
269
+ return None
270
+
271
+ # Bind to an ephemeral port (port=0)
272
+ server = Echo(address='127.0.0.1', port=0)
273
+ _, port = server.socket.getsockname()
274
+ server.start()
275
+
276
+ client = jsocket.JsonClient(address='127.0.0.1', port=port)
277
+ assert client.connect() is True
278
+
279
+ payload = {"echo": "hello"}
280
+ client.send_obj(payload)
281
+ assert client.read_obj() == payload
282
+
283
+ client.close()
284
+ server.stop()
285
+ server.join()
286
+ ```
287
+
288
+ Per‑connection workers with `ServerFactory`:
289
+
290
+ ```python
291
+ import jsocket
292
+
293
+ class Worker(jsocket.ServerFactoryThread):
294
+ def __init__(self):
295
+ super().__init__()
296
+ self.timeout = 2.0
297
+
298
+ def _process_message(self, obj):
299
+ if isinstance(obj, dict) and 'message' in obj:
300
+ return {"reply": f"got: {obj['message']}"}
301
+
302
+ server = jsocket.ServerFactory(Worker, address='127.0.0.1', port=5489)
303
+ server.start()
304
+ # Connect one or more clients; one Worker is spawned per connection
305
+ ```
306
+
307
+
308
+ API Highlights
309
+ --------------
310
+
311
+ - JsonClient:
312
+ - `connect()` returns True on success
313
+ - `send_obj(dict)` sends a JSON object
314
+ - `read_obj()` blocks until a full message is received; raises `socket.timeout` or `RuntimeError("socket connection broken")`
315
+ - `timeout` property controls socket timeouts
316
+
317
+ - ThreadedServer:
318
+ - Subclass and implement `_process_message(self, obj) -> Optional[dict]`
319
+ - Return a dict to send a response; return `None` to send nothing
320
+ - `start()`, `stop()`, `join()` manage the server thread
321
+ - `send_obj(dict)` sends to the currently connected client
322
+
323
+ - ServerFactory / ServerFactoryThread:
324
+ - `ServerFactoryThread` is a worker that handles one client connection
325
+ - `ServerFactory` accepts connections and spawns a worker per client
326
+
327
+
328
+ Examples and Tests
329
+ ------------------
330
+
331
+ - Examples: see `examples/example_servers.py` and `scripts/smoke_test.py`
332
+ - Pytest: end-to-end and listener tests under `tests/`
333
+ - Run: `pytest -q`
334
+
335
+
336
+ Behavior-Driven Tests (Behave)
337
+ ------------------------------
338
+
339
+ - Steps live under `features/steps/` and environment hooks in `features/environment.py`.
340
+ - To run Behave scenarios, add one or more `.feature` files under `features/` and run:
341
+ - `pip install -r requirements-dev.txt`
342
+ - `PYTHONPATH=. behave -f progress2`
343
+ - A minimal example feature:
344
+
345
+ ```gherkin
346
+ Feature: Echo round-trip
347
+ Scenario: client/server echo
348
+ Given I start the server
349
+ And I connect the client
350
+ When the client sends the object {"echo": "hi"}
351
+ Then the client sees a message {"echo": "hi"}
352
+ ```
353
+
354
+
355
+ Notes
356
+ -----
357
+
358
+ - Breaking change: version 2.0.0 uses a new framing header (magic + length + CRC32). v1 clients are incompatible.
359
+ - Message framing uses a 12‑byte header: 4‑byte magic, 4‑byte big‑endian length, and 4‑byte CRC32 of the payload, followed by a JSON payload encoded as UTF‑8.
360
+ - `max_message_size` defaults to 10MB; set `.max_message_size` to adjust or set to `None` to disable.
361
+ - On disconnect, reads raise `RuntimeError("socket connection broken")` so callers can distinguish cleanly from timeouts.
362
+ - Binding with `port=0` lets the OS choose an ephemeral port; find it with `server.socket.getsockname()`.
363
+
364
+
365
+ Links
366
+ -----
367
+
368
+ - PyPI: https://pypi.org/project/jsocket/
369
+ - License: see `LICENSE`
@@ -132,7 +132,9 @@ Behavior-Driven Tests (Behave)
132
132
  Notes
133
133
  -----
134
134
 
135
- - Message framing uses a 4‑byte big‑endian length header followed by a JSON payload encoded as UTF‑8.
135
+ - Breaking change: version 2.0.0 uses a new framing header (magic + length + CRC32). v1 clients are incompatible.
136
+ - Message framing uses a 12‑byte header: 4‑byte magic, 4‑byte big‑endian length, and 4‑byte CRC32 of the payload, followed by a JSON payload encoded as UTF‑8.
137
+ - `max_message_size` defaults to 10MB; set `.max_message_size` to adjust or set to `None` to disable.
136
138
  - On disconnect, reads raise `RuntimeError("socket connection broken")` so callers can distinguish cleanly from timeouts.
137
139
  - Binding with `port=0` lets the OS choose an ephemeral port; find it with `server.socket.getsockname()`.
138
140
 
@@ -1,3 +1,3 @@
1
1
  """Package version."""
2
2
 
3
- __version__ = "1.9.6"
3
+ __version__ = "2.0.0"
@@ -24,11 +24,21 @@ import socket
24
24
  import struct
25
25
  import logging
26
26
  import time
27
+ import zlib
27
28
 
28
29
  from ._version import __version__
29
30
 
30
31
  logger = logging.getLogger("jsocket")
31
32
 
33
+ FRAME_MAGIC = b"JSN1"
34
+ FRAME_HEADER_FMT = "!4sII"
35
+ FRAME_HEADER_SIZE = struct.calcsize(FRAME_HEADER_FMT)
36
+ DEFAULT_MAX_MESSAGE_SIZE = 10 * 1024 * 1024
37
+
38
+
39
+ class FramingError(RuntimeError):
40
+ """Raised when a message fails framing or integrity checks."""
41
+
32
42
 
33
43
  def _socket_fileno(sock):
34
44
  try:
@@ -40,12 +50,14 @@ def _socket_fileno(sock):
40
50
  class JsonSocket:
41
51
  """Lightweight JSON-over-TCP socket wrapper with length-prefixed framing."""
42
52
 
43
- def __init__(self, address='127.0.0.1', port=5489, timeout=2.0):
53
+ def __init__(self, address='127.0.0.1', port=5489, timeout=2.0, max_message_size=DEFAULT_MAX_MESSAGE_SIZE):
44
54
  self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
45
55
  self.conn = self.socket
46
56
  self._timeout = timeout
47
57
  self._address = address
48
58
  self._port = port
59
+ self._max_message_size = None
60
+ self.max_message_size = max_message_size
49
61
  self._last_client_addr = None
50
62
  # Ensure the primary socket respects timeout for accept/connect operations
51
63
  self.socket.settimeout(self._timeout)
@@ -55,11 +67,12 @@ class JsonSocket:
55
67
  msg = json.dumps(obj, ensure_ascii=False)
56
68
  if self.socket:
57
69
  payload = msg.encode('utf-8')
58
- frmt = f"={len(payload)}s"
59
- packed_msg = struct.pack(frmt, payload)
60
- packed_hdr = struct.pack('!I', len(packed_msg))
70
+ if self._max_message_size is not None and len(payload) > self._max_message_size:
71
+ raise ValueError(f"message exceeds max_message_size ({len(payload)} > {self._max_message_size})")
72
+ checksum = zlib.crc32(payload) & 0xFFFFFFFF
73
+ packed_hdr = struct.pack(FRAME_HEADER_FMT, FRAME_MAGIC, len(payload), checksum)
61
74
  self._send(packed_hdr)
62
- self._send(packed_msg)
75
+ self._send(payload)
63
76
 
64
77
  def _send(self, msg):
65
78
  """Send all bytes in `msg` to the peer."""
@@ -67,29 +80,53 @@ class JsonSocket:
67
80
  while sent < len(msg):
68
81
  sent += self.conn.send(msg[sent:])
69
82
 
70
- def _read(self, size):
83
+ def _read(self, size, allow_timeout=False):
71
84
  """Read exactly `size` bytes from the peer or raise on disconnect."""
72
85
  data = b''
73
86
  while len(data) < size:
74
- data_tmp = self.conn.recv(size - len(data))
75
- data += data_tmp
87
+ try:
88
+ data_tmp = self.conn.recv(size - len(data))
89
+ except socket.timeout:
90
+ if allow_timeout and not data:
91
+ raise
92
+ self._close_connection()
93
+ raise FramingError("socket read timeout during message")
76
94
  if data_tmp == b'':
95
+ self._close_connection()
77
96
  raise RuntimeError("socket connection broken")
97
+ data += data_tmp
78
98
  return data
79
99
 
80
- def _msg_length(self):
81
- """Read and unpack the 4-byte big-endian length header."""
82
- d = self._read(4)
83
- s = struct.unpack('!I', d)
84
- return s[0]
100
+ def _read_header(self):
101
+ """Read and unpack the framing header."""
102
+ header = self._read(FRAME_HEADER_SIZE, allow_timeout=True)
103
+ magic, size, checksum = struct.unpack(FRAME_HEADER_FMT, header)
104
+ if magic != FRAME_MAGIC:
105
+ self._close_connection()
106
+ raise FramingError("invalid message header magic")
107
+ if self._max_message_size is not None and size > self._max_message_size:
108
+ self._close_connection()
109
+ raise FramingError(f"message length {size} exceeds max_message_size {self._max_message_size}")
110
+ return size, checksum
85
111
 
86
112
  def read_obj(self):
87
113
  """Read a full message and decode it as JSON, returning a Python object."""
88
- size = self._msg_length()
114
+ size, checksum = self._read_header()
89
115
  data = self._read(size)
90
- frmt = f"={size}s"
91
- msg = struct.unpack(frmt, data)
92
- return json.loads(msg[0].decode('utf-8'))
116
+ actual = zlib.crc32(data) & 0xFFFFFFFF
117
+ if actual != checksum:
118
+ self._close_connection()
119
+ raise FramingError("message checksum mismatch")
120
+ try:
121
+ decoded = data.decode('utf-8')
122
+ except UnicodeDecodeError as e:
123
+ self._close_connection()
124
+ raise FramingError("invalid UTF-8 payload") from e
125
+ try:
126
+ return json.loads(decoded)
127
+ except json.JSONDecodeError as e:
128
+ self._close_connection()
129
+ raise FramingError("invalid JSON payload") from e
93
130
 
94
131
  def close(self):
95
132
  """Close active connection and the listening socket if open."""
@@ -118,10 +155,10 @@ class JsonSocket:
118
155
  pass
119
156
 
120
157
  def _close_connection(self):
121
- """Best-effort shutdown and close of the accepted connection socket."""
158
+ """Best-effort shutdown and close of the connection socket."""
122
159
  logger.debug("closing connection socket (fd=%s)", _socket_fileno(self.conn))
123
160
  try:
124
- if self.conn and self.conn is not self.socket and self.conn.fileno() != -1:
161
+ if self.conn and self.conn.fileno() != -1:
125
162
  try:
126
163
  self.conn.shutdown(socket.SHUT_RDWR)
127
164
  except OSError:
@@ -158,9 +195,24 @@ class JsonSocket:
158
195
  """No-op: port is read-only after initialization."""
159
196
  return None
160
197
 
198
+ def _get_max_message_size(self):
199
+ """Get the maximum allowed message size in bytes."""
200
+ return self._max_message_size
201
+
202
+ def _set_max_message_size(self, size):
203
+ """Set the maximum allowed message size in bytes."""
204
+ if size is None:
205
+ self._max_message_size = None
206
+ return
207
+ size = int(size)
208
+ if size <= 0:
209
+ raise ValueError("max_message_size must be positive")
210
+ self._max_message_size = size
211
+
161
212
  timeout = property(_get_timeout, _set_timeout, doc='Get/set the socket timeout')
162
213
  address = property(_get_address, _set_address, doc='read only property socket address')
163
214
  port = property(_get_port, _set_port, doc='read only property socket port')
215
+ max_message_size = property(_get_max_message_size, _set_max_message_size, doc='Get/set max message size in bytes')
164
216
 
165
217
 
166
218
  class JsonServer(JsonSocket):
@@ -170,6 +222,22 @@ class JsonServer(JsonSocket):
170
222
  super().__init__(address, port)
171
223
  self._bind()
172
224
 
225
+ def _close_connection(self):
226
+ """Best-effort shutdown and close of the accepted connection socket."""
227
+ logger.debug("closing connection socket (fd=%s)", _socket_fileno(self.conn))
228
+ try:
229
+ if self.conn and self.conn is not self.socket and self.conn.fileno() != -1:
230
+ try:
231
+ self.conn.shutdown(socket.SHUT_RDWR)
232
+ except OSError:
233
+ pass
234
+ try:
235
+ self.conn.close()
236
+ except OSError:
237
+ pass
238
+ except OSError:
239
+ pass
240
+
173
241
  def _bind(self):
174
242
  self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
175
243
  self.socket.bind((self.address, self.port))