rabbitmq-fxmacrodata 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,168 @@
1
+ """Publish public FXMacroData responses to a customer-owned RabbitMQ exchange."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import hashlib
7
+ import json
8
+ import math
9
+ import re
10
+ from typing import Any
11
+
12
+ import pika
13
+ from fxmacrodata_platform_core import read
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ COLUMNS = (
18
+ "operation", "source_url", "record_id", "currency", "indicator", "date",
19
+ "announcement_datetime", "value", "value_text", "record_json", "response_json",
20
+ "content_hash",
21
+ )
22
+ HEADERS = ("operation", "record_id", "content_hash", "source_url")
23
+ MAX_MESSAGE_BYTES = 16 * 1024 * 1024
24
+ _NAME = re.compile(r"[A-Za-z0-9_.:-]{0,255}\Z")
25
+
26
+
27
+ class PublishError(RuntimeError):
28
+ """A destination publish failed; inspect the destination before retrying."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class PublishResult:
33
+ destination: str
34
+ messages: int
35
+ batches: int
36
+
37
+
38
+ def _destination(destination: Any) -> tuple[str, str]:
39
+ if not isinstance(destination, tuple) or len(destination) != 2:
40
+ raise ValueError("destination must be an (exchange, routing_key) tuple")
41
+ exchange, routing_key = destination
42
+ if not isinstance(exchange, str) or not isinstance(routing_key, str):
43
+ raise ValueError("exchange and routing_key must be strings")
44
+ if not _NAME.fullmatch(exchange) or not _NAME.fullmatch(routing_key):
45
+ raise ValueError("exchange and routing_key accept letters, digits, '_', '.', ':' and '-' only")
46
+ if not exchange and not routing_key:
47
+ raise ValueError("the default exchange requires a routing_key naming the queue")
48
+ return exchange, routing_key
49
+
50
+
51
+ def _bounds(batch_size: int, max_message_bytes: int, confirm: bool) -> None:
52
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or not 1 <= batch_size <= 10000:
53
+ raise ValueError("batch_size must be an integer between 1 and 10000")
54
+ if isinstance(max_message_bytes, bool) or not isinstance(max_message_bytes, int) or not 1 <= max_message_bytes <= MAX_MESSAGE_BYTES:
55
+ raise ValueError(f"max_message_bytes must be an integer between 1 and {MAX_MESSAGE_BYTES}")
56
+ if not isinstance(confirm, bool):
57
+ raise ValueError("confirm must be a boolean")
58
+
59
+
60
+ def _rows(batch: Any) -> list[dict[str, Any]]:
61
+ rows = []
62
+ for source in batch.rows():
63
+ row = {name: source.get(name) for name in COLUMNS[:-1]}
64
+ if not isinstance(row["operation"], str) or not isinstance(row["record_id"], str):
65
+ raise ValueError("every row requires string operation and record_id")
66
+ for name, value in row.items():
67
+ if name == "value":
68
+ if value is not None and (
69
+ isinstance(value, bool) or not isinstance(value, (int, float)) or
70
+ not math.isfinite(value)
71
+ ):
72
+ raise ValueError("value must be a finite number or null")
73
+ elif value is not None and not isinstance(value, str):
74
+ raise ValueError(f"{name} must be a string or null")
75
+ encoded = json.dumps(row, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
76
+ row["content_hash"] = hashlib.sha256(encoded.encode("utf-8")).hexdigest()
77
+ rows.append(row)
78
+ return rows
79
+
80
+
81
+ def message_key(row: dict[str, Any]) -> str:
82
+ """Return the idempotency key used as the AMQP message_id."""
83
+ return f"{row['operation']}:{row['record_id']}:{row['content_hash']}"
84
+
85
+
86
+ def encode_message(row: dict[str, Any]) -> bytes:
87
+ """Return the canonical UTF-8 JSON body for one envelope row."""
88
+ return json.dumps(row, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
89
+ allow_nan=False).encode("utf-8")
90
+
91
+
92
+ def _properties(row: dict[str, Any]) -> pika.BasicProperties:
93
+ return pika.BasicProperties(
94
+ delivery_mode=2, content_type="application/json", content_encoding="utf-8",
95
+ message_id=message_key(row),
96
+ headers={name: row[name] for name in HEADERS if row.get(name) is not None},
97
+ )
98
+
99
+
100
+ def _blocks(rows: list[dict[str, Any]], batch_size: int,
101
+ max_message_bytes: int) -> list[list[tuple[bytes, pika.BasicProperties]]]:
102
+ output: list[list[tuple[bytes, pika.BasicProperties]]] = []
103
+ block: list[tuple[bytes, pika.BasicProperties]] = []
104
+ for row in rows:
105
+ body = encode_message(row)
106
+ if len(body) > max_message_bytes:
107
+ raise ValueError("one envelope exceeds max_message_bytes; narrow the source date range")
108
+ if len(block) >= batch_size:
109
+ output.append(block)
110
+ block = []
111
+ block.append((body, _properties(row)))
112
+ if block:
113
+ output.append(block)
114
+ return output
115
+
116
+
117
+ def publish(batch: Any, channel: Any, destination: tuple[str, str], *, batch_size: int = 1000,
118
+ max_message_bytes: int = MAX_MESSAGE_BYTES, confirm: bool = False) -> PublishResult:
119
+ """Publish one persistent message per envelope row through BlockingChannel.basic_publish.
120
+
121
+ Messages carry the canonical JSON body, `message_id` equal to
122
+ `operation:record_id:content_hash`, `content_type` application/json and
123
+ the headers `operation`, `record_id`, `content_hash` and `source_url`.
124
+ With `confirm=True` the channel enters publisher-confirm mode before the
125
+ first publish, so an unroutable or rejected message fails the block.
126
+ Delivery is at-least-once; a failed block raises PublishError and is not
127
+ retried.
128
+ """
129
+ exchange, routing_key = _destination(destination)
130
+ _bounds(batch_size, max_message_bytes, confirm)
131
+ blocks = _blocks(_rows(batch), batch_size, max_message_bytes)
132
+ if confirm:
133
+ try:
134
+ channel.confirm_delivery()
135
+ except Exception:
136
+ raise PublishError("RabbitMQ publisher confirms could not be enabled; inspect the channel.") from None
137
+ count, messages = 0, 0
138
+ for block in blocks:
139
+ try:
140
+ for body, properties in block:
141
+ channel.basic_publish(exchange, routing_key, body, properties=properties)
142
+ except Exception:
143
+ raise PublishError(
144
+ f"RabbitMQ publish block {count + 1} failed; earlier blocks may be delivered. "
145
+ "Inspect the destination and deduplicate by message_id on retry."
146
+ ) from None
147
+ count += 1
148
+ messages += len(block)
149
+ return PublishResult(f"{exchange}/{routing_key}", messages, count)
150
+
151
+
152
+ def publish_operation(operation: str, args: dict[str, Any] | None, channel: Any,
153
+ destination: tuple[str, str], *, api_key_env: str | None = None,
154
+ complete_history: bool = True, max_pages: int = 10000,
155
+ client_factory: Any = None, batch_size: int = 1000,
156
+ max_message_bytes: int = MAX_MESSAGE_BYTES, confirm: bool = False) -> PublishResult:
157
+ """Read one public operation and publish its complete response envelope."""
158
+ _destination(destination)
159
+ _bounds(batch_size, max_message_bytes, confirm)
160
+ batch = read(operation, args, api_key_env=api_key_env,
161
+ complete_history=complete_history, max_pages=max_pages,
162
+ client_factory=client_factory)
163
+ return publish(batch, channel, destination, batch_size=batch_size,
164
+ max_message_bytes=max_message_bytes, confirm=confirm)
165
+
166
+
167
+ __all__ = ["COLUMNS", "HEADERS", "MAX_MESSAGE_BYTES", "PublishError", "PublishResult",
168
+ "encode_message", "message_key", "publish", "publish_operation"]
File without changes
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.4
2
+ Name: rabbitmq-fxmacrodata
3
+ Version: 0.1.0
4
+ Summary: Publish public FXMacroData responses to RabbitMQ
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://fxmacrodata.com/documentation/reference?utm_source=pypi&utm_medium=referral&utm_campaign=rabbitmq-fxmacrodata&utm_content=package
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: fxmacrodata-platform-core==0.1.0
11
+ Requires-Dist: pika<2,>=1.4.4
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest<9,>=8; extra == "test"
14
+ Dynamic: license-file
15
+
16
+ # FXMacroData for RabbitMQ
17
+
18
+ Publish FXMacroData public responses to a RabbitMQ exchange with the official
19
+ `pika` Python client. Route macro announcements to your own queues while
20
+ retaining the source payload and revision metadata.
21
+
22
+ [FXMacroData documentation](https://fxmacrodata.com/documentation/reference?utm_source=github&utm_medium=referral&utm_campaign=rabbitmq-fxmacrodata&utm_content=readme)
23
+
24
+ ## Install and connect
25
+
26
+ Requires Python 3.10 or later. Install this package and its adjacent public
27
+ client dependencies from the distribution supplied to you:
28
+
29
+ ```sh
30
+ python -m pip install /path/to/fxmacrodata-public-client /path/to/fxmacrodata-platform-core /path/to/rabbitmq-fxmacrodata
31
+ ```
32
+
33
+ Configure `RABBITMQ_URL` (an `amqps://` URL with the credentials your
34
+ administrator provides) in your runtime secret store. Then publish to a
35
+ customer-owned exchange:
36
+
37
+ ```python
38
+ import os
39
+ import pika
40
+ from fxmacrodata_platform_core import read
41
+ from fxmacrodata_rabbitmq import publish
42
+
43
+ connection = pika.BlockingConnection(pika.URLParameters(os.environ["RABBITMQ_URL"]))
44
+ try:
45
+ channel = connection.channel()
46
+ batch = read("indicator_history", {"currency": "usd", "indicator": "policy_rate"})
47
+ result = publish(batch, channel, ("fxmacrodata", "usd.policy_rate"), confirm=True)
48
+ print(result.messages, "messages in", result.batches, "blocks")
49
+ finally:
50
+ connection.close()
51
+ ```
52
+
53
+ The exchange and any bound queues must already exist. The destination is an
54
+ `(exchange, routing_key)` tuple; names accept letters, digits, `_`, `.`, `:`
55
+ and `-` up to 255 characters. Use `("", "queue-name")` for the default
56
+ exchange and `("exchange-name", "")` for a fanout exchange. Wildcards, URLs
57
+ and other values are rejected before any publish.
58
+
59
+ Every operation exposed by `fxmacrodata_platform_core.operations()` is
60
+ available, including REST and MCP operations. `publish_operation` reads one
61
+ operation and publishes it in a single call:
62
+
63
+ ```python
64
+ from fxmacrodata_rabbitmq import publish_operation
65
+
66
+ publish_operation("release_calendar", {"currency": "usd"}, channel, ("fxmacrodata", "usd.calendar"),
67
+ api_key_env="FXMD_API_KEY")
68
+ ```
69
+
70
+ ## Message format
71
+
72
+ Each envelope row becomes one persistent message (`delivery_mode=2`). The
73
+ body is canonical UTF-8 JSON with the keys `operation`, `source_url`,
74
+ `record_id`, `currency`, `indicator`, `date`, `announcement_datetime`,
75
+ `value`, `value_text`, `record_json`, `response_json` and the publisher's
76
+ `content_hash` (SHA-256 of the ten source columns). Only `value` is numeric.
77
+ Dates and announcement times remain source strings. No publication time is
78
+ inferred, and no missing value is filled. `record_json` retains the original
79
+ record; `response_json` retains the complete response, including pagination
80
+ and metadata. An empty response produces one message with `record_json`
81
+ equal to `"null"`, so absence of data and the server's metadata remain
82
+ inspectable. It is not an observation.
83
+
84
+ `message_id` is `operation:record_id:content_hash`; the same source record
85
+ with the same content always produces the same id, and changed data or
86
+ metadata produces a different one. `content_type` is `application/json` and
87
+ the headers `operation`, `record_id`, `content_hash` and `source_url` are set
88
+ on every message. No timestamp property is derived from the data.
89
+
90
+ ## Delivery guarantee
91
+
92
+ Delivery is at-least-once. Messages are published in blocks of `batch_size`
93
+ rows (1 to 10,000, 1,000 by default). With `confirm=True` the channel enters
94
+ publisher-confirm mode before the first publish, so a message the broker
95
+ rejects or cannot route fails its block; without confirms, a broker-side
96
+ failure surfaces only when the channel closes. A failed block raises
97
+ `PublishError` without the broker's own diagnostic text and is not retried;
98
+ earlier blocks may already be delivered. Consumers should deduplicate on
99
+ `message_id`, or on the `operation`, `record_id` and `content_hash` headers.
100
+
101
+ `max_message_bytes` (16 MiB by default) rejects an individual envelope larger
102
+ than the budget before anything is published; keep it within the broker's
103
+ `max_message_size`, and narrow the source date range to reduce the response
104
+ size. The source response is materialized before publishing; choose a source
105
+ date range suitable for memory.
106
+
107
+ `publish_operation` accepts `api_key_env`, `complete_history`, `max_pages`
108
+ and `client_factory` for the public source reader. Supply source credentials
109
+ through your runtime secret store, exposing only the environment variable
110
+ name; omit `api_key_env` for anonymous USD access. Destination authentication
111
+ belongs to the connection you open with the official client. The adapter
112
+ neither saves nor prints credentials and never places one in a message or
113
+ header.
114
+
115
+ The package licence covers this adapter code. FXMacroData data access and
116
+ onward redistribution remain subject to your subscription and applicable
117
+ licence. Publishing data to a broker does not grant permission to publish or
118
+ resell it.
119
+
120
+ ## Development
121
+
122
+ Tests run offline against an in-memory fake channel:
123
+
124
+ ```sh
125
+ python -m pytest tests -q
126
+ ```
127
+
128
+ Official SDK reference:
129
+ [pika BlockingChannel.basic_publish](https://pika.readthedocs.io/en/stable/modules/adapters/blocking.html?utm_source=pypi&utm_medium=referral&utm_campaign=rabbitmq-fxmacrodata&utm_content=upstream-reference#pika.adapters.blocking_connection.BlockingChannel.basic_publish).
@@ -0,0 +1,7 @@
1
+ fxmacrodata_rabbitmq/__init__.py,sha256=-uSPHjm1inrWdURr3kuA23UPYMY1aHwe-JzgYD-aozs,7436
2
+ fxmacrodata_rabbitmq/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ rabbitmq_fxmacrodata-0.1.0.dist-info/licenses/LICENSE,sha256=rklK7Fl8aL1eWGubsrozZ7rCNTsN-MATw4M6LQIMv10,1092
4
+ rabbitmq_fxmacrodata-0.1.0.dist-info/METADATA,sha256=F9D3imTjb2C1uLxCxVFUacTH7rPqfUPNi4xVqg7zeds,6054
5
+ rabbitmq_fxmacrodata-0.1.0.dist-info/WHEEL,sha256=16fc_9Rp854SLcdhaDEjr0u65p0e3FhZxihNgcnCE98,91
6
+ rabbitmq_fxmacrodata-0.1.0.dist-info/top_level.txt,sha256=b0EfDT1DDIZzAbFoYuKsfqN_q7OVH1sXs4iiJvFSjw0,21
7
+ rabbitmq_fxmacrodata-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Robert Tidball
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ fxmacrodata_rabbitmq