asfpy 0.58__tar.gz → 0.60__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.
@@ -1,2 +1,4 @@
1
1
  github:
2
2
  del_branch_on_merge: true
3
+ features:
4
+ issues: true
@@ -15,11 +15,11 @@ jobs:
15
15
  python-version: [3.13]
16
16
 
17
17
  steps:
18
- - uses: actions/checkout@master
18
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
19
19
  with:
20
20
  persist-credentials: false
21
21
  - name: Install uv
22
- uses: astral-sh/setup-uv@61cb8a9741eeb8a550a1b8544337180c0fc8476b # v7.2.0
22
+ uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
23
23
  - name: Set up Python ${{ matrix.python-version }}
24
24
  run: uv python install ${{ matrix.python-version }}
25
25
  - name: Install dependencies
@@ -33,5 +33,5 @@ jobs:
33
33
  - name: Test with mypy
34
34
  if: always()
35
35
  run: |
36
- uv run pip install types-PyYAML types-requests
36
+ uv pip install types-PyYAML types-requests
37
37
  uv run mypy --ignore-missing-imports . # recursive by default
@@ -2,7 +2,7 @@ name: Unit Tests
2
2
 
3
3
  on:
4
4
  push:
5
-
5
+
6
6
  workflow_dispatch:
7
7
 
8
8
  jobs:
@@ -13,19 +13,17 @@ jobs:
13
13
  max-parallel: 4
14
14
  matrix:
15
15
  python-version:
16
- - '3.8'
17
- - '3.9'
18
16
  - '3.10'
19
17
  - '3.11'
20
18
  - '3.12'
21
19
  - '3.13'
22
20
 
23
21
  steps:
24
- - uses: actions/checkout@master
22
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
25
23
  with:
26
24
  persist-credentials: false
27
25
  - name: Install uv
28
- uses: astral-sh/setup-uv@61cb8a9741eeb8a550a1b8544337180c0fc8476b # v7.2.0
26
+ uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
29
27
  - name: Set up Python ${{ matrix.python-version }}
30
28
  run: uv python install ${{ matrix.python-version }}
31
29
  - name: Install dependencies
@@ -1,15 +1,15 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: asfpy
3
- Version: 0.58
3
+ Version: 0.60
4
4
  Summary: ASF Common Python Methods
5
5
  Author-email: ASF Infrastructure <users@infra.apache.org>
6
6
  License-File: LICENSE
7
7
  Classifier: License :: OSI Approved :: Apache Software License
8
8
  Classifier: Programming Language :: Python :: 3
9
- Requires-Python: >=3.9.2
9
+ Requires-Python: >=3.10
10
10
  Requires-Dist: aiohttp<4,>=3.10.5
11
11
  Requires-Dist: cffi>=1.17.1
12
- Requires-Dist: cryptography<47,>=46.0.5
12
+ Requires-Dist: cryptography>=46.0.5
13
13
  Requires-Dist: easydict<2,>=1.13
14
14
  Requires-Dist: ezt<2,>=1.1
15
15
  Requires-Dist: pyyaml<7,>=6.0.2
@@ -360,7 +360,7 @@ class manager:
360
360
  raise ValidatorException("Invalid email address supplied!", 'email')
361
361
 
362
362
  # Set password, b64-encoded crypt of random string
363
- salt_alphabet = string.ascii_letters = string.digits
363
+ salt_alphabet = string.ascii_letters + string.digits
364
364
  salt = ''.join(secrets.choice(salt_alphabet) for _ in range(6))
365
365
  password = ''.join(secrets.choice(salt_alphabet) for _ in range(16))
366
366
  if forcePass:
@@ -38,6 +38,7 @@ import logging
38
38
  import warnings
39
39
 
40
40
  import aiohttp
41
+ from aiohttp.http_exceptions import LineTooLong
41
42
 
42
43
 
43
44
  LOGGER = logging.getLogger(__name__)
@@ -48,6 +49,11 @@ DEFAULT_INACTIVITY_TIMEOUT = 11
48
49
  ### for debug:
49
50
  #DEFAULT_INACTIVITY_TIMEOUT = 4.5
50
51
 
52
+ # Every payload carries a cursor, and the server will replay what it has
53
+ # published since a given one. See PUBSUB_CURSOR_HEADER below.
54
+ PUBSUB_CURSOR_KEY = 'pubsub_cursor'
55
+ PUBSUB_CURSOR_HEADER = 'X-Fetch-Since-Cursor'
56
+
51
57
  # Default read buffer size. Max payload size in pypubsub is 256kb (plus metadata and JSON overhead)
