pulsar-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,155 @@
1
+ """Publish public FXMacroData responses to a customer-owned Apache Pulsar topic."""
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
+ from fxmacrodata_platform_core import read
13
+
14
+ __version__ = "0.1.0"
15
+
16
+ COLUMNS = (
17
+ "operation", "source_url", "record_id", "currency", "indicator", "date",
18
+ "announcement_datetime", "value", "value_text", "record_json", "response_json",
19
+ "content_hash",
20
+ )
21
+ PROPERTIES = ("operation", "record_id", "content_hash", "source_url")
22
+ MAX_MESSAGE_BYTES = 16 * 1024 * 1024
23
+ _TOPIC = re.compile(
24
+ r"(?:(?:persistent|non-persistent)://[A-Za-z0-9_.-]{1,64}/[A-Za-z0-9_.-]{1,64}/)?[A-Za-z0-9_.-]{1,255}\Z"
25
+ )
26
+
27
+
28
+ class PublishError(RuntimeError):
29
+ """A destination publish failed; inspect the destination before retrying."""
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class PublishResult:
34
+ destination: str
35
+ messages: int
36
+ batches: int
37
+
38
+
39
+ def _topic(destination: str, producer: Any) -> str:
40
+ if not isinstance(destination, str) or not _TOPIC.fullmatch(destination):
41
+ raise ValueError("destination must be a Pulsar topic name such as persistent://tenant/namespace/topic")
42
+ bound = getattr(producer, "topic", None)
43
+ if callable(bound):
44
+ try:
45
+ actual = bound()
46
+ except Exception:
47
+ raise ValueError("the producer did not report its topic; pass a connected pulsar.Producer") from None
48
+ if isinstance(actual, str) and actual != destination:
49
+ raise ValueError("destination does not match the producer's topic")
50
+ return destination
51
+
52
+
53
+ def _bounds(batch_size: int, max_message_bytes: int) -> None:
54
+ if isinstance(batch_size, bool) or not isinstance(batch_size, int) or not 1 <= batch_size <= 10000:
55
+ raise ValueError("batch_size must be an integer between 1 and 10000")
56
+ if isinstance(max_message_bytes, bool) or not isinstance(max_message_bytes, int) or not 1 <= max_message_bytes <= MAX_MESSAGE_BYTES:
57
+ raise ValueError(f"max_message_bytes must be an integer between 1 and {MAX_MESSAGE_BYTES}")
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 Pulsar partition key."""
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]) -> dict[str, str]:
93
+ return {name: row[name] for name in PROPERTIES if row.get(name) is not None}
94
+
95
+
96
+ def _blocks(rows: list[dict[str, Any]], batch_size: int,
97
+ max_message_bytes: int) -> list[list[tuple[str, bytes, dict[str, str]]]]:
98
+ output: list[list[tuple[str, bytes, dict[str, str]]]] = []
99
+ block: list[tuple[str, bytes, dict[str, str]]] = []
100
+ for row in rows:
101
+ body = encode_message(row)
102
+ if len(body) > max_message_bytes:
103
+ raise ValueError("one envelope exceeds max_message_bytes; narrow the source date range")
104
+ if len(block) >= batch_size:
105
+ output.append(block)
106
+ block = []
107
+ block.append((message_key(row), body, _properties(row)))
108
+ if block:
109
+ output.append(block)
110
+ return output
111
+
112
+
113
+ def publish(batch: Any, producer: Any, destination: str, *, batch_size: int = 1000,
114
+ max_message_bytes: int = MAX_MESSAGE_BYTES) -> PublishResult:
115
+ """Send one message per envelope row through Producer.send and wait for each acknowledgement.
116
+
117
+ Messages carry the canonical JSON body, the properties `operation`,
118
+ `record_id`, `content_hash` and `source_url`, and a partition key of
119
+ `operation:record_id:content_hash`. No event timestamp is set. Delivery
120
+ is at-least-once; a failed block raises PublishError and is not retried.
121
+ """
122
+ topic = _topic(destination, producer)
123
+ _bounds(batch_size, max_message_bytes)
124
+ blocks = _blocks(_rows(batch), batch_size, max_message_bytes)
125
+ count, messages = 0, 0
126
+ for block in blocks:
127
+ try:
128
+ for key, body, properties in block:
129
+ producer.send(body, properties=properties, partition_key=key, event_timestamp=None)
130
+ except Exception:
131
+ raise PublishError(
132
+ f"Pulsar send block {count + 1} failed; earlier blocks may be delivered. "
133
+ "Inspect the destination and deduplicate by partition key on retry."
134
+ ) from None
135
+ count += 1
136
+ messages += len(block)
137
+ return PublishResult(topic, messages, count)
138
+
139
+
140
+ def publish_operation(operation: str, args: dict[str, Any] | None, producer: Any, destination: str,
141
+ *, api_key_env: str | None = None, complete_history: bool = True,
142
+ max_pages: int = 10000, client_factory: Any = None,
143
+ batch_size: int = 1000, max_message_bytes: int = MAX_MESSAGE_BYTES) -> PublishResult:
144
+ """Read one public operation and publish its complete response envelope."""
145
+ _topic(destination, producer)
146
+ _bounds(batch_size, max_message_bytes)
147
+ batch = read(operation, args, api_key_env=api_key_env,
148
+ complete_history=complete_history, max_pages=max_pages,
149
+ client_factory=client_factory)
150
+ return publish(batch, producer, destination, batch_size=batch_size,
151
+ max_message_bytes=max_message_bytes)
152
+
153
+
154
+ __all__ = ["COLUMNS", "MAX_MESSAGE_BYTES", "PROPERTIES", "PublishError", "PublishResult",
155
+ "encode_message", "message_key", "publish", "publish_operation"]
File without changes
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.4
2
+ Name: pulsar-fxmacrodata
3
+ Version: 0.1.0
4
+ Summary: Publish public FXMacroData responses to Apache Pulsar
5
+ License-Expression: MIT
6
+ Project-URL: Documentation, https://fxmacrodata.com/documentation/reference?utm_source=pypi&utm_medium=referral&utm_campaign=pulsar-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: pulsar-client<4,>=3.13.0
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest<9,>=8; extra == "test"
14
+ Dynamic: license-file
15
+
16
+ # FXMacroData for Apache Pulsar
17
+
18
+ Publish FXMacroData public responses to a Pulsar topic with the official
19
+ `pulsar-client` Python library. Stream macro announcements to your own
20
+ subscriptions while retaining the source payload and revision metadata.
21
+
22
+ [FXMacroData documentation](https://fxmacrodata.com/documentation/reference?utm_source=github&utm_medium=referral&utm_campaign=pulsar-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/pulsar-fxmacrodata
31
+ ```
32
+
33
+ Configure `PULSAR_SERVICE_URL` and any token file in your runtime secret
34
+ store. Then publish through a producer bound to a customer-owned topic:
35
+
36
+ ```python
37
+ import os
38
+ import pulsar
39
+ from fxmacrodata_platform_core import read
40
+ from fxmacrodata_pulsar import publish
41
+
42
+ TOPIC = "persistent://public/default/fxmacrodata"
43
+ client = pulsar.Client(os.environ["PULSAR_SERVICE_URL"])
44
+ try:
45
+ producer = client.create_producer(TOPIC)
46
+ batch = read("indicator_history", {"currency": "usd", "indicator": "policy_rate"})
47
+ result = publish(batch, producer, TOPIC)
48
+ print(result.messages, "messages in", result.batches, "blocks")
49
+ finally:
50
+ client.close()
51
+ ```
52
+
53
+ The destination is the topic name, either the full
54
+ `persistent://tenant/namespace/topic` form or the short name, and it must
55
+ match the topic the producer was created for. Service URLs and other values
56
+ are rejected before any send.
57
+
58
+ Every operation exposed by `fxmacrodata_platform_core.operations()` is
59
+ available, including REST and MCP operations. `publish_operation` reads one
60
+ operation and publishes it in a single call:
61
+
62
+ ```python
63
+ from fxmacrodata_pulsar import publish_operation
64
+
65
+ publish_operation("release_calendar", {"currency": "usd"}, producer, TOPIC,
66
+ api_key_env="FXMD_API_KEY")
67
+ ```
68
+
69
+ ## Message format
70
+
71
+ Each envelope row becomes one message. The body is canonical UTF-8 JSON with
72
+ the keys `operation`, `source_url`, `record_id`, `currency`, `indicator`,
73
+ `date`, `announcement_datetime`, `value`, `value_text`, `record_json`,
74
+ `response_json` and the publisher's `content_hash` (SHA-256 of the ten source
75
+ columns). Only `value` is numeric. Dates and announcement times remain source
76
+ strings. No publication time is inferred, no missing value is filled, and no
77
+ event timestamp is set on the message. `record_json` retains the original
78
+ record; `response_json` retains the complete response, including pagination
79
+ and metadata. An empty response produces one message with `record_json`
80
+ equal to `"null"`, so absence of data and the server's metadata remain
81
+ inspectable. It is not an observation.
82
+
83
+ The partition key is `operation:record_id:content_hash`; the same source
84
+ record with the same content always produces the same key, and changed data
85
+ or metadata produces a different one. The properties `operation`,
86
+ `record_id`, `content_hash` and `source_url` are set on every message for
87
+ consumer-side filtering.
88
+
89
+ ## Delivery guarantee
90
+
91
+ Delivery is at-least-once. Messages are sent in blocks of `batch_size` rows
92
+ (1 to 10,000, 1,000 by default) with `Producer.send`, which blocks until the
93
+ broker acknowledges each message; the producer's own batching settings
94
+ decide how messages are grouped on the wire. A failed block raises
95
+ `PublishError` without the broker's own diagnostic text and is not retried;
96
+ earlier blocks may already be delivered. Consumers should deduplicate on the
97
+ partition key, or on the `operation`, `record_id` and `content_hash`
98
+ properties.
99
+
100
+ `max_message_bytes` (16 MiB by default) rejects an individual envelope larger
101
+ than the budget before anything is published; keep it within the broker's
102
+ `maxMessageSize`, and narrow the source date range to reduce the response
103
+ size. The source response is materialized before publishing; choose a source
104
+ date range suitable for memory.
105
+
106
+ `publish_operation` accepts `api_key_env`, `complete_history`, `max_pages`
107
+ and `client_factory` for the public source reader. Supply source credentials
108
+ through your runtime secret store, exposing only the environment variable
109
+ name; omit `api_key_env` for anonymous USD access. Destination authentication
110
+ belongs to the Pulsar client you create the producer from. The adapter
111
+ neither saves nor prints credentials and never places one in a message or
112
+ property.
113
+
114
+ The package licence covers this adapter code. FXMacroData data access and
115
+ onward redistribution remain subject to your subscription and applicable
116
+ licence. Publishing data to a topic does not grant permission to publish or
117
+ resell it.
118
+
119
+ ## Development
120
+
121
+ Tests run offline against an in-memory fake producer:
122
+
123
+ ```sh
124
+ python -m pytest tests -q
125
+ ```
126
+
127
+ Official SDK reference:
128
+ [pulsar-client Producer.send](https://pulsar.apache.org/api/python/3.13.x/pulsar.Producer.html?utm_source=pypi&utm_medium=referral&utm_campaign=pulsar-fxmacrodata&utm_content=upstream-reference#send).
@@ -0,0 +1,7 @@
1
+ fxmacrodata_pulsar/__init__.py,sha256=9Nh8wUVcnON0A9ZWf_jSvVz_rlf5-WG9X64eCx_VUUs,6686
2
+ fxmacrodata_pulsar/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ pulsar_fxmacrodata-0.1.0.dist-info/licenses/LICENSE,sha256=rklK7Fl8aL1eWGubsrozZ7rCNTsN-MATw4M6LQIMv10,1092
4
+ pulsar_fxmacrodata-0.1.0.dist-info/METADATA,sha256=4uM5fwh6F8kHY58Mh4Ds2I2pniHa2x_3BP_JKc2pPzM,5712
5
+ pulsar_fxmacrodata-0.1.0.dist-info/WHEEL,sha256=16fc_9Rp854SLcdhaDEjr0u65p0e3FhZxihNgcnCE98,91
6
+ pulsar_fxmacrodata-0.1.0.dist-info/top_level.txt,sha256=i9hDu12UclDlto5Yu_V72se4TJJ3vyjsxODIuYXcHSA,19
7
+ pulsar_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_pulsar