py-datacents 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.
datacents/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """Clients for publishing Datacents events and issuing Circle USDC payouts."""
2
+
3
+ from .circle import (
4
+ CircleConfig,
5
+ CirclePaymentsClient,
6
+ CirclePayout,
7
+ CirclePayoutError,
8
+ CirclePayoutTimeout,
9
+ )
10
+ from .events import DATASETS, EventValidationError, validate_and_flatten_batch
11
+ from .snowpipe import BatchReceipt, SnowpipeConfig, SnowpipeStreamingPublisher
12
+
13
+ __all__ = [
14
+ "BatchReceipt",
15
+ "CircleConfig",
16
+ "CirclePayout",
17
+ "CirclePayoutError",
18
+ "CirclePayoutTimeout",
19
+ "CirclePaymentsClient",
20
+ "DATASETS",
21
+ "EventValidationError",
22
+ "SnowpipeConfig",
23
+ "SnowpipeStreamingPublisher",
24
+ "validate_and_flatten_batch",
25
+ ]
datacents/circle.py ADDED
@@ -0,0 +1,322 @@
1
+ """Circle developer-controlled wallet payouts using Circle's Python SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import time
7
+ import warnings
8
+ from dataclasses import dataclass
9
+ from datetime import datetime, timezone
10
+ from hmac import compare_digest
11
+ from typing import Any, Callable, Mapping
12
+ from uuid import UUID, uuid4
13
+
14
+
15
+ class CirclePayoutError(RuntimeError):
16
+ """Raised when Circle returns a non-success terminal transaction state."""
17
+
18
+ def __init__(
19
+ self,
20
+ message: str,
21
+ *,
22
+ transaction_id: str | None = None,
23
+ idempotency_key: str | None = None,
24
+ state: str | None = None,
25
+ ) -> None:
26
+ self.transaction_id = transaction_id
27
+ self.idempotency_key = idempotency_key
28
+ self.state = state
29
+ super().__init__(message)
30
+
31
+
32
+ class CirclePayoutTimeout(TimeoutError):
33
+ """Raised when a Circle transaction has not reached a terminal state in time."""
34
+
35
+ def __init__(self, transaction_id: str, idempotency_key: str) -> None:
36
+ self.transaction_id = transaction_id
37
+ self.idempotency_key = idempotency_key
38
+ super().__init__(
39
+ "Circle transaction did not reach a terminal state before timeout; "
40
+ f"resume polling transaction {transaction_id} with idempotency key "
41
+ f"{idempotency_key}"
42
+ )
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class CircleConfig:
47
+ api_key: str
48
+ entity_secret: str
49
+ environment: str
50
+ blockchain: str
51
+ token_address: str
52
+ source_wallet_id: str
53
+ source_wallet_address: str
54
+ poll_interval: float = 3.0
55
+ poll_timeout: float = 300.0
56
+ large_transfer_threshold_atomic: int = 100_000_000
57
+
58
+ def __post_init__(self) -> None:
59
+ for name in (
60
+ "api_key",
61
+ "entity_secret",
62
+ "blockchain",
63
+ "token_address",
64
+ "source_wallet_id",
65
+ "source_wallet_address",
66
+ ):
67
+ if not getattr(self, name):
68
+ raise ValueError(f"{name} must not be empty")
69
+ if self.environment not in {"TESTNET", "MAINNET"}:
70
+ raise ValueError("environment must be TESTNET or MAINNET")
71
+ if (
72
+ not math.isfinite(self.poll_interval)
73
+ or not math.isfinite(self.poll_timeout)
74
+ or self.poll_interval <= 0
75
+ or self.poll_timeout <= 0
76
+ ):
77
+ raise ValueError("poll_interval and poll_timeout must be positive")
78
+ if self.large_transfer_threshold_atomic <= 0:
79
+ raise ValueError("large_transfer_threshold_atomic must be positive")
80
+ if len(self.entity_secret) != 64:
81
+ raise ValueError("entity_secret must be a 32-byte hexadecimal value")
82
+ try:
83
+ int(self.entity_secret, 16)
84
+ except ValueError as exc:
85
+ raise ValueError("entity_secret must be a 32-byte hexadecimal value") from exc
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class CirclePayout:
90
+ contributor_id: str
91
+ environment: str
92
+ source_wallet_id: str
93
+ source_wallet_address: str
94
+ destination_address: str
95
+ asset: str
96
+ blockchain: str
97
+ amount_atomic: int
98
+ idempotency_key: str
99
+ transaction_id: str
100
+ state: str
101
+ settled_at: datetime | None
102
+ transaction_hash: str | None = None
103
+
104
+
105
+ def _circle_sdk(api_key: str, entity_secret: str) -> tuple[Any, Any]:
106
+ try:
107
+ from circle.web3 import developer_controlled_wallets, utils
108
+ except ImportError as exc:
109
+ raise RuntimeError(
110
+ "Circle's developer-controlled-wallets SDK is unavailable; "
111
+ "install the project dependencies"
112
+ ) from exc
113
+
114
+ client = utils.init_developer_controlled_wallets_client(
115
+ api_key=api_key,
116
+ entity_secret=entity_secret,
117
+ )
118
+ return (
119
+ developer_controlled_wallets.TransactionsApi(client),
120
+ developer_controlled_wallets.CreateTransferTransactionForDeveloperRequest,
121
+ )
122
+
123
+
124
+ def _as_mapping(value: Any) -> Mapping[str, Any]:
125
+ if isinstance(value, Mapping):
126
+ return value
127
+ to_dict = getattr(value, "to_dict", None)
128
+ if callable(to_dict):
129
+ return to_dict()
130
+ raise TypeError("Circle SDK returned a response in an unexpected format")
131
+
132
+
133
+ def _response_data(response: Any) -> Mapping[str, Any]:
134
+ data = getattr(response, "data", None)
135
+ if data is None:
136
+ raise CirclePayoutError("Circle response did not contain data")
137
+ return _as_mapping(data)
138
+
139
+
140
+ def _amount_in_usdc(amount_atomic: int) -> str:
141
+ whole, fractional = divmod(amount_atomic, 1_000_000)
142
+ if not fractional:
143
+ return str(whole)
144
+ return f"{whole}.{fractional:06d}".rstrip("0")
145
+
146
+
147
+ class CirclePaymentsClient:
148
+ """Submit USDC transfers and wait for Circle's terminal transaction state."""
149
+
150
+ TERMINAL_STATES = frozenset({"COMPLETE", "FAILED", "DENIED", "CANCELLED", "STUCK"})
151
+
152
+ def __init__(
153
+ self,
154
+ config: CircleConfig,
155
+ *,
156
+ transactions_api: Any | None = None,
157
+ request_factory: Callable[[Mapping[str, Any]], Any] | None = None,
158
+ sleep: Callable[[float], None] = time.sleep,
159
+ monotonic: Callable[[], float] = time.monotonic,
160
+ ) -> None:
161
+ self._config = config
162
+ if transactions_api is None or request_factory is None:
163
+ sdk_api, sdk_request_factory = _circle_sdk(
164
+ config.api_key, config.entity_secret
165
+ )
166
+ transactions_api = transactions_api or sdk_api
167
+ request_factory = request_factory or (
168
+ lambda payload: sdk_request_factory.from_dict(dict(payload))
169
+ )
170
+ self._transactions_api = transactions_api
171
+ self._request_factory = request_factory
172
+ self._sleep = sleep
173
+ self._monotonic = monotonic
174
+
175
+ @staticmethod
176
+ def mainnet_confirmation(
177
+ blockchain: str,
178
+ token_address: str,
179
+ source_wallet_id: str,
180
+ destination_address: str,
181
+ amount_atomic: int,
182
+ ) -> str:
183
+ """Return the exact value a caller must confirm before a mainnet payout."""
184
+ return (
185
+ f"{blockchain}|{token_address}|{source_wallet_id}|"
186
+ f"{destination_address}|{amount_atomic}"
187
+ )
188
+
189
+ def transfer_usdc(
190
+ self,
191
+ *,
192
+ contributor_id: str,
193
+ destination_address: str,
194
+ amount_atomic: int,
195
+ idempotency_key: str | None = None,
196
+ mainnet_confirmation: str | None = None,
197
+ wait: bool = True,
198
+ ) -> CirclePayout:
199
+ if not contributor_id:
200
+ raise ValueError("contributor_id must not be empty")
201
+ if not destination_address:
202
+ raise ValueError("destination_address must not be empty")
203
+ if isinstance(amount_atomic, bool) or not isinstance(amount_atomic, int):
204
+ raise TypeError("amount_atomic must be an integer number of USDC units")
205
+ if amount_atomic <= 0:
206
+ raise ValueError("amount_atomic must be a positive integer")
207
+ if self._config.environment == "MAINNET":
208
+ required_confirmation = self.mainnet_confirmation(
209
+ self._config.blockchain,
210
+ self._config.token_address,
211
+ self._config.source_wallet_id,
212
+ destination_address,
213
+ amount_atomic,
214
+ )
215
+ if mainnet_confirmation is None or not compare_digest(
216
+ mainnet_confirmation, required_confirmation
217
+ ):
218
+ raise ValueError(
219
+ "MAINNET payout requires confirmation of chain, token, source, "
220
+ "destination, and amount using mainnet_confirmation()"
221
+ )
222
+ if amount_atomic >= self._config.large_transfer_threshold_atomic:
223
+ warnings.warn(
224
+ "USDC payout is above the configured large-transfer threshold",
225
+ RuntimeWarning,
226
+ stacklevel=2,
227
+ )
228
+
229
+ key = idempotency_key or str(uuid4())
230
+ try:
231
+ parsed_key = UUID(key)
232
+ except (ValueError, AttributeError) as exc:
233
+ raise ValueError("idempotency_key must be a UUID v4") from exc
234
+ if parsed_key.version != 4:
235
+ raise ValueError("idempotency_key must be a UUID v4")
236
+
237
+ request = self._request_factory(
238
+ {
239
+ "walletId": self._config.source_wallet_id,
240
+ "blockchain": self._config.blockchain,
241
+ "destinationAddress": destination_address,
242
+ "tokenAddress": self._config.token_address,
243
+ "amounts": [_amount_in_usdc(amount_atomic)],
244
+ "feeLevel": "MEDIUM",
245
+ "idempotencyKey": key,
246
+ }
247
+ )
248
+ response = self._transactions_api.create_developer_transaction_transfer(
249
+ request
250
+ )
251
+ data = _response_data(response)
252
+ transaction_id = data.get("id")
253
+ state = data.get("state")
254
+ if not transaction_id or not state:
255
+ raise CirclePayoutError(
256
+ "Circle transfer response did not include transaction ID and state"
257
+ )
258
+
259
+ if wait:
260
+ data = self.wait_for_transaction(transaction_id, key, initial_data=data)
261
+ state = data["state"]
262
+ if state in {"FAILED", "DENIED", "CANCELLED", "STUCK"}:
263
+ raise CirclePayoutError(
264
+ f"Circle transaction {transaction_id} ended in state {state}",
265
+ transaction_id=str(transaction_id),
266
+ idempotency_key=key,
267
+ state=str(state),
268
+ )
269
+ settled_at = datetime.now(timezone.utc) if state == "COMPLETE" else None
270
+ return CirclePayout(
271
+ contributor_id=contributor_id,
272
+ environment=self._config.environment,
273
+ source_wallet_id=self._config.source_wallet_id,
274
+ source_wallet_address=self._config.source_wallet_address,
275
+ destination_address=destination_address,
276
+ asset="USDC",
277
+ blockchain=self._config.blockchain,
278
+ amount_atomic=amount_atomic,
279
+ idempotency_key=key,
280
+ transaction_id=str(transaction_id),
281
+ state=str(state),
282
+ settled_at=settled_at,
283
+ transaction_hash=data.get("txHash") or data.get("tx_hash"),
284
+ )
285
+
286
+ def wait_for_transaction(
287
+ self,
288
+ transaction_id: str,
289
+ idempotency_key: str,
290
+ *,
291
+ initial_data: Mapping[str, Any] | None = None,
292
+ ) -> Mapping[str, Any]:
293
+ current = dict(initial_data or {})
294
+ state = current.get("state")
295
+ deadline = self._monotonic() + self._config.poll_timeout
296
+ while state not in self.TERMINAL_STATES:
297
+ remaining = deadline - self._monotonic()
298
+ if remaining <= 0:
299
+ raise CirclePayoutTimeout(transaction_id, idempotency_key)
300
+ self._sleep(min(self._config.poll_interval, remaining))
301
+ response = self._transactions_api.get_transaction(id=transaction_id)
302
+ data = _response_data(response)
303
+ transaction = data.get("transaction")
304
+ if transaction is None:
305
+ raise CirclePayoutError(
306
+ f"Circle response omitted transaction {transaction_id}"
307
+ )
308
+ current = dict(_as_mapping(transaction))
309
+ state = current.get("state")
310
+ if not state:
311
+ raise CirclePayoutError(
312
+ f"Circle response omitted transaction state for {transaction_id}"
313
+ )
314
+
315
+ if state != "COMPLETE":
316
+ raise CirclePayoutError(
317
+ f"Circle transaction {transaction_id} ended in state {state}",
318
+ transaction_id=transaction_id,
319
+ idempotency_key=idempotency_key,
320
+ state=str(state),
321
+ )
322
+ return current
datacents/events.py ADDED
@@ -0,0 +1,598 @@
1
+ """Validation and Snowflake column mapping for Datacents data-product events."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timedelta, timezone
9
+ from typing import Any, Mapping, Sequence
10
+ from uuid import UUID
11
+
12
+
13
+ class EventValidationError(ValueError):
14
+ """Raised when an event does not match its published data-product schema."""
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Dataset:
19
+ product: str
20
+ table: str
21
+ max_batch_size: int
22
+ columns: Mapping[str, str]
23
+ required: tuple[str, ...]
24
+
25
+
26
+ def _dataset(
27
+ product: str,
28
+ table: str,
29
+ max_batch_size: int,
30
+ columns: Mapping[str, str],
31
+ required: tuple[str, ...],
32
+ ) -> Dataset:
33
+ return Dataset(product, table, max_batch_size, columns, required)
34
+
35
+
36
+ DATASETS: dict[str, Dataset] = {
37
+ "utilities.electric_usage_events": _dataset(
38
+ "utilities",
39
+ "electric_usage_events",
40
+ 1000,
41
+ {
42
+ "event_id": "EVENT_ID",
43
+ "contributor_id": "CONTRIBUTOR_ID",
44
+ "timestamp": "TIMESTAMP",
45
+ "reading_type": "READING_TYPE",
46
+ "power_w": "POWER_W",
47
+ "energy_kwh": "ENERGY_KWH",
48
+ "voltage_v": "VOLTAGE_V",
49
+ "current_a": "CURRENT_A",
50
+ "power_factor": "POWER_FACTOR",
51
+ "grid_import_kwh": "GRID_IMPORT_KWH",
52
+ "grid_export_kwh": "GRID_EXPORT_KWH",
53
+ "solar_production_kwh": "SOLAR_PRODUCTION_KWH",
54
+ "battery_charge_kwh": "BATTERY_CHARGE_KWH",
55
+ "location.country": "COUNTRY",
56
+ "location.state_province": "STATE_PROVINCE",
57
+ "location.postal_code_prefix": "POSTAL_CODE_PREFIX",
58
+ "location.timezone": "TIMEZONE",
59
+ "device_metadata.device_type": "DEVICE_TYPE",
60
+ "device_metadata.manufacturer": "MANUFACTURER",
61
+ "device_metadata.circuit_name": "CIRCUIT_NAME",
62
+ },
63
+ (
64
+ "event_id",
65
+ "contributor_id",
66
+ "timestamp",
67
+ "reading_type",
68
+ "power_w",
69
+ "energy_kwh",
70
+ "location.country",
71
+ "location.state_province",
72
+ "location.postal_code_prefix",
73
+ "location.timezone",
74
+ "device_metadata.device_type",
75
+ "device_metadata.manufacturer",
76
+ ),
77
+ ),
78
+ "utilities.water_usage_events": _dataset(
79
+ "utilities",
80
+ "water_usage_events",
81
+ 1000,
82
+ {
83
+ "event_id": "EVENT_ID",
84
+ "contributor_id": "CONTRIBUTOR_ID",
85
+ "timestamp": "TIMESTAMP",
86
+ "reading_type": "READING_TYPE",
87
+ "flow_rate_lpm": "FLOW_RATE_LPM",
88
+ "volume_liters": "VOLUME_LITERS",
89
+ "location.country": "COUNTRY",
90
+ "location.state_province": "STATE_PROVINCE",
91
+ "location.postal_code_prefix": "POSTAL_CODE_PREFIX",
92
+ "location.timezone": "TIMEZONE",
93
+ "device_metadata.device_type": "DEVICE_TYPE",
94
+ "device_metadata.manufacturer": "MANUFACTURER",
95
+ "device_metadata.fixture_type": "FIXTURE_TYPE",
96
+ },
97
+ (
98
+ "event_id",
99
+ "contributor_id",
100
+ "timestamp",
101
+ "reading_type",
102
+ "flow_rate_lpm",
103
+ "volume_liters",
104
+ "location.country",
105
+ "location.state_province",
106
+ "location.postal_code_prefix",
107
+ "location.timezone",
108
+ "device_metadata.device_type",
109
+ "device_metadata.manufacturer",
110
+ ),
111
+ ),
112
+ "content.media_playback_events": _dataset(
113
+ "content",
114
+ "media_playback_events",
115
+ 100,
116
+ {
117
+ "event_id": "EVENT_ID",
118
+ "contributor_id": "CONTRIBUTOR_ID",
119
+ "timestamp": "TIMESTAMP",
120
+ "event_type": "EVENT_TYPE",
121
+ "media_type": "MEDIA_TYPE",
122
+ "platform": "PLATFORM",
123
+ "content_metadata.genre": "GENRE",
124
+ "content_metadata.content_rating": "CONTENT_RATING",
125
+ "content_metadata.release_decade": "RELEASE_DECADE",
126
+ "content_metadata.language": "LANGUAGE",
127
+ "content_metadata.duration_seconds": "DURATION_SECONDS",
128
+ "content_metadata.is_live": "IS_LIVE",
129
+ "content_metadata.content_hash": "CONTENT_HASH",
130
+ "playback_metadata.playback_duration_seconds": "PLAYBACK_DURATION_SECONDS",
131
+ "playback_metadata.completion_percentage": "COMPLETION_PERCENTAGE",
132
+ "playback_metadata.device_type": "DEVICE_TYPE",
133
+ "playback_metadata.audio_quality": "AUDIO_QUALITY",
134
+ "playback_metadata.video_quality": "VIDEO_QUALITY",
135
+ "playback_metadata.playback_speed": "PLAYBACK_SPEED",
136
+ "context.time_of_day": "TIME_OF_DAY",
137
+ "context.day_of_week": "DAY_OF_WEEK",
138
+ "context.is_weekend": "IS_WEEKEND",
139
+ "context.device_room": "DEVICE_ROOM",
140
+ "demographic.age_range": "AGE_RANGE",
141
+ "demographic.household_size": "HOUSEHOLD_SIZE",
142
+ "demographic.country": "COUNTRY",
143
+ "demographic.timezone": "TIMEZONE",
144
+ },
145
+ (
146
+ "event_id",
147
+ "contributor_id",
148
+ "timestamp",
149
+ "event_type",
150
+ "media_type",
151
+ "platform",
152
+ ),
153
+ ),
154
+ "content.voice_assistant_interactions": _dataset(
155
+ "content",
156
+ "voice_assistant_interactions",
157
+ 100,
158
+ {
159
+ "event_id": "EVENT_ID",
160
+ "contributor_id": "CONTRIBUTOR_ID",
161
+ "timestamp": "TIMESTAMP",
162
+ "assistant_type": "ASSISTANT_TYPE",
163
+ "interaction_type": "INTERACTION_TYPE",
164
+ "domain": "DOMAIN",
165
+ "intent_category": "INTENT_CATEGORY",
166
+ "success": "SUCCESS",
167
+ "follow_up": "FOLLOW_UP",
168
+ "context.time_of_day": "TIME_OF_DAY",
169
+ "context.day_of_week": "DAY_OF_WEEK",
170
+ "context.device_room": "DEVICE_ROOM",
171
+ "demographic.age_range": "AGE_RANGE",
172
+ "demographic.household_size": "HOUSEHOLD_SIZE",
173
+ "demographic.country": "COUNTRY",
174
+ "demographic.timezone": "TIMEZONE",
175
+ },
176
+ (
177
+ "event_id",
178
+ "contributor_id",
179
+ "timestamp",
180
+ "assistant_type",
181
+ "interaction_type",
182
+ "domain",
183
+ "intent_category",
184
+ "success",
185
+ "follow_up",
186
+ ),
187
+ ),
188
+ "content.content_discovery_events": _dataset(
189
+ "content",
190
+ "content_discovery_events",
191
+ 100,
192
+ {
193
+ "event_id": "EVENT_ID",
194
+ "contributor_id": "CONTRIBUTOR_ID",
195
+ "timestamp": "TIMESTAMP",
196
+ "discovery_method": "DISCOVERY_METHOD",
197
+ "platform": "PLATFORM",
198
+ "resulted_in_playback": "RESULTED_IN_PLAYBACK",
199
+ "time_to_decision_seconds": "TIME_TO_DECISION_SECONDS",
200
+ },
201
+ (
202
+ "event_id",
203
+ "contributor_id",
204
+ "timestamp",
205
+ "discovery_method",
206
+ "platform",
207
+ "resulted_in_playback",
208
+ "time_to_decision_seconds",
209
+ ),
210
+ ),
211
+ "cybersecurity.network_security_events": _dataset(
212
+ "cybersecurity",
213
+ "network_security_events",
214
+ 500,
215
+ {
216
+ "event_id": "EVENT_ID",
217
+ "contributor_id": "CONTRIBUTOR_ID",
218
+ "timestamp": "TIMESTAMP",
219
+ "event_type": "EVENT_TYPE",
220
+ "severity": "SEVERITY",
221
+ "source.ip_prefix": "SOURCE_IP_PREFIX",
222
+ "source.country": "SOURCE_COUNTRY",
223
+ "source.asn": "SOURCE_ASN",
224
+ "source.is_internal": "SOURCE_IS_INTERNAL",
225
+ "source.device_type": "SOURCE_DEVICE_TYPE",
226
+ "destination.ip_prefix": "DESTINATION_IP_PREFIX",
227
+ "destination.port": "DESTINATION_PORT",
228
+ "destination.protocol": "DESTINATION_PROTOCOL",
229
+ "destination.service": "DESTINATION_SERVICE",
230
+ "attack_metadata.attack_type": "ATTACK_TYPE",
231
+ "attack_metadata.attack_signature_id": "ATTACK_SIGNATURE_ID",
232
+ "attack_metadata.attack_category": "ATTACK_CATEGORY",
233
+ "attack_metadata.payload_hash": "PAYLOAD_HASH",
234
+ "attack_metadata.packet_count": "PACKET_COUNT",
235
+ "attack_metadata.byte_count": "BYTE_COUNT",
236
+ "detection_metadata.detection_method": "DETECTION_METHOD",
237
+ "detection_metadata.detector": "DETECTOR",
238
+ "detection_metadata.confidence_score": "CONFIDENCE_SCORE",
239
+ "detection_metadata.false_positive_likelihood": "FALSE_POSITIVE_LIKELIHOOD",
240
+ "response_action.action_taken": "ACTION_TAKEN",
241
+ "response_action.automated": "AUTOMATED",
242
+ "response_action.rule_id": "RULE_ID",
243
+ "location.country": "LOCATION_COUNTRY",
244
+ "location.state_province": "STATE_PROVINCE",
245
+ "location.timezone": "TIMEZONE",
246
+ "location.network_type": "NETWORK_TYPE",
247
+ },
248
+ ("event_id", "contributor_id", "timestamp", "event_type", "severity"),
249
+ ),
250
+ "cybersecurity.iot_device_security_events": _dataset(
251
+ "cybersecurity",
252
+ "iot_device_security_events",
253
+ 500,
254
+ {
255
+ "event_id": "EVENT_ID",
256
+ "contributor_id": "CONTRIBUTOR_ID",
257
+ "timestamp": "TIMESTAMP",
258
+ "event_type": "EVENT_TYPE",
259
+ "device.device_category": "DEVICE_CATEGORY",
260
+ "device.manufacturer": "MANUFACTURER",
261
+ "device.model_category": "MODEL_CATEGORY",
262
+ "device.firmware_version_hash": "FIRMWARE_VERSION_HASH",
263
+ "device.age_months": "AGE_MONTHS",
264
+ "vulnerability.vulnerability_type": "VULNERABILITY_TYPE",
265
+ "vulnerability.cve_id": "CVE_ID",
266
+ "vulnerability.cvss_score": "CVSS_SCORE",
267
+ "vulnerability.exploited": "EXPLOITED",
268
+ "behavioral_anomaly.anomaly_type": "ANOMALY_TYPE",
269
+ "behavioral_anomaly.baseline_deviation_score": "BASELINE_DEVIATION_SCORE",
270
+ "behavioral_anomaly.traffic_destination_country": "TRAFFIC_DESTINATION_COUNTRY",
271
+ "behavioral_anomaly.data_volume_mb": "DATA_VOLUME_MB",
272
+ },
273
+ ("event_id", "contributor_id", "timestamp", "event_type"),
274
+ ),
275
+ "cybersecurity.authentication_events": _dataset(
276
+ "cybersecurity",
277
+ "authentication_events",
278
+ 500,
279
+ {
280
+ "event_id": "EVENT_ID",
281
+ "contributor_id": "CONTRIBUTOR_ID",
282
+ "timestamp": "TIMESTAMP",
283
+ "event_type": "EVENT_TYPE",
284
+ "access_method": "ACCESS_METHOD",
285
+ "device_type": "DEVICE_TYPE",
286
+ "authentication.auth_type": "AUTH_TYPE",
287
+ "authentication.attempt_count": "ATTEMPT_COUNT",
288
+ "authentication.success": "SUCCESS",
289
+ "authentication.lockout_triggered": "LOCKOUT_TRIGGERED",
290
+ "source.ip_prefix": "SOURCE_IP_PREFIX",
291
+ "source.country": "SOURCE_COUNTRY",
292
+ "source.is_tor": "SOURCE_IS_TOR",
293
+ "source.is_vpn": "SOURCE_IS_VPN",
294
+ "source.is_known_device": "SOURCE_IS_KNOWN_DEVICE",
295
+ "context.time_since_last_access_hours": "TIME_SINCE_LAST_ACCESS_HOURS",
296
+ "context.unusual_time": "UNUSUAL_TIME",
297
+ "context.unusual_location": "UNUSUAL_LOCATION",
298
+ },
299
+ (
300
+ "event_id",
301
+ "contributor_id",
302
+ "timestamp",
303
+ "event_type",
304
+ "access_method",
305
+ "device_type",
306
+ "authentication.auth_type",
307
+ "authentication.attempt_count",
308
+ "authentication.success",
309
+ "authentication.lockout_triggered",
310
+ ),
311
+ ),
312
+ "cybersecurity.malware_threat_events": _dataset(
313
+ "cybersecurity",
314
+ "malware_threat_events",
315
+ 500,
316
+ {
317
+ "event_id": "EVENT_ID",
318
+ "contributor_id": "CONTRIBUTOR_ID",
319
+ "timestamp": "TIMESTAMP",
320
+ "threat_type": "THREAT_TYPE",
321
+ "detection_source": "DETECTION_SOURCE",
322
+ "malware_family": "MALWARE_FAMILY",
323
+ "ioc.domain_hash": "IOC_DOMAIN_HASH",
324
+ "ioc.ip_prefix": "IOC_IP_PREFIX",
325
+ "ioc.file_hash": "IOC_FILE_HASH",
326
+ "ioc.url_category": "URL_CATEGORY",
327
+ "impact.devices_affected": "DEVICES_AFFECTED",
328
+ "impact.data_encrypted": "DATA_ENCRYPTED",
329
+ "impact.data_exfiltrated": "DATA_EXFILTRATED",
330
+ "impact.service_disrupted": "SERVICE_DISRUPTED",
331
+ "remediation.action_taken": "REMEDIATION_ACTION",
332
+ "remediation.successful": "REMEDIATION_SUCCESSFUL",
333
+ "remediation.time_to_remediation_minutes": "TIME_TO_REMEDIATION_MINUTES",
334
+ },
335
+ ("event_id", "contributor_id", "timestamp", "threat_type", "detection_source"),
336
+ ),
337
+ }
338
+
339
+
340
+ def _get_path(event: Mapping[str, Any], path: str) -> Any:
341
+ value: Any = event
342
+ for component in path.split("."):
343
+ if not isinstance(value, Mapping) or component not in value:
344
+ return None
345
+ value = value[component]
346
+ return value
347
+
348
+
349
+ def _parse_timestamp(value: Any) -> tuple[datetime, str]:
350
+ if isinstance(value, datetime):
351
+ parsed = value
352
+ elif isinstance(value, str):
353
+ try:
354
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
355
+ except ValueError as exc:
356
+ raise EventValidationError("timestamp must be an ISO 8601 datetime") from exc
357
+ else:
358
+ raise EventValidationError("timestamp must be an ISO 8601 datetime")
359
+
360
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
361
+ raise EventValidationError("timestamp must include a timezone")
362
+ parsed = parsed.astimezone(timezone.utc)
363
+ return parsed, parsed.isoformat()
364
+
365
+
366
+ def _number(value: Any, path: str) -> float:
367
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
368
+ raise EventValidationError(f"{path} must be a number")
369
+ if not math.isfinite(value):
370
+ raise EventValidationError(f"{path} must be finite")
371
+ return value
372
+
373
+
374
+ def _validate_private_fields(dataset_name: str, event: Mapping[str, Any]) -> None:
375
+ if dataset_name.startswith("utilities."):
376
+ postal_prefix = _get_path(event, "location.postal_code_prefix")
377
+ if not isinstance(postal_prefix, str) or not re.fullmatch(r"\d{3}", postal_prefix):
378
+ raise EventValidationError(
379
+ "postal_code_prefix must contain only the first three digits"
380
+ )
381
+
382
+ if dataset_name == "cybersecurity.network_security_events":
383
+ paths = ("source.ip_prefix", "destination.ip_prefix")
384
+ elif dataset_name == "cybersecurity.authentication_events":
385
+ paths = ("source.ip_prefix",)
386
+ elif dataset_name == "cybersecurity.malware_threat_events":
387
+ paths = ("ioc.ip_prefix",)
388
+ else:
389
+ paths = ()
390
+ for path in paths:
391
+ value = _get_path(event, path)
392
+ if value is not None:
393
+ if not isinstance(value, str):
394
+ raise EventValidationError(f"{path} must be a masked IPv4 prefix")
395
+ match = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.[xX]\.[xX]", value)
396
+ if match is None or any(int(octet) > 255 for octet in match.groups()):
397
+ raise EventValidationError(
398
+ f"{path} must contain only a /16 IPv4 prefix (a.b.x.x)"
399
+ )
400
+
401
+
402
+ def _flatten(
403
+ event: Mapping[str, Any], dataset: Dataset, path: str = ""
404
+ ) -> dict[str, Any]:
405
+ flattened: dict[str, Any] = {}
406
+ for key, value in event.items():
407
+ if not isinstance(key, str):
408
+ raise EventValidationError("event field names must be strings")
409
+ current_path = f"{path}.{key}" if path else key
410
+ if isinstance(value, Mapping):
411
+ if not value and not any(
412
+ column.startswith(f"{current_path}.")
413
+ for column in dataset.columns
414
+ ):
415
+ raise EventValidationError(
416
+ f"field {current_path!r} is not defined by the "
417
+ "data-product specification"
418
+ )
419
+ flattened.update(_flatten(value, dataset, current_path))
420
+ continue
421
+ if current_path not in dataset.columns:
422
+ raise EventValidationError(
423
+ f"field {current_path!r} is not defined by the "
424
+ "data-product specification"
425
+ )
426
+ if current_path == "timestamp":
427
+ parsed, value = _parse_timestamp(value)
428
+ if dataset.product == "cybersecurity":
429
+ parsed = (parsed + timedelta(seconds=30)).replace(
430
+ second=0, microsecond=0
431
+ )
432
+ value = parsed.isoformat()
433
+ flattened[dataset.columns[current_path]] = value
434
+ return flattened
435
+
436
+
437
+ def _validate_event(dataset_name: str, event: Mapping[str, Any]) -> dict[str, Any]:
438
+ dataset = DATASETS[dataset_name]
439
+ if not isinstance(event, Mapping):
440
+ raise EventValidationError("each event must be a mapping")
441
+
442
+ for path in dataset.required:
443
+ if _get_path(event, path) is None:
444
+ raise EventValidationError(f"required field {path!r} is missing")
445
+
446
+ event_id = _get_path(event, "event_id")
447
+ if not isinstance(event_id, str):
448
+ raise EventValidationError("event_id must be a UUID string")
449
+ try:
450
+ event_id = str(UUID(event_id))
451
+ except ValueError as exc:
452
+ raise EventValidationError("event_id must be a UUID string") from exc
453
+ contributor_id = _get_path(event, "contributor_id")
454
+ if not isinstance(contributor_id, str) or not contributor_id.strip():
455
+ raise EventValidationError("contributor_id must be a non-empty hashed ID")
456
+
457
+ parsed_timestamp, _ = _parse_timestamp(_get_path(event, "timestamp"))
458
+ if dataset.product == "utilities":
459
+ now = datetime.now(timezone.utc)
460
+ try:
461
+ oldest_allowed = now.replace(year=now.year - 10)
462
+ except ValueError:
463
+ oldest_allowed = now.replace(year=now.year - 10, day=28)
464
+ if parsed_timestamp > now:
465
+ raise EventValidationError("timestamp cannot be in the future")
466
+ if parsed_timestamp < oldest_allowed:
467
+ raise EventValidationError("timestamp cannot be more than 10 years old")
468
+
469
+ if dataset_name == "utilities.electric_usage_events":
470
+ power_w = _number(_get_path(event, "power_w"), "power_w")
471
+ energy_kwh = _number(_get_path(event, "energy_kwh"), "energy_kwh")
472
+ if power_w < 0 or power_w >= 50_000:
473
+ raise EventValidationError("power_w must be >= 0 and < 50000")
474
+ if energy_kwh < 0:
475
+ raise EventValidationError("energy_kwh must be non-negative")
476
+ reading_type = _get_path(event, "reading_type")
477
+ if not isinstance(reading_type, str) or reading_type not in {
478
+ "instantaneous",
479
+ "cumulative",
480
+ }:
481
+ raise EventValidationError("reading_type must be instantaneous or cumulative")
482
+ elif dataset_name == "utilities.water_usage_events":
483
+ flow_rate = _number(_get_path(event, "flow_rate_lpm"), "flow_rate_lpm")
484
+ volume_liters = _number(_get_path(event, "volume_liters"), "volume_liters")
485
+ if flow_rate < 0 or flow_rate >= 100:
486
+ raise EventValidationError("flow_rate_lpm must be >= 0 and < 100")
487
+ if volume_liters < 0:
488
+ raise EventValidationError("volume_liters must be non-negative")
489
+ reading_type = _get_path(event, "reading_type")
490
+ if not isinstance(reading_type, str) or reading_type not in {
491
+ "instantaneous",
492
+ "cumulative",
493
+ }:
494
+ raise EventValidationError("reading_type must be instantaneous or cumulative")
495
+
496
+ if dataset_name == "content.media_playback_events":
497
+ event_type = _get_path(event, "event_type")
498
+ if not isinstance(event_type, str) or event_type not in {
499
+ "play",
500
+ "pause",
501
+ "stop",
502
+ "skip",
503
+ "seek",
504
+ "complete",
505
+ }:
506
+ raise EventValidationError("event_type is not a supported media event")
507
+ media_type = _get_path(event, "media_type")
508
+ if not isinstance(media_type, str) or media_type not in {
509
+ "movie",
510
+ "tv_show",
511
+ "music",
512
+ "podcast",
513
+ "audiobook",
514
+ "youtube",
515
+ "game",
516
+ }:
517
+ raise EventValidationError("media_type is not supported")
518
+ percentage = _get_path(event, "playback_metadata.completion_percentage")
519
+ if percentage is not None:
520
+ percentage = _number(percentage, "completion_percentage")
521
+ if not 0 <= percentage <= 100:
522
+ raise EventValidationError(
523
+ "completion_percentage must be between 0 and 100"
524
+ )
525
+ played = _get_path(event, "playback_metadata.playback_duration_seconds")
526
+ duration = _get_path(event, "content_metadata.duration_seconds")
527
+ if played is not None and duration is not None:
528
+ played = _number(played, "playback_duration_seconds")
529
+ duration = _number(duration, "duration_seconds")
530
+ if played > duration * 1.1:
531
+ raise EventValidationError(
532
+ "playback duration cannot exceed content duration by more than 10%"
533
+ )
534
+ elif dataset_name == "content.voice_assistant_interactions":
535
+ assistant_type = _get_path(event, "assistant_type")
536
+ if not isinstance(assistant_type, str) or assistant_type not in {
537
+ "alexa",
538
+ "google_assistant",
539
+ "siri",
540
+ }:
541
+ raise EventValidationError("assistant_type is not supported")
542
+ elif dataset_name == "content.content_discovery_events":
543
+ discovery_method = _get_path(event, "discovery_method")
544
+ if not isinstance(discovery_method, str) or discovery_method not in {
545
+ "browse",
546
+ "search",
547
+ "recommendation",
548
+ "autoplay",
549
+ "notification",
550
+ }:
551
+ raise EventValidationError("discovery_method is not supported")
552
+
553
+ if dataset_name == "cybersecurity.network_security_events":
554
+ severity = _get_path(event, "severity")
555
+ if not isinstance(severity, str) or severity not in {
556
+ "low",
557
+ "medium",
558
+ "high",
559
+ "critical",
560
+ }:
561
+ raise EventValidationError("severity must be low, medium, high, or critical")
562
+
563
+ _validate_private_fields(dataset_name, event)
564
+ return _flatten(event, dataset)
565
+
566
+
567
+ def validate_and_flatten_batch(
568
+ dataset_name: str, events: Sequence[Mapping[str, Any]]
569
+ ) -> list[dict[str, Any]]:
570
+ """Validate a batch against a data-product schema and map it to columns."""
571
+ try:
572
+ dataset = DATASETS[dataset_name]
573
+ except KeyError as exc:
574
+ raise EventValidationError(f"unknown dataset {dataset_name!r}") from exc
575
+
576
+ if len(events) > dataset.max_batch_size:
577
+ raise EventValidationError(
578
+ f"{dataset_name} accepts at most {dataset.max_batch_size} events per batch"
579
+ )
580
+ if not events:
581
+ return []
582
+
583
+ rows = [_validate_event(dataset_name, event) for event in events]
584
+ for row in rows:
585
+ row["EVENT_ID"] = str(UUID(row["EVENT_ID"]))
586
+ event_ids = [row["EVENT_ID"] for row in rows]
587
+ if len(event_ids) != len(set(event_ids)):
588
+ raise EventValidationError("a batch cannot contain duplicate event_id values")
589
+
590
+ if dataset.product == "utilities":
591
+ contributor_timestamps = [
592
+ (row["CONTRIBUTOR_ID"], row["TIMESTAMP"]) for row in rows
593
+ ]
594
+ if len(contributor_timestamps) != len(set(contributor_timestamps)):
595
+ raise EventValidationError(
596
+ "a batch cannot contain duplicate contributor/timestamp readings"
597
+ )
598
+ return rows
datacents/snowpipe.py ADDED
@@ -0,0 +1,142 @@
1
+ """Snowpipe Streaming publisher for Datacents event batches."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+ from typing import Any, Callable, Mapping, Sequence
10
+ from uuid import uuid4
11
+
12
+ from .events import DATASETS, Dataset, validate_and_flatten_batch
13
+
14
+ _IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_$]*$")
15
+ _ClientFactory = Callable[..., Any]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class SnowpipeConfig:
20
+ database: str
21
+ schemas: Mapping[str, str]
22
+ properties: Mapping[str, Any]
23
+ table_names: Mapping[str, str] | None = None
24
+ client_name: str = "datacents"
25
+ acknowledgement_timeout: float = 60.0
26
+
27
+ def __post_init__(self) -> None:
28
+ _validate_identifier(self.database, "database")
29
+ for product in ("utilities", "content", "cybersecurity"):
30
+ if product not in self.schemas:
31
+ raise ValueError(f"schemas must define a Snowflake schema for {product}")
32
+ _validate_identifier(self.schemas[product], f"{product} schema")
33
+ if self.table_names is not None:
34
+ unknown_tables = set(self.table_names) - set(DATASETS)
35
+ if unknown_tables:
36
+ raise ValueError(
37
+ f"table_names contains unknown datasets: {sorted(unknown_tables)}"
38
+ )
39
+ for name in DATASETS:
40
+ if name in self.table_names:
41
+ _validate_identifier(self.table_names[name], f"{name} table")
42
+ if (
43
+ not math.isfinite(self.acknowledgement_timeout)
44
+ or self.acknowledgement_timeout <= 0
45
+ ):
46
+ raise ValueError("acknowledgement_timeout must be positive")
47
+ if not self.properties:
48
+ raise ValueError("Snowpipe connection properties must not be empty")
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class BatchReceipt:
53
+ dataset: str
54
+ row_count: int
55
+ acknowledged_at: datetime
56
+
57
+
58
+ def _validate_identifier(value: str, label: str) -> None:
59
+ if not _IDENTIFIER.fullmatch(value):
60
+ raise ValueError(f"{label} must be a simple Snowflake identifier")
61
+
62
+
63
+ def _snowpipe_client_factory(**kwargs: Any) -> Any:
64
+ try:
65
+ from snowflake.ingest.streaming import StreamingIngestClient
66
+ except ImportError as exc:
67
+ raise RuntimeError(
68
+ "Snowpipe Streaming is unavailable; install the project dependencies"
69
+ ) from exc
70
+ return StreamingIngestClient.from_table(**kwargs)
71
+
72
+
73
+ class SnowpipeStreamingPublisher:
74
+ """Publish validated data-product events through Snowpipe Elastic Channels."""
75
+
76
+ def __init__(
77
+ self,
78
+ config: SnowpipeConfig,
79
+ *,
80
+ client_factory: _ClientFactory | None = None,
81
+ ) -> None:
82
+ self._config = config
83
+ self._client_factory = client_factory or _snowpipe_client_factory
84
+ self._clients: dict[str, tuple[Any, Any]] = {}
85
+ self._closed = False
86
+
87
+ def publish_batch(
88
+ self, dataset_name: str, events: Sequence[Mapping[str, Any]]
89
+ ) -> BatchReceipt:
90
+ if self._closed:
91
+ raise RuntimeError("publisher is closed")
92
+ rows = validate_and_flatten_batch(dataset_name, events)
93
+ if not rows:
94
+ return BatchReceipt(dataset_name, 0, datetime.now(timezone.utc))
95
+
96
+ dataset = DATASETS[dataset_name]
97
+ client, channel = self._get_channel(dataset_name, dataset)
98
+ future = channel.append_rows_with_wait(rows, str(uuid4()))
99
+ future.result(timeout=self._config.acknowledgement_timeout)
100
+ return BatchReceipt(dataset_name, len(rows), datetime.now(timezone.utc))
101
+
102
+ def publish_event(
103
+ self, dataset_name: str, event: Mapping[str, Any]
104
+ ) -> BatchReceipt:
105
+ return self.publish_batch(dataset_name, [event])
106
+
107
+ def _get_channel(self, dataset_name: str, dataset: Dataset) -> tuple[Any, Any]:
108
+ existing = self._clients.get(dataset_name)
109
+ if existing is not None:
110
+ return existing
111
+
112
+ schema_name = self._config.schemas[dataset.product]
113
+ table_name = (
114
+ self._config.table_names.get(dataset_name, dataset.table)
115
+ if self._config.table_names is not None
116
+ else dataset.table
117
+ )
118
+ client = self._client_factory(
119
+ client_name=f"{self._config.client_name}-{dataset_name.replace('.', '-')}",
120
+ db_name=self._config.database,
121
+ schema_name=schema_name,
122
+ table_name=table_name,
123
+ properties=dict(self._config.properties),
124
+ )
125
+ channel = client.get_elastic_channel()
126
+ self._clients[dataset_name] = (client, channel)
127
+ return client, channel
128
+
129
+ def close(self) -> None:
130
+ if self._closed:
131
+ return
132
+ for client, _ in self._clients.values():
133
+ client.close()
134
+ self._closed = True
135
+
136
+ def __enter__(self) -> SnowpipeStreamingPublisher:
137
+ if self._closed:
138
+ raise RuntimeError("publisher is closed")
139
+ return self
140
+
141
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
142
+ self.close()
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: py-datacents
3
+ Version: 0.1.0
4
+ Summary: A library for Home Assistant to help people make money from their data.
5
+ Author: Derek Stearns
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/djstearns/py-datacents
8
+ Project-URL: Repository, https://github.com/djstearns/py-datacents
9
+ Project-URL: Issues, https://github.com/djstearns/py-datacents/issues
10
+ Keywords: home-assistant,snowflake,snowpipe-streaming,circle,usdc
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: circle-developer-controlled-wallets<10,>=9.6
22
+ Requires-Dist: snowpipe-streaming<2,>=1.8
23
+ Dynamic: license-file
24
+
25
+ # py-datacents
26
+
27
+ A Python library for Home Assistant integrations that stream privacy-conscious
28
+ data-product events to Snowflake and submit contributor USDC payouts through
29
+ Circle developer-controlled wallets.
30
+
31
+ ## Install
32
+
33
+ ```shell
34
+ pip install py-datacents
35
+ ```
36
+
37
+ ## Stream data to Snowflake
38
+
39
+ Create a Snowpipe Streaming pipe/table for each dataset and configure Snowflake
40
+ key-pair authentication. Pass the database, schema names, and connection
41
+ properties to the publisher; credentials are not read from source files or
42
+ logged.
43
+
44
+ ```python
45
+ from datetime import datetime, timezone
46
+ from uuid import uuid4
47
+
48
+ from datacents import SnowpipeConfig, SnowpipeStreamingPublisher
49
+
50
+ publisher = SnowpipeStreamingPublisher(
51
+ SnowpipeConfig(
52
+ database="DATACENTS",
53
+ schemas={
54
+ "utilities": "UTILITIES",
55
+ "content": "CONTENT",
56
+ "cybersecurity": "CYBERSECURITY",
57
+ },
58
+ properties={
59
+ "account": "your_account",
60
+ "user": "DATACENTS_INGEST",
61
+ "private_key_file": "/run/secrets/snowflake_key.p8",
62
+ "url": "https://your_account.snowflakecomputing.com",
63
+ "role": "DATACENTS_INGEST_ROLE",
64
+ },
65
+ )
66
+ )
67
+
68
+ electric_event = {
69
+ "event_id": str(uuid4()),
70
+ "contributor_id": "hashed_contributor_id",
71
+ "timestamp": datetime.now(timezone.utc).isoformat(),
72
+ "reading_type": "instantaneous",
73
+ "power_w": 500.0,
74
+ "energy_kwh": 0.5,
75
+ "location": {
76
+ "country": "US",
77
+ "state_province": "CA",
78
+ "postal_code_prefix": "941",
79
+ "timezone": "America/Los_Angeles",
80
+ },
81
+ "device_metadata": {
82
+ "device_type": "smart_meter",
83
+ "manufacturer": "example",
84
+ },
85
+ }
86
+
87
+ publisher.publish_batch(
88
+ "utilities.electric_usage_events",
89
+ [electric_event],
90
+ )
91
+ publisher.close()
92
+ ```
93
+
94
+ Supported dataset identifiers and maximum batch sizes are:
95
+
96
+ | Dataset | Maximum events per batch |
97
+ | --- | ---: |
98
+ | `utilities.electric_usage_events` | 1000 |
99
+ | `utilities.water_usage_events` | 1000 |
100
+ | `content.media_playback_events` | 100 |
101
+ | `content.voice_assistant_interactions` | 100 |
102
+ | `content.content_discovery_events` | 100 |
103
+ | `cybersecurity.network_security_events` | 500 |
104
+ | `cybersecurity.iot_device_security_events` | 500 |
105
+ | `cybersecurity.authentication_events` | 500 |
106
+ | `cybersecurity.malware_threat_events` | 500 |
107
+
108
+ Nested event fields are flattened to the columns described by the data-product
109
+ specifications. Each batch call waits for Snowflake's durable acknowledgement;
110
+ keep the source events until the call succeeds so the caller can decide how to
111
+ recover from a failure or timeout.
112
+
113
+ ## Submit Circle USDC payouts
114
+
115
+ Use Circle TESTNET credentials for development. Configure a separate client,
116
+ wallet set, and credentials for each environment. The entity secret and API key
117
+ must come from a secret manager or the Home Assistant integration's protected
118
+ configuration; never expose them in frontend code or logs.
119
+
120
+ ```python
121
+ from datacents import CircleConfig, CirclePaymentsClient
122
+
123
+ payments = CirclePaymentsClient(
124
+ CircleConfig(
125
+ api_key="read from a secret store",
126
+ entity_secret="64 hexadecimal characters from a secret store",
127
+ environment="TESTNET",
128
+ blockchain="ARC-TESTNET",
129
+ token_address="the configured USDC token contract",
130
+ source_wallet_id="the platform payout wallet ID",
131
+ source_wallet_address="the platform payout wallet address",
132
+ )
133
+ )
134
+
135
+ payout = payments.transfer_usdc(
136
+ contributor_id="hashed_contributor_id",
137
+ destination_address="verified_contributor_address",
138
+ amount_atomic=5_000_000, # 5 USDC (six decimal places)
139
+ )
140
+ ```
141
+
142
+ Transfers use a fresh UUID v4 idempotency key and wait until Circle reports a
143
+ terminal state. Only `COMPLETE` is returned as a successful payout. A polling
144
+ timeout includes the transaction ID and idempotency key so the existing
145
+ transaction can be resumed rather than submitted again.
146
+
147
+ MAINNET transfers require an exact confirmation string from
148
+ `CirclePaymentsClient.mainnet_confirmation(...)` for the chain, token, source
149
+ wallet, destination, and amount. USDC amounts are integers in atomic units;
150
+ floating-point amounts are not accepted.
151
+
152
+ ## Development
153
+
154
+ Run the unit tests with:
155
+
156
+ ```shell
157
+ PYTHONPATH=src python -m unittest discover -s tests
158
+ ```
159
+
160
+ ## Publishing
161
+
162
+ The GitHub Actions workflow runs when changes reach `main`, including after a
163
+ PR merge. It builds and validates both distribution formats and runs the tests
164
+ on each push. It publishes to PyPI only when the version in `pyproject.toml`
165
+ increases from the previous `main` commit; version decreases fail the workflow.
166
+
167
+ Before the first release:
168
+
169
+ 1. In PyPI account settings, add a trusted publisher for project `py-datacents`,
170
+ owner `djstearns`, repository `py-datacents`, workflow `publish.yml`, and
171
+ GitHub environment `pypi`.
172
+ 2. Create the `pypi` environment in GitHub repository settings and configure
173
+ required reviewers for release approval.
174
+ 3. Increase the version in `pyproject.toml` in a release PR, merge it to
175
+ `main`, and approve the workflow deployment.
176
+
177
+ The workflow uses PyPI Trusted Publishing (OIDC); it does not require a stored
178
+ PyPI API token.
@@ -0,0 +1,9 @@
1
+ datacents/__init__.py,sha256=Wee-hb1IqYB1KMjkqKHZXRN5227iklTMfFZH_O8ptiI,661
2
+ datacents/circle.py,sha256=414asv_rjcLpK8UeghINhhXWGoBfdhZwmOkotsghEiU,11720
3
+ datacents/events.py,sha256=0d1KyIlct025gA0Kd8ZAPI-FyFfR5i5O18GMegLCfbo,23924
4
+ datacents/snowpipe.py,sha256=-K4Lz7AxjuUrTAWN_oqqhW0HxlAz3lPe3EMLAp0QC5U,5059
5
+ py_datacents-0.1.0.dist-info/licenses/LICENSE,sha256=P6ltfyTCpsl3C8y07KD5zJpmHB4mBTYvHVFF_12PyRY,1070
6
+ py_datacents-0.1.0.dist-info/METADATA,sha256=0hKgGycQuhfEmRVqqvY5GcVo3Fchd3v1fDcNhsgdkro,6185
7
+ py_datacents-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ py_datacents-0.1.0.dist-info/top_level.txt,sha256=9LCQNDyupxDlHQ5dXn6oRBYWckQiDF8PvqzItfWglgw,10
9
+ py_datacents-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Derek Stearns
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
+ datacents