52
58
  DEFAULT_READ_BUFFER_SIZE = 300 * 1024
53
59
 
@@ -68,6 +74,11 @@ async def listen(pubsub_url, username=None, password=None, timeout=None, buffers
68
74
 
69
75
  async with aiohttp.ClientSession(auth=auth, timeout=ct, read_bufsize=buffersize) as session:
70
76
 
77
+ # The cursor of the last payload seen, so that a reconnect can pick up
78
+ # where this one left off rather than silently skipping whatever was
79
+ # published in between.
80
+ cursor = None
81
+
71
82
  # Retry immediately, and then back it off.
72
83
  delay = 0.0
73
84
 
@@ -75,32 +86,61 @@ async def listen(pubsub_url, username=None, password=None, timeout=None, buffers
75
86
  while True:
76
87
  LOGGER.debug('Opening new connection...')
77
88
  try:
78
- async for payload in _process_connection(session, pubsub_url):
79
- if not payload:
80
- pass ### tbd?: event loop killed or hit EOF
81
-
89
+ async for payload in _process_connection(session, pubsub_url, cursor):
82
90
  # We got a payload, so reset the DELAY.
83
91
  delay = 0.0
84
92
 
93
+ # Keepalives carry no cursor, and leave this one where it is.
94
+ if isinstance(payload, dict):
95
+ cursor = payload.get(PUBSUB_CURSOR_KEY, cursor)
96
+
85
97
  yield payload
86
98
 
99
+ LOGGER.info(f'Connection closed, reconnecting in {delay} seconds')
100
+
87
101
  except (ConnectionRefusedError,
88
- aiohttp.ClientConnectorError,
89
- aiohttp.ServerTimeoutError,
102
+ # ClientConnectionError covers the ways a connection can
103
+ # break: the server hung up (ServerDisconnectedError), the
104
+ # peer reset it (ClientOSError), we could not reach it
105
+ # (ClientConnectorError), or it went quiet past the
106
+ # inactivity timeout (ServerTimeoutError).
107
+ aiohttp.ClientConnectionError,
108
+ # The server answered, but not with a stream of payloads.
109
+ aiohttp.ClientResponseError,
90
110
  aiohttp.ClientPayloadError,
91
111
  ) as e:
92
112
  LOGGER.error(f'Connection failed ({type(e).__name__}: {e})'
93
113
  f', reconnecting in {delay} seconds')
94
- await asyncio.sleep(delay)
95
114
 
96
- # Back off on the delay. Step it up from 0s, doubling each
97
- # time, and top out at 30s retry. Steps: 0, 2, 6, 14, 30.
98
- delay = min(30.0, (delay + 1.0) * 2)
115
+ # However this connection ended, wait before opening the next one.
116
+ await asyncio.sleep(delay)
117
+
118
+ # Back off on the delay. Step it up from 0s, doubling each
119
+ # time, and top out at 30s retry. Steps: 0, 2, 6, 14, 30.
120
+ delay = min(30.0, (delay + 1.0) * 2)
121
+
99
122
 
123
+ async def _process_connection(session, pubsub_url, cursor=None):
124
+ # Connect to pubsub and listen for payloads. This generator ends when the
125
+ # connection does, leaving it to the caller to open the next one.
100
126
 
101
- async def _process_connection(session, pubsub_url):
102
- # Connect to pubsub and listen for payloads.
103
- async with session.get(pubsub_url) as conn:
127
+ # Asking to resume from a cursor the server no longer holds is not an
128
+ # error: it simply has nothing to replay, and the stream starts from now.
129
+ headers = {PUBSUB_CURSOR_HEADER: cursor} if cursor else None
130
+
131
+ async with session.get(pubsub_url, headers=headers) as conn:
132
+
133
+ # A non-200 has a body too, and it is not a stream of payloads.
134
+ # raise_for_status() only rejects 4xx/5xx, so reject the rest --
135
+ # a 204, a 201 with a body -- explicitly.
136
+ if conn.status != 200:
137
+ raise aiohttp.ClientResponseError(
138
+ conn.request_info,
139
+ conn.history,
140
+ status=conn.status,
141
+ message=conn.reason,
142
+ headers=conn.headers,
143
+ )
104
144
 
105
145
  #print('LIMITS:', conn.content.get_read_buffer_limits())
106
146
 
@@ -117,15 +157,28 @@ async def _process_connection(session, pubsub_url):
117
157
  # ignores it.
118
158
  try:
119
159
  raw = await conn.content.readuntil(b'\n')
120
- except ValueError as e:
160
+ except (ValueError, LineTooLong) as e:
161
+ # A line past the read buffer raises LineTooLong rather than
162
+ # ValueError, and neither is a connection error: both mean this
163
+ # stream cannot be read, so end it and let the caller reconnect.
121
164
  LOGGER.error(f'Saw "{e}"; re-raising as ClientPayloadError to close/reconnect')
122
- raise aiohttp.ClientPayloadError('re-raised from ValueError in readuntil()')
165
+ raise aiohttp.ClientPayloadError(f're-raised from {type(e).__name__} in readuntil()') from e
166
+
167
+ if not raw.endswith(b'\n'):
168
+ # At EOF, readuntil() returns what it has rather than raising:
169
+ # nothing, if the stream ended between payloads, or a partial
170
+ # payload, if the server went away part-way through writing one.
171
+ # Either way, there is nothing further to read here.
172
+ LOGGER.debug('Hit EOF; closing the connection.')
173
+ return
123
174
 
124
- if not raw:
125
- # We just hit EOF.
126
- yield None
175
+ try:
176
+ payload = json.loads(raw)
177
+ except ValueError as e:
178
+ LOGGER.error(f'Saw "{e}"; re-raising as ClientPayloadError to close/reconnect')
179
+ raise aiohttp.ClientPayloadError('re-raised from ValueError in json.loads()') from e
127
180
 
128
- yield json.loads(raw)
181
+ yield payload
129
182
 
130
183
 
131
184
  def test_listening():
@@ -1,7 +1,6 @@
1
1
  import time
2
2
  import logging
3
3
  import inspect
4
- import asyncio
5
4
  import functools
6
5
 
7
6
  class Stopwatch:
@@ -27,7 +26,7 @@ class Stopwatch:
27
26
  if self.name is None:
28
27
  self.name = f"Function '{func.__name__}'"
29
28
  # Check if the function is async
30
- if asyncio.iscoroutinefunction(func):
29
+ if inspect.iscoroutinefunction(func):
31
30
  @functools.wraps(func)
32
31
  async def async_wrapper(*args, **kwargs):
33
32
  self.start_time = time.time() # Reset start_time at function call
@@ -24,6 +24,9 @@ print("Hello, world!") # prints to syslog
24
24
 
25
25
  print = asfpy.syslog.Printer(stdout=True)
26
26
  print("Hello!!") # print to syslog AND stdout
27
+
28
+ print = asfpy.syslog.Printer(stderr=True)
29
+ print("Hello!!") # print to syslog AND stderr
27
30
  """
28
31
  import syslog
29
32
  import os
@@ -32,6 +35,7 @@ import sys
32
35
  class Printer:
33
36
  def __init__(self, **kwargs):
34
37
  self.copy_to_stdout = kwargs.get('stdout')
38
+ self.copy_to_stderr = kwargs.get('stderr')
35
39
  log_options = 0
36
40
  log_ident = kwargs.get('identity', os.path.basename(sys.argv[0]))
37
41
  facility = syslog.LOG_USER
@@ -44,4 +48,6 @@ class Printer:
44
48
  syslog.syslog(line)
45
49
  if self.copy_to_stdout:
46
50
  print(*args)
51
+ if self.copy_to_stderr:
52
+ print(*args, file=sys.stderr)
47
53
 
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "asfpy"
3
- version = "0.58"
3
+ version = "0.60"
4
4
  description = "ASF Common Python Methods"
5
5
  authors = [{name = "ASF Infrastructure", email = "users@infra.apache.org"}]
6
6
  readme = "README.md"
7
- requires-python = ">=3.9.2"
7
+ requires-python = ">=3.10"
8
8
  classifiers = [
9
9
  "License :: OSI Approved :: Apache Software License",
10
10
  "Programming Language :: Python :: 3",
@@ -12,7 +12,7 @@ classifiers = [
12
12
  dependencies = [
13
13
  "aiohttp>=3.10.5,<4",
14
14
  "cffi>=1.17.1",
15
- "cryptography>=46.0.5,<47",
15
+ "cryptography>=46.0.5",
16
16
  "easydict>=1.13,<2",
17
17
  "ezt>=1.1,<2",
18
18
  "pyyaml>=6.0.2,<7",