-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_optimization_sync.bzl
More file actions
2963 lines (2650 loc) · 127 KB
/
Copy pathtest_optimization_sync.bzl
File metadata and controls
2963 lines (2650 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Unless explicitly stated otherwise all files in this repository are licensed under
# the Apache 2.0 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.
"""Datadog Test Optimization repository rule helpers and module extension.
This file defines:
- A repository_rule (`test_optimization_sync`) that performs one or more
authenticated HTTP POST requests to Datadog to retrieve Test Optimization
metadata.
- Reusable helpers for building curl commands, ensuring output directories
exist, and parsing JSON in Starlark.
- A first request to the Settings API which always runs and writes
`settings_file`.
- An optional second request to the Known Tests API when the settings say
`known_tests_enabled = true`, writing `known_tests_file`. If disabled, an
empty JSON stub for known tests is still written so downstream consumers
can always depend on the declared outputs.
- An optional request to the Flaky Tests API when the settings say
`flaky_test_retries_enabled = true`, writing `flaky_tests_file`. The raw
backend response is persisted as-is; per-module files are derived afterward.
Repository-rule execution model:
- This code runs during Bazel repository/module resolution, not test runtime.
- It must therefore be deterministic given the declared `environ` inputs and
repository attributes.
- Network and host-tool access happen here so test actions can remain hermetic.
High-level data flow:
1) Resolve env/context metadata (CI + Git + runtime hints)
2) Fetch settings JSON
3) Optionally fetch known-tests, test-management, and flaky-tests JSON
4) Split module payloads into stable per-module bundles
5) Generate BUILD/export/context/manifest outputs for consumers
Important invariants:
- Secrets are never written to generated files (API key is used only in-memory
for requests).
- Public label names are stable (`test_optimization_files`,
`test_optimization_context`, `module_<sanitized>`).
- Output JSONs are generated in deterministic key/order-sensitive paths to keep
cache behavior predictable.
Troubleshooting guidance for maintainers:
- Failures in this file are often due to environment/configuration drift
(missing `DD_API_KEY`, wrong `DD_SITE`, stale refs) rather than logic bugs.
- Keep `fail(...)` messages explicit and user-actionable.
"""
# Developer map (quick navigation):
# - Filesystem helpers: `_ensure_parent_directory`, `_dirname`, `_try_read_abs_file`
# - Go/rules metadata helpers: `_detect_go_module_path`, `_build_context_tags`
# - HTTP helpers: `_http_request`, `_http_post_json`
# - API calls: `_perform_dd_settings_request`, `_perform_dd_known_tests_request`,
# `_perform_dd_test_management_tests_request`, `_perform_dd_flaky_tests_request`
# - Repository entrypoint: `_impl`
load(
"//tools/core:common_utils.bzl",
"RULES_VERSION",
"dedup_keys",
"fail_with_prefix",
"log_debug",
"log_info",
"sanitize_label_fragment",
"validate_api_key",
"validate_runtime_name",
"validate_runtime_version",
"validate_service_name",
_is_dict = "is_dict",
)
load(
"//tools/core:test_optimization_sync_env.bzl",
_ALL_SYNC_ENV_KEYS = "ALL_SYNC_ENV_KEYS",
_apply_dd_git_overrides = "apply_dd_git_overrides",
_apply_github_event_payload = "apply_github_event_payload",
_collect_env_from_environ = "collect_env_from_environ",
_first_env = "first_env",
_first_env_from_environ = "first_env_from_environ",
_normalize_env_data = "normalize_env_data",
_normalize_ref = "normalize_ref",
_sanitize_repository_url = "sanitize_repository_url",
_set_context_tag_from_env = "set_context_tag_from_env",
)
# ##########################################################################
# Constants
# ##########################################################################
TEST_OPT_DIR = ".testoptimization"
TEST_BAZEL_RULE_NAME = "datadog-rules-test-optimization"
TEST_BAZEL_RULE_VERSION = RULES_VERSION
# Shared HTTP timing/retry policy for both curl and Invoke-WebRequest paths.
HTTP_CONNECT_TIMEOUT_SECONDS = 10
HTTP_MAX_TIME_SECONDS = 60
HTTP_RETRY_ATTEMPTS = 3
HTTP_RETRY_DELAY_SECONDS = 2
# Keep outer execute timeout above worst-case retry budget to avoid cutting
# transport retries short on slower hosts/CI workers.
HTTP_EXECUTE_TIMEOUT_BUFFER_SECONDS = 60
HTTP_EXECUTE_TIMEOUT_SECONDS = (
# Curl/PowerShell both do one initial attempt plus `retry_attempts` retries.
((HTTP_RETRY_ATTEMPTS + 1) * HTTP_MAX_TIME_SECONDS) +
(HTTP_RETRY_ATTEMPTS * HTTP_RETRY_DELAY_SECONDS) +
HTTP_EXECUTE_TIMEOUT_BUFFER_SECONDS
)
# Sentinel value used by optional integer attrs where 0 can be meaningful.
HTTP_POLICY_ATTR_UNSET = -1
# ##########################################################################
# Tools functions
# ##########################################################################
def _parse_int_from_env_or_fail(env_key, raw_value):
"""Parse a base-10 integer from an environment variable value."""
s = (raw_value or "").strip()
if not s:
fail_with_prefix("test_optimization_sync", "%s must be a non-empty integer when set" % env_key)
start = 1 if s.startswith("-") else 0
if start == len(s):
fail_with_prefix("test_optimization_sync", "%s must be a valid integer, got %s" % (env_key, repr(raw_value)))
for i in range(start, len(s)):
ch = s[i]
if ch < "0" or ch > "9":
fail_with_prefix("test_optimization_sync", "%s must be a valid integer, got %s" % (env_key, repr(raw_value)))
return int(s)
def _resolve_http_int_setting(ctx, attr_name, env_key, default_value, allow_zero = False):
"""Resolve one HTTP policy integer from attr/env/default with validation."""
attr_value = getattr(ctx.attr, attr_name, HTTP_POLICY_ATTR_UNSET)
if attr_value != HTTP_POLICY_ATTR_UNSET:
value = attr_value
source = "attribute %s" % attr_name
else:
env_value = (ctx.os.environ.get(env_key) or "").strip()
if env_value:
value = _parse_int_from_env_or_fail(env_key, env_value)
source = "environment %s" % env_key
else:
value = default_value
source = "default"
if allow_zero:
if value < 0:
fail_with_prefix("test_optimization_sync", "%s must be >= 0 (from %s), got %d" % (attr_name, source, value))
elif value <= 0:
fail_with_prefix("test_optimization_sync", "%s must be > 0 (from %s), got %d" % (attr_name, source, value))
return value
def _resolve_http_policy(ctx):
"""Resolve effective HTTP timeout/retry policy from attrs/env/defaults."""
connect_timeout_seconds = _resolve_http_int_setting(
ctx,
"http_connect_timeout_seconds",
"DD_TEST_OPTIMIZATION_HTTP_CONNECT_TIMEOUT_SECONDS",
HTTP_CONNECT_TIMEOUT_SECONDS,
)
max_time_seconds = _resolve_http_int_setting(
ctx,
"http_max_time_seconds",
"DD_TEST_OPTIMIZATION_HTTP_MAX_TIME_SECONDS",
HTTP_MAX_TIME_SECONDS,
)
retry_attempts = _resolve_http_int_setting(
ctx,
"http_retry_attempts",
"DD_TEST_OPTIMIZATION_HTTP_RETRY_ATTEMPTS",
HTTP_RETRY_ATTEMPTS,
)
retry_delay_seconds = _resolve_http_int_setting(
ctx,
"http_retry_delay_seconds",
"DD_TEST_OPTIMIZATION_HTTP_RETRY_DELAY_SECONDS",
HTTP_RETRY_DELAY_SECONDS,
allow_zero = True,
)
execute_timeout_buffer_seconds = _resolve_http_int_setting(
ctx,
"http_execute_timeout_buffer_seconds",
"DD_TEST_OPTIMIZATION_HTTP_EXECUTE_TIMEOUT_BUFFER_SECONDS",
HTTP_EXECUTE_TIMEOUT_BUFFER_SECONDS,
allow_zero = True,
)
execute_timeout_seconds = (
# Retry budget = initial attempt + N retries.
((retry_attempts + 1) * max_time_seconds) +
(retry_attempts * retry_delay_seconds) +
execute_timeout_buffer_seconds
)
return {
"connect_timeout_seconds": connect_timeout_seconds,
"max_time_seconds": max_time_seconds,
"retry_attempts": retry_attempts,
"retry_delay_seconds": retry_delay_seconds,
"execute_timeout_buffer_seconds": execute_timeout_buffer_seconds,
"execute_timeout_seconds": execute_timeout_seconds,
}
def _curl_base_args(policy):
"""Return the shared curl argument baseline for sync API calls.
Keep this in one helper so timeout/retry policy stays consistent across
settings/known-tests/test-management requests.
"""
# _curl_base_args: returns common curl flags applied to all HTTP requests
# -f: fail on HTTP errors (>= 400)
# -sS: silent, but show errors
# retry/backoff: basic robustness against transient failures
return [
"curl",
"-f",
"-sS",
"--connect-timeout",
str(policy["connect_timeout_seconds"]),
"--max-time",
str(policy["max_time_seconds"]),
"--retry",
str(policy["retry_attempts"]),
"--retry-delay",
str(policy["retry_delay_seconds"]),
"--retry-connrefused",
]
def _is_windows(ctx):
"""Best-effort repository-host Windows detection."""
# _is_windows: prefer repository_ctx.os.name, then fall back to env heuristics.
os_name = (getattr(ctx.os, "name", "") or "").lower()
if "windows" in os_name:
return True
os_env = (ctx.os.environ.get("OS") or "").lower()
comspec = (ctx.os.environ.get("ComSpec") or ctx.os.environ.get("COMSPEC") or "").lower()
return ("windows" in os_env) or comspec.endswith("cmd.exe")
_FINGERPRINT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_:/.+@=#%~!$^*()[]{}<>?,;|\\\"'` "
def _powershell_single_quote_literal(value):
"""Escape value for safe use inside a single-quoted PowerShell string."""
return (value or "").replace("'", "''")
def _fnv1a_32(value):
"""Compute a deterministic non-cryptographic 32-bit hash.
Used only for context fingerprinting; this is *not* a security primitive.
"""
# FNV-1a style 32-bit hash for stable fingerprinting (non-cryptographic).
# Starlark lacks ord()/bytes, so map characters via a fixed alphabet.
h = 2166136261
vlen = len(value)
for i in range(vlen):
ch = value[i]
idx = _FINGERPRINT_ALPHABET.find(ch)
if idx < 0:
# Spread unknown characters across a few deterministic buckets
# instead of collapsing all to one index.
idx = len(_FINGERPRINT_ALPHABET) + (i % 7)
h = h ^ idx
h = (h * 16777619) & 0xffffffff
return h
def _clone_payload_with_detached_attributes(obj):
"""Deep-clone payload object so module mutations never leak to source."""
return _clone_json_like(obj)
def _clone_json_like(value):
"""Clone dict/list payload nodes via JSON round-trip; scalars pass through."""
if _is_dict(value) or type(value) == type([]):
return json.decode(json.encode(value))
return value
def _hex32(value):
"""Format a 32-bit integer as lowercase 8-char hex."""
digits = "0123456789abcdef"
out = ""
v = value
for _ in range(8):
out = digits[v & 0xf] + out
v = v >> 4
return out
def _api_key_fingerprint(api_key):
"""Return a non-reversible stable fingerprint for an API key value."""
if not api_key:
return ""
return _hex32(_fnv1a_32(api_key))
def _ensure_parent_directory(ctx, path, debug):
"""Ensure parent directory exists for a generated output file path.
This helper is cross-platform: Unix uses `mkdir -p`; Windows uses
PowerShell `New-Item -ItemType Directory -Force`.
"""
# Create parent directory for a given file path if needed.
# Starlark has no os.path utilities; use simple split/join.
if not path:
return
normalized_path = path.replace("\\", "/")
# Normalize path segments and drop empty/"." parts
segments = [s for s in normalized_path.split("/") if (s != "" and s != ".")]
if len(segments) <= 1:
return
dirp = "/".join(segments[:-1])
if _is_windows(ctx):
# On Windows use PowerShell New-Item to create intermediate directories robustly
win_dir = dirp.replace("/", "\\")
ps_cmd = [
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
"New-Item -ItemType Directory -Force -Path '%s' | Out-Null" % _powershell_single_quote_literal(win_dir),
]
res = ctx.execute(ps_cmd)
else:
res = ctx.execute(["mkdir", "-p", dirp])
log_debug(debug, "filesystem", "Ensured directory '%s' for output '%s' (rc=%d)" % (dirp, path, res.return_code))
if res.return_code != 0:
fail_with_prefix("test_optimization_sync", "Failed creating directory %s for output %s: %s" % (dirp, path, (res.stderr or "").strip()))
def _dirname(path):
"""Return parent directory using simple Starlark path operations."""
# _dirname: return parent directory component of a path using simple split
if not path:
return ""
segs = [s for s in path.split("/") if (s != "" and s != ".")]
if len(segs) <= 1:
return ""
return "/".join(segs[:-1])
def _normalize_out_dir_or_fail(out_dir):
"""Validate and normalize sync `out_dir` into a safe relative path."""
# Keep output paths predictable and avoid traversal/absolute path inputs.
raw = (out_dir or "").strip()
if not raw:
fail_with_prefix("test_optimization_sync", "out_dir must be a non-empty relative path")
for ch in ["\n", "\r", "\t"]:
if ch in raw:
fail_with_prefix("test_optimization_sync", "out_dir must not contain control characters: %s" % repr(out_dir))
normalized = raw.replace("\\", "/")
if normalized.startswith("/"):
fail_with_prefix("test_optimization_sync", "out_dir must be relative (absolute paths are not allowed): %s" % repr(out_dir))
if len(normalized) >= 2 and normalized[1] == ":":
fail_with_prefix("test_optimization_sync", "out_dir must not include a Windows drive prefix: %s" % repr(out_dir))
segments = []
for seg in normalized.split("/"):
if seg == "" or seg == ".":
continue
if seg == "..":
fail_with_prefix("test_optimization_sync", "out_dir must not contain '..' path traversal segments: %s" % repr(out_dir))
segments.append(seg)
if not segments:
fail_with_prefix("test_optimization_sync", "out_dir must resolve to a non-empty relative path: %s" % repr(out_dir))
return "/".join(segments)
def _bzl_string_literal(value):
"""Return a safely escaped double-quoted Starlark string literal."""
return json.encode(str(value or ""))
def _validate_abs_path_command_input_or_fail(abs_path):
"""Fail fast when absolute path contains control characters."""
if not abs_path:
return
if ("\n" in abs_path) or ("\r" in abs_path) or ("\t" in abs_path):
fail_with_prefix("test_optimization_sync", "absolute path contains unsupported control characters: %s" % repr(abs_path))
def _try_read_abs_file(ctx, abs_path):
"""Best-effort absolute file read with explicit miss/read-error signaling."""
# Returns a status dict:
# - ok: bool (read command succeeded)
# - missing: bool (path does not exist)
# - value: file content when ok
# - error: diagnostic for non-missing failures
if not abs_path:
return {"ok": False, "missing": True, "value": "", "error": "empty path"}
if _is_windows(ctx):
exists_cmd = _build_windows_exists_abs_file_command(abs_path)
exists_res = ctx.execute([
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
exists_cmd,
])
if exists_res.return_code == 3:
return {"ok": False, "missing": True, "value": "", "error": ""}
if exists_res.return_code != 0:
err = (exists_res.stderr or "").strip() or ("exists-check failed with exit code %d" % exists_res.return_code)
log_info("warning: unable to check file '%s': %s" % (abs_path, err))
return {"ok": False, "missing": False, "value": "", "error": err}
ps_cmd = _build_windows_read_abs_file_command(abs_path)
cmd = [
"powershell.exe",
"-NoProfile",
"-NonInteractive",
"-Command",
ps_cmd,
]
res = ctx.execute(cmd)
if res.return_code == 0:
return {"ok": True, "missing": False, "value": res.stdout or "", "error": ""}
err = (res.stderr or "").strip() or ("file read failed with exit code %d" % res.return_code)
log_info("warning: unable to read file '%s': %s" % (abs_path, err))
return {"ok": False, "missing": False, "value": "", "error": err}
else:
exists_cmd = _build_unix_exists_abs_file_command(abs_path)
exists_res = ctx.execute(["/bin/sh", "-c", exists_cmd])
if exists_res.return_code == 3:
return {"ok": False, "missing": True, "value": "", "error": ""}
if exists_res.return_code != 0:
err = (exists_res.stderr or "").strip() or ("exists-check failed with exit code %d" % exists_res.return_code)
log_info("warning: unable to check file '%s': %s" % (abs_path, err))
return {"ok": False, "missing": False, "value": "", "error": err}
sh_cmd = _build_unix_read_abs_file_command(abs_path)
res = ctx.execute(["/bin/sh", "-c", sh_cmd])
if res.return_code == 0:
return {"ok": True, "missing": False, "value": res.stdout or "", "error": ""}
err = (res.stderr or "").strip() or ("file read failed with exit code %d" % res.return_code)
log_info("warning: unable to read file '%s': %s" % (abs_path, err))
return {"ok": False, "missing": False, "value": "", "error": err}
def _build_windows_exists_abs_file_command(abs_path):
"""Build PowerShell command string for absolute-file existence checks."""
_validate_abs_path_command_input_or_fail(abs_path)
return "$p = '%s'; if (Test-Path -LiteralPath $p -PathType Leaf) { exit 0 } else { exit 3 }" % _powershell_single_quote_literal(abs_path)
def _build_unix_exists_abs_file_command(abs_path):
"""Build POSIX shell command string for absolute-file existence checks."""
_validate_abs_path_command_input_or_fail(abs_path)
escaped = abs_path.replace("'", "'\\''")
return "[ -f '" + escaped + "' ] || exit 3"
def _build_windows_read_abs_file_command(abs_path):
"""Build PowerShell command string for `_try_read_abs_file` reads."""
_validate_abs_path_command_input_or_fail(abs_path)
# Security note: single quotes are doubled for PowerShell literal strings.
return "$p = '%s'; Get-Content -Raw -LiteralPath $p" % _powershell_single_quote_literal(abs_path)
def _build_unix_read_abs_file_command(abs_path):
"""Build shell command string for `_try_read_abs_file` reads."""
_validate_abs_path_command_input_or_fail(abs_path)
# Security note: single quotes are escaped using the POSIX '\'' pattern.
# The escaping contract is covered by `read_abs_file_command_escaping_test`.
escaped = abs_path.replace("'", "'\\''")
return "cat '" + escaped + "'"
def _parse_go_module_path(go_mod_content):
"""Extract `module <path>` value from go.mod content."""
# _parse_go_module_path: extract the module path from a go.mod content string.
if not go_mod_content:
return ""
lines = go_mod_content.split("\n")
for ln in lines:
s = ln.strip()
if not s or s.startswith("//"):
continue
if s.startswith("module ") or s.startswith("module\t"):
rest = s[len("module"):].strip()
# Trim optional quotes
if len(rest) >= 2 and rest[0] == '"' and rest[-1] == '"':
rest = rest[1:-1]
return rest
return ""
def _detect_go_module_path(ctx, debug, runtime_module_path = ""):
"""Best-effort Go module path detection for export metadata.
Precedence:
1) `GO_MODULE_PATH` override
2) `runtime_module_path` attr
3) go.mod in known CI workspace directories
4) go.mod under git top-level directory
"""
mod_env = ctx.os.environ.get("GO_MODULE_PATH") or ""
log_debug(debug, "go", "GO_MODULE_PATH env: %s" % (mod_env or "<unset>"))
if mod_env:
log_debug(debug, "go", "Using GO_MODULE_PATH from env")
return mod_env
explicit_module_path = (runtime_module_path or "").strip()
log_debug(debug, "go", "runtime_module_path attr: %s" % (explicit_module_path or "<unset>"))
if explicit_module_path:
log_debug(debug, "go", "Using runtime_module_path attr")
return explicit_module_path
# Candidate workspace roots
candidates = []
for k in [
"CI_PROJECT_DIR",
"GITHUB_WORKSPACE",
"WORKSPACE",
"BUILDKITE_BUILD_CHECKOUT_PATH",
"TRAVIS_BUILD_DIR",
]:
v = ctx.os.environ.get(k)
if v and (v not in candidates):
candidates.append(v)
for root in candidates:
go_mod_path = root.rstrip("/") + "/go.mod"
log_debug(debug, "go", "Checking go.mod at: %s" % go_mod_path)
read_result = _try_read_abs_file(ctx, go_mod_path)
if read_result.get("ok"):
content = read_result.get("value") or ""
mp = _parse_go_module_path(content)
if mp:
log_debug(debug, "go", "Detected module path '%s' from %s" % (mp, go_mod_path))
return mp
# Fallback: try using git to find toplevel go.mod.
top = ""
workspace_root = str(getattr(ctx, "workspace_root", "") or "")
if workspace_root:
r = ctx.execute(["git", "-C", workspace_root, "rev-parse", "--show-toplevel"], timeout = 10)
else:
r = ctx.execute(["git", "rev-parse", "--show-toplevel"], timeout = 10)
if r.return_code == 0 and r.stdout:
top = r.stdout.strip()
log_debug(debug, "go", "git toplevel: %s" % (top or "<unset>"))
if top:
go_mod_path = top.rstrip("/") + "/go.mod"
log_debug(debug, "go", "Checking go.mod at: %s" % go_mod_path)
read_result = _try_read_abs_file(ctx, go_mod_path)
if read_result.get("ok"):
content = read_result.get("value") or ""
mp = _parse_go_module_path(content)
if mp:
log_debug(debug, "go", "Detected module path '%s' from %s" % (mp, go_mod_path))
return mp
log_debug(debug, "go", "Go module path not detected; returning empty")
return ""
def _runtime_module_path_from_environ(environ, env_key):
"""Return a normalized runtime module path override from environment."""
return (environ.get(env_key) or "").strip()
def _detect_runtime_module_path(ctx, debug, runtime_name, env_key, runtime_module_path = ""):
"""Return explicit runtime module path metadata with env-first precedence."""
module_path = _runtime_module_path_from_environ(ctx.os.environ, env_key)
log_debug(debug, runtime_name, "%s env: %s" % (env_key, module_path or "<unset>"))
if module_path:
log_debug(debug, runtime_name, "Using %s from env" % env_key)
return module_path
explicit_module_path = (runtime_module_path or "").strip()
log_debug(debug, runtime_name, "runtime_module_path attr: %s" % (explicit_module_path or "<unset>"))
if explicit_module_path:
log_debug(debug, runtime_name, "Using runtime_module_path attr")
return explicit_module_path
def _split_json_payload_by_module(ctx, source_file, debug, module_key, output_filename, label_map = None):
"""Split one payload JSON map into per-module canonical files."""
specs = []
src_path = ctx.path(source_file)
content = ctx.read(src_path)
if not content or not content.strip():
return specs
# Decode and navigate to data.attributes.<module_key> (map: module -> content map)
obj = _decode_json_object_or_fail(content, source_file)
data_obj = obj.get("data")
if not _is_dict(data_obj):
data_obj = {}
attrs_obj = data_obj.get("attributes")
if not _is_dict(attrs_obj):
attrs_obj = {}
modules_obj = attrs_obj.get(module_key)
if not _is_dict(modules_obj):
modules_obj = {}
if not _is_dict(modules_obj):
return specs
base_dir = _dirname(source_file)
# Ensure deterministic ordering for reproducible BUILD content
module_names = sorted([k for k in modules_obj.keys()])
# Compute sanitized labels and deduplicate (or use provided mapping)
if label_map:
deduped_labels = [label_map.get(m) or sanitize_label_fragment(m) for m in module_names]
else:
raw_labels = [sanitize_label_fragment(m) for m in module_names]
deduped_labels = dedup_keys(raw_labels)
for i in range(len(module_names)):
module_name = module_names[i]
label = deduped_labels[i]
module_content = modules_obj.get(module_name)
# Guard against non-dict anomalies
if not _is_dict(module_content):
continue
# Place per-module canonical-named file under a dedicated subdirectory to avoid collisions
per_module_dir = ("%s/%s" % (base_dir, ("module_%s" % label))) if base_dir else ("module_%s" % label)
out_file = per_module_dir + "/" + output_filename
# Build a per-module JSON that preserves the full original shape
# and only narrows data.attributes.<module_key> to the single module.
new_obj = _clone_payload_with_detached_attributes(obj)
data_obj2 = new_obj.get("data")
if not _is_dict(data_obj2):
data_obj2 = {}
new_obj["data"] = data_obj2
attrs_obj2 = data_obj2.get("attributes")
if not _is_dict(attrs_obj2):
attrs_obj2 = {}
data_obj2["attributes"] = attrs_obj2
attrs_obj2[module_key] = {module_name: module_content}
mod_obj = new_obj
_ensure_parent_directory(ctx, out_file, debug)
ctx.file(out_file, json.encode(mod_obj) + "\n")
log_debug(
debug,
"module",
"Wrote per-module %s file '%s' for module '%s'" % (output_filename, out_file, module_name),
)
specs.append({
"module": module_name,
"label": label,
"file": out_file,
})
return specs
def _split_known_tests_by_module(ctx, known_tests_file, debug, label_map = None):
"""Split aggregate known-tests payload into one file per module."""
return _split_json_payload_by_module(
ctx,
known_tests_file,
debug,
module_key = "tests",
output_filename = "known_tests.json",
label_map = label_map,
)
def _split_test_management_by_module(ctx, test_management_file, debug, label_map = None):
"""Split aggregate test-management payload into one file per module."""
return _split_json_payload_by_module(
ctx,
test_management_file,
debug,
module_key = "modules",
output_filename = "test_management.json",
label_map = label_map,
)
def _split_flaky_tests_by_module(ctx, flaky_tests_file, debug, label_map = None):
"""Split raw flaky-tests payload into one file per module.
Unlike known_tests/test_management which use `_split_json_payload_by_module`
for their `data.attributes.<key>` object payloads, the flaky-tests endpoint
returns `data` as a flat array. This splitter:
- decodes the original raw response from flaky_tests.json
- groups entries by `entry.attributes.configurations.test.bundle`
- ignores malformed entries
- clones the full response envelope (preserving all top-level keys)
- replaces only `new_obj["data"]` with each module's filtered entries
- preserves original entry order within each module's data array
- writes per-module files to `module_<label>/flaky_tests.json`
"""
specs = []
src_path = ctx.path(flaky_tests_file)
content = ctx.read(src_path)
if not content or not content.strip():
return specs
obj = _decode_json_object_or_fail(content, flaky_tests_file)
data_arr = obj.get("data")
if type(data_arr) != type([]):
return specs
# Group entries by module, preserving original order within each group
module_entries = {}
module_order = []
for entry in data_arr:
if not _is_dict(entry):
continue
attrs = entry.get("attributes")
if not _is_dict(attrs):
continue
configs = attrs.get("configurations")
if not _is_dict(configs):
continue
test_config = configs.get("test")
if not _is_dict(test_config):
continue
bundle = test_config.get("bundle") or ""
if not bundle:
continue
if bundle not in module_entries:
module_entries[bundle] = []
module_order.append(bundle)
module_entries[bundle].append(entry)
if not module_entries:
return specs
base_dir = _dirname(flaky_tests_file)
# Deterministic module ordering
module_names = sorted(module_order)
# Compute sanitized labels (use provided mapping or generate fresh)
if label_map:
deduped_labels = [label_map.get(m) or sanitize_label_fragment(m) for m in module_names]
else:
raw_labels = [sanitize_label_fragment(m) for m in module_names]
deduped_labels = dedup_keys(raw_labels)
for i in range(len(module_names)):
module_name = module_names[i]
label = deduped_labels[i]
entries = module_entries[module_name]
per_module_dir = ("%s/%s" % (base_dir, ("module_%s" % label))) if base_dir else ("module_%s" % label)
out_file = per_module_dir + "/flaky_tests.json"
# Clone full response envelope and replace only `data` with filtered entries
new_obj = _clone_json_like(obj)
new_obj["data"] = entries
_ensure_parent_directory(ctx, out_file, debug)
ctx.file(out_file, json.encode(new_obj) + "\n")
log_debug(
debug,
"module",
"Wrote per-module flaky_tests.json file '%s' for module '%s'" % (out_file, module_name),
)
specs.append({
"module": module_name,
"label": label,
"file": out_file,
})
return specs
def _detect_os_info(ctx, debug):
"""Detect host OS platform/version/arch for request configuration tags."""
# _detect_os_info: detect OS platform, version, and architecture using host tools.
# Returns a dict with keys: platform, version, arch
def _run(args):
res = ctx.execute(args)
return res.stdout.strip() if res.return_code == 0 and res.stdout else ""
if _is_windows(ctx):
platform = "windows"
# Windows arch via environment variables
arch = (
ctx.os.environ.get("PROCESSOR_ARCHITECTURE") or
ctx.os.environ.get("PROCESSOR_ARCHITEW6432") or
"unknown"
)
version = ctx.os.environ.get("OS") or ""
log_debug(debug, "os", "Detected OS → platform='%s', version='%s', arch='%s'" % (platform, version, arch))
return {"platform": platform, "version": version, "arch": arch}
raw_platform = _run(["uname", "-s"]) or ""
raw_arch = _run(["uname", "-m"]) or ""
raw_version = _run(["uname", "-r"]) or ""
p = raw_platform.lower()
if "darwin" in p or p == "macos" or p == "mac" or p == "osx":
platform = "darwin"
elif "linux" in p:
platform = "linux"
elif "mingw" in p or "msys" in p or "cygwin" in p or p.startswith("windows"):
platform = "windows"
else:
platform = p or "unknown"
arch = raw_arch or "unknown"
version = raw_version or ""
log_debug(debug, "os", "Detected OS → platform='%s', version='%s', arch='%s'" % (platform, version, arch))
return {"platform": platform, "version": version, "arch": arch}
def _normalize_dd_site_or_fail(site_env):
"""Normalize DD_SITE-like input into a validated hostname."""
site = (site_env or "").strip()
if not site:
return "datadoghq.com"
# Accept full URLs for compatibility with existing caller behavior.
if "://" in site:
site = site.split("://", 1)[1]
if "/" in site:
site = site.split("/", 1)[0]
if "?" in site:
site = site.split("?", 1)[0]
if "#" in site:
site = site.split("#", 1)[0]
if site.startswith("app."):
site = site[len("app."):]
if site.startswith("api."):
site = site[len("api."):]
site = site.lower()
if not site:
fail_with_prefix("test_optimization_sync", "DD_SITE resolved to an empty hostname: %s" % repr(site_env))
if "@" in site:
fail_with_prefix("test_optimization_sync", "DD_SITE must not include credentials/userinfo: %s" % repr(site_env))
if ":" in site:
fail_with_prefix("test_optimization_sync", "DD_SITE must be a hostname without an explicit port: %s" % repr(site_env))
if site.startswith(".") or site.endswith(".") or ".." in site:
fail_with_prefix("test_optimization_sync", "DD_SITE must be a valid hostname: %s" % repr(site_env))
labels = site.split(".")
for label in labels:
if not label:
fail_with_prefix("test_optimization_sync", "DD_SITE must be a valid hostname: %s" % repr(site_env))
if label.startswith("-") or label.endswith("-"):
fail_with_prefix("test_optimization_sync", "DD_SITE labels must not start/end with '-': %s" % repr(site_env))
for i in range(len(label)):
ch = label[i]
is_alpha = (ch >= "a" and ch <= "z")
is_num = (ch >= "0" and ch <= "9")
if not (is_alpha or is_num or ch == "-"):
fail_with_prefix("test_optimization_sync", "DD_SITE contains unsupported hostname character %s in %s" % (repr(ch), repr(site_env)))
return site
def _compute_dd_api_base(site_env):
"""Normalize DD_SITE-like input into Datadog API base URL."""
# _compute_dd_api_base: compute the base Datadog API URL from a site value.
# - Input examples:
# site_env = "app.datadoghq.com" -> returns https://api.datadoghq.com
# site_env = "datadoghq.eu" -> returns https://api.datadoghq.eu
# site_env = None/"" -> returns https://api.datadoghq.com
# - Rationale: users frequently set DD_SITE to app.*; Datadog APIs are under
# api.*. We normalize here for consistency.
site = _normalize_dd_site_or_fail(site_env)
return "https://api.%s" % site
def _resolve_dd_api_base(env_data, debug):
"""Resolve API base URL using override-first precedence."""
# _resolve_dd_api_base: resolve API base URL from overrides or DD_SITE.
override = env_data.get("dd_api_base") or ""
if override:
# Allow tests/dev to point sync requests at a mock server without changing DD_SITE.
base = override.rstrip("/")
log_debug(debug, "http", "DD_TEST_OPTIMIZATION_AGENTLESS_URL override set: %s" % _redact_url_userinfo(base))
return base
return _compute_dd_api_base(env_data.get("dd_site"))
def _resolve_dd_api_base_for_tests(dd_site, dd_api_base):
"""Test helper wrapper for API base resolution."""
# Test helper to validate override behavior deterministically.
env_data = {
"dd_site": dd_site or "",
"dd_api_base": dd_api_base or "",
}
return _resolve_dd_api_base(env_data, False)
def _redact_url_userinfo(url):
"""Remove URL userinfo to keep logs/errors free from credential leaks."""
s = (url or "").strip()
if not s:
return ""
scheme_idx = s.find("://")
if scheme_idx < 0:
return s
auth_start = scheme_idx + 3
end = len(s)
for sep in ["/", "?", "#"]:
idx = s.find(sep, auth_start)
if idx >= 0 and idx < end:
end = idx
authority = s[auth_start:end]
at_idx = -1
for i in range(len(authority)):
if authority[i] == "@":
at_idx = i
if at_idx < 0:
return s
return s[:auth_start] + authority[at_idx + 1:] + s[end:]
def _decode_json_object_or_fail(content, context):
"""Decode JSON and enforce top-level object with actionable failures."""
# Parse API/file JSON with actionable guardrails for malformed responses.
trimmed = (content or "").strip()
if not trimmed:
fail_with_prefix("test_optimization_sync", "%s response is empty; expected JSON object" % context)
# Catch common non-JSON responses (HTML/text proxy errors) early.
if not (trimmed.startswith("{") or trimmed.startswith("[")):
sample = trimmed[:120].replace("\n", " ").replace("\r", " ")
fail_with_prefix(
"test_optimization_sync",
(
"%s response is not JSON (starts with: %s). " +
"Check DD_SITE/DD_TEST_OPTIMIZATION_AGENTLESS_URL, credentials, and endpoint routing."
) % (context, repr(sample)),
)
obj = json.decode(trimmed)
if not _is_dict(obj):
fail_with_prefix("test_optimization_sync", "%s response must be a JSON object, got %s" % (context, type(obj)))
return obj
def _parse_curl_time_ms(value):
"""Convert a curl-style seconds string into integer milliseconds."""
text = (value or "").strip()
if not text:
return 0
negative = text.startswith("-")
if negative:
text = text[1:]
if "." in text:
parts = text.split(".", 1)
seconds_text = parts[0]
frac_text = parts[1]
else:
seconds_text = text
frac_text = ""
seconds = int(seconds_text) if seconds_text else 0
digits = ""
for i in range(len(frac_text)):
ch = frac_text[i]
if ch < "0" or ch > "9":
break
digits += ch
for _unused in [0, 1, 2]:
if len(digits) >= 3:
break
digits += "0"
millis = seconds * 1000
if digits:
millis += int(digits[:3])
return -millis if negative else millis
def _parse_positive_int_or_zero(value):
"""Parse a positive integer string or return zero for blank input."""
text = (value or "").strip()
if not text:
return 0
return int(text)
def _new_telemetry_facts(service_name, runtime_name = "", env = ""):
"""Create the normalized sync telemetry facts document."""
facts = {
"schema_version": 1,
"service_name": service_name or "",
"counts": [],
"distributions": [],
}
if runtime_name:
facts["runtime_name"] = runtime_name
if env:
facts["env"] = env
return facts
def _append_telemetry_count(doc, name, value = 1, tags = None):
"""Append one normalized count metric fact."""
doc["counts"].append({
"name": name,
"value": value,
"tags": list(tags or []),
})
def _append_telemetry_distribution(doc, name, value, tags = None):
"""Append one normalized distribution metric fact."""
doc["distributions"].append({
"name": name,
"value": value,
"tags": list(tags or []),
})
def _build_settings_response_tags(attrs_obj):
"""Build the combined settings-response tags used by dd-trace-go."""