py-datacentslib 0.0.1__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/events.py ADDED
@@ -0,0 +1,671 @@
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
+ "weather.weather_sensor_readings": _dataset(
338
+ "weather",
339
+ "weather_sensor_readings",
340
+ 1000,
341
+ {
342
+ "event_id": "EVENT_ID",
343
+ "contributor_id": "CONTRIBUTOR_ID",
344
+ "event_timestamp": "EVENT_TIMESTAMP",
345
+ "sensor_id": "SENSOR_ID",
346
+ "measurement_type": "MEASUREMENT_TYPE",
347
+ "value_number": "VALUE_NUMBER",
348
+ "value_text": "VALUE_TEXT",
349
+ "unit": "UNIT",
350
+ "location.country": "COUNTRY",
351
+ "location.state_province": "STATE_PROVINCE",
352
+ "location.postal_code_prefix": "POSTAL_CODE_PREFIX",
353
+ "location.timezone": "TIMEZONE",
354
+ },
355
+ (
356
+ "event_id",
357
+ "contributor_id",
358
+ "event_timestamp",
359
+ "sensor_id",
360
+ "measurement_type",
361
+ "unit",
362
+ ),
363
+ ),
364
+ }
365
+
366
+
367
+ def _get_path(event: Mapping[str, Any], path: str) -> Any:
368
+ value: Any = event
369
+ for component in path.split("."):
370
+ if not isinstance(value, Mapping) or component not in value:
371
+ return None
372
+ value = value[component]
373
+ return value
374
+
375
+
376
+ def _parse_timestamp(value: Any) -> tuple[datetime, str]:
377
+ if isinstance(value, datetime):
378
+ parsed = value
379
+ elif isinstance(value, str):
380
+ try:
381
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
382
+ except ValueError as exc:
383
+ raise EventValidationError("timestamp must be an ISO 8601 datetime") from exc
384
+ else:
385
+ raise EventValidationError("timestamp must be an ISO 8601 datetime")
386
+
387
+ if parsed.tzinfo is None or parsed.utcoffset() is None:
388
+ raise EventValidationError("timestamp must include a timezone")
389
+ parsed = parsed.astimezone(timezone.utc)
390
+ return parsed, parsed.isoformat()
391
+
392
+
393
+ def _number(value: Any, path: str) -> float:
394
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
395
+ raise EventValidationError(f"{path} must be a number")
396
+ if not math.isfinite(value):
397
+ raise EventValidationError(f"{path} must be finite")
398
+ return value
399
+
400
+
401
+ def _validate_private_fields(dataset_name: str, event: Mapping[str, Any]) -> None:
402
+ if dataset_name.startswith("utilities."):
403
+ postal_prefix = _get_path(event, "location.postal_code_prefix")
404
+ if not isinstance(postal_prefix, str) or not re.fullmatch(r"\d{3}", postal_prefix):
405
+ raise EventValidationError(
406
+ "postal_code_prefix must contain only the first three digits"
407
+ )
408
+
409
+ if dataset_name == "cybersecurity.network_security_events":
410
+ paths = ("source.ip_prefix", "destination.ip_prefix")
411
+ elif dataset_name == "cybersecurity.authentication_events":
412
+ paths = ("source.ip_prefix",)
413
+ elif dataset_name == "cybersecurity.malware_threat_events":
414
+ paths = ("ioc.ip_prefix",)
415
+ else:
416
+ paths = ()
417
+ for path in paths:
418
+ value = _get_path(event, path)
419
+ if value is not None:
420
+ if not isinstance(value, str):
421
+ raise EventValidationError(f"{path} must be a masked IPv4 prefix")
422
+ match = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.[xX]\.[xX]", value)
423
+ if match is None or any(int(octet) > 255 for octet in match.groups()):
424
+ raise EventValidationError(
425
+ f"{path} must contain only a /16 IPv4 prefix (a.b.x.x)"
426
+ )
427
+
428
+
429
+ def _flatten(
430
+ event: Mapping[str, Any], dataset: Dataset, path: str = ""
431
+ ) -> dict[str, Any]:
432
+ flattened: dict[str, Any] = {}
433
+ for key, value in event.items():
434
+ if not isinstance(key, str):
435
+ raise EventValidationError("event field names must be strings")
436
+ current_path = f"{path}.{key}" if path else key
437
+ if isinstance(value, Mapping):
438
+ if not value and not any(
439
+ column.startswith(f"{current_path}.")
440
+ for column in dataset.columns
441
+ ):
442
+ raise EventValidationError(
443
+ f"field {current_path!r} is not defined by the "
444
+ "data-product specification"
445
+ )
446
+ flattened.update(_flatten(value, dataset, current_path))
447
+ continue
448
+ if current_path not in dataset.columns:
449
+ raise EventValidationError(
450
+ f"field {current_path!r} is not defined by the "
451
+ "data-product specification"
452
+ )
453
+ if current_path in {"timestamp", "event_timestamp"}:
454
+ parsed, value = _parse_timestamp(value)
455
+ if dataset.product == "cybersecurity":
456
+ parsed = (parsed + timedelta(seconds=30)).replace(
457
+ second=0, microsecond=0
458
+ )
459
+ value = parsed.isoformat()
460
+ flattened[dataset.columns[current_path]] = value
461
+ return flattened
462
+
463
+
464
+ def _validate_event(dataset_name: str, event: Mapping[str, Any]) -> dict[str, Any]:
465
+ dataset = DATASETS[dataset_name]
466
+ if not isinstance(event, Mapping):
467
+ raise EventValidationError("each event must be a mapping")
468
+
469
+ for path in dataset.required:
470
+ if _get_path(event, path) is None:
471
+ raise EventValidationError(f"required field {path!r} is missing")
472
+
473
+ event_id = _get_path(event, "event_id")
474
+ if not isinstance(event_id, str):
475
+ raise EventValidationError("event_id must be a UUID string")
476
+ try:
477
+ event_id = str(UUID(event_id))
478
+ except ValueError as exc:
479
+ raise EventValidationError("event_id must be a UUID string") from exc
480
+ contributor_id = _get_path(event, "contributor_id")
481
+ if not isinstance(contributor_id, str) or not contributor_id.strip():
482
+ raise EventValidationError("contributor_id must be a non-empty hashed ID")
483
+
484
+ timestamp_path = (
485
+ "event_timestamp" if dataset_name == "weather.weather_sensor_readings" else "timestamp"
486
+ )
487
+ parsed_timestamp, _ = _parse_timestamp(_get_path(event, timestamp_path))
488
+ if dataset.product == "utilities":
489
+ now = datetime.now(timezone.utc)
490
+ try:
491
+ oldest_allowed = now.replace(year=now.year - 10)
492
+ except ValueError:
493
+ oldest_allowed = now.replace(year=now.year - 10, day=28)
494
+ if parsed_timestamp > now:
495
+ raise EventValidationError("timestamp cannot be in the future")
496
+ if parsed_timestamp < oldest_allowed:
497
+ raise EventValidationError("timestamp cannot be more than 10 years old")
498
+
499
+ if dataset_name == "utilities.electric_usage_events":
500
+ power_w = _number(_get_path(event, "power_w"), "power_w")
501
+ energy_kwh = _number(_get_path(event, "energy_kwh"), "energy_kwh")
502
+ if power_w < 0 or power_w >= 50_000:
503
+ raise EventValidationError("power_w must be >= 0 and < 50000")
504
+ if energy_kwh < 0:
505
+ raise EventValidationError("energy_kwh must be non-negative")
506
+ reading_type = _get_path(event, "reading_type")
507
+ if not isinstance(reading_type, str) or reading_type not in {
508
+ "instantaneous",
509
+ "cumulative",
510
+ }:
511
+ raise EventValidationError("reading_type must be instantaneous or cumulative")
512
+ elif dataset_name == "utilities.water_usage_events":
513
+ flow_rate = _number(_get_path(event, "flow_rate_lpm"), "flow_rate_lpm")
514
+ volume_liters = _number(_get_path(event, "volume_liters"), "volume_liters")
515
+ if flow_rate < 0 or flow_rate >= 100:
516
+ raise EventValidationError("flow_rate_lpm must be >= 0 and < 100")
517
+ if volume_liters < 0:
518
+ raise EventValidationError("volume_liters must be non-negative")
519
+ reading_type = _get_path(event, "reading_type")
520
+ if not isinstance(reading_type, str) or reading_type not in {
521
+ "instantaneous",
522
+ "cumulative",
523
+ }:
524
+ raise EventValidationError("reading_type must be instantaneous or cumulative")
525
+ elif dataset_name == "weather.weather_sensor_readings":
526
+ measurement_type = _get_path(event, "measurement_type")
527
+ units = {
528
+ "temperature": "C",
529
+ "dew_point": "C",
530
+ "humidity": "%",
531
+ "pressure": "hPa",
532
+ "wind_speed": "m/s",
533
+ "wind_gust": "m/s",
534
+ "precipitation": "mm",
535
+ "uv_index": "index",
536
+ "visibility": "km",
537
+ "condition": "condition",
538
+ }
539
+ if not isinstance(measurement_type, str) or measurement_type not in units:
540
+ raise EventValidationError("measurement_type is not supported")
541
+ if _get_path(event, "unit") != units[measurement_type]:
542
+ raise EventValidationError(
543
+ f"unit for {measurement_type} must be {units[measurement_type]!r}"
544
+ )
545
+ value_number = _get_path(event, "value_number")
546
+ value_text = _get_path(event, "value_text")
547
+ if measurement_type == "condition":
548
+ if value_number is not None or not isinstance(value_text, str) or not value_text:
549
+ raise EventValidationError(
550
+ "condition readings require value_text and null value_number"
551
+ )
552
+ else:
553
+ if value_text is not None:
554
+ raise EventValidationError(
555
+ "numeric readings require null value_text"
556
+ )
557
+ _number(value_number, "value_number")
558
+ sensor_id = _get_path(event, "sensor_id")
559
+ if not isinstance(sensor_id, str) or not sensor_id.strip():
560
+ raise EventValidationError("sensor_id must be a non-empty pseudonymous ID")
561
+ postal_prefix = _get_path(event, "location.postal_code_prefix")
562
+ if postal_prefix is not None and (
563
+ not isinstance(postal_prefix, str) or len(postal_prefix) > 3
564
+ ):
565
+ raise EventValidationError(
566
+ "postal_code_prefix must contain at most the first three characters"
567
+ )
568
+
569
+ if dataset_name == "content.media_playback_events":
570
+ event_type = _get_path(event, "event_type")
571
+ if not isinstance(event_type, str) or event_type not in {
572
+ "play",
573
+ "pause",
574
+ "stop",
575
+ "skip",
576
+ "seek",
577
+ "complete",
578
+ }:
579
+ raise EventValidationError("event_type is not a supported media event")
580
+ media_type = _get_path(event, "media_type")
581
+ if not isinstance(media_type, str) or media_type not in {
582
+ "movie",
583
+ "tv_show",
584
+ "music",
585
+ "podcast",
586
+ "audiobook",
587
+ "youtube",
588
+ "game",
589
+ }:
590
+ raise EventValidationError("media_type is not supported")
591
+ percentage = _get_path(event, "playback_metadata.completion_percentage")
592
+ if percentage is not None:
593
+ percentage = _number(percentage, "completion_percentage")
594
+ if not 0 <= percentage <= 100:
595
+ raise EventValidationError(
596
+ "completion_percentage must be between 0 and 100"
597
+ )
598
+ played = _get_path(event, "playback_metadata.playback_duration_seconds")
599
+ duration = _get_path(event, "content_metadata.duration_seconds")
600
+ if played is not None and duration is not None:
601
+ played = _number(played, "playback_duration_seconds")
602
+ duration = _number(duration, "duration_seconds")
603
+ if played > duration * 1.1:
604
+ raise EventValidationError(
605
+ "playback duration cannot exceed content duration by more than 10%"
606
+ )
607
+ elif dataset_name == "content.voice_assistant_interactions":
608
+ assistant_type = _get_path(event, "assistant_type")
609
+ if not isinstance(assistant_type, str) or assistant_type not in {
610
+ "alexa",
611
+ "google_assistant",
612
+ "siri",
613
+ }:
614
+ raise EventValidationError("assistant_type is not supported")
615
+ elif dataset_name == "content.content_discovery_events":
616
+ discovery_method = _get_path(event, "discovery_method")
617
+ if not isinstance(discovery_method, str) or discovery_method not in {
618
+ "browse",
619
+ "search",
620
+ "recommendation",
621
+ "autoplay",
622
+ "notification",
623
+ }:
624
+ raise EventValidationError("discovery_method is not supported")
625
+
626
+ if dataset_name == "cybersecurity.network_security_events":
627
+ severity = _get_path(event, "severity")
628
+ if not isinstance(severity, str) or severity not in {
629
+ "low",
630
+ "medium",
631
+ "high",
632
+ "critical",
633
+ }:
634
+ raise EventValidationError("severity must be low, medium, high, or critical")
635
+
636
+ _validate_private_fields(dataset_name, event)
637
+ return _flatten(event, dataset)
638
+
639
+
640
+ def validate_and_flatten_batch(
641
+ dataset_name: str, events: Sequence[Mapping[str, Any]]
642
+ ) -> list[dict[str, Any]]:
643
+ """Validate a batch against a data-product schema and map it to columns."""
644
+ try:
645
+ dataset = DATASETS[dataset_name]
646
+ except KeyError as exc:
647
+ raise EventValidationError(f"unknown dataset {dataset_name!r}") from exc
648
+
649
+ if len(events) > dataset.max_batch_size:
650
+ raise EventValidationError(
651
+ f"{dataset_name} accepts at most {dataset.max_batch_size} events per batch"
652
+ )
653
+ if not events:
654
+ return []
655
+
656
+ rows = [_validate_event(dataset_name, event) for event in events]
657
+ for row in rows:
658
+ row["EVENT_ID"] = str(UUID(row["EVENT_ID"]))
659
+ event_ids = [row["EVENT_ID"] for row in rows]
660
+ if len(event_ids) != len(set(event_ids)):
661
+ raise EventValidationError("a batch cannot contain duplicate event_id values")
662
+
663
+ if dataset.product == "utilities":
664
+ contributor_timestamps = [
665
+ (row["CONTRIBUTOR_ID"], row["TIMESTAMP"]) for row in rows
666
+ ]
667
+ if len(contributor_timestamps) != len(set(contributor_timestamps)):
668
+ raise EventValidationError(
669
+ "a batch cannot contain duplicate contributor/timestamp readings"
670
+ )
671
+ return rows