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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
//! SDK heartbeat — telemetry parity with the Go / Python /
//! TypeScript / Java SDKs.
//!
//! Sends at most one ping per machine per 7 days to
//! `https://checkpoint.getaxonflow.com/v1/ping` carrying SDK version,
//! OS, architecture, runtime version, deployment mode, and an
//! endpoint-type classification (never the raw URL — see issue #1525
//! in the AxonFlow tracker for the privacy rationale).
//!
//! # Network behaviour change in 0.10.0 (sdk-rust#88)
//!
//! Before 0.10.0 the telemetry path made exactly one outbound request: the
//! POST to the checkpoint service. It now makes a second one FIRST — a `GET`
//! on the configured platform endpoint's `/health` — and relays four values
//! from that response so Rust rows carry the same dimensions the other four
//! SDKs already carry. `/health` is unauthenticated and is the caller's own
//! platform, so this is a request to an endpoint the SDK was already
//! configured to talk to; it is nonetheless a change to the SDK's network
//! behaviour and is disclosed as such in `README.md`.
//!
//! `AXONFLOW_TELEMETRY=off` is the SOLE opt-out path, and it suppresses the
//! `/health` probe together with the ping — nothing on this path runs. There
//! is intentionally no programmatic disable on the SDK config: the single
//! env-var lever matches HashiCorp checkpoint, Docker, and the Datadog Agent.
//! Sandbox-mode clients tag their pings with `stream="sandbox"` so analytics
//! can distinguish dev/test usage from production heartbeat. `DO_NOT_TRACK` is
//! intentionally NOT honored — host CLIs commonly inherit it, which makes it
//! an unreliable expression of AxonFlow-scoped intent.
//!
//! Pre-v0.2 the Rust SDK pinged `{configured_endpoint}/api/telemetry/heartbeat`
//! against the local agent — useful for proxy debugging but invisible to
//! AxonFlow's central telemetry pipeline. The endpoint switch in v0.2
//! brings Rust into parity with the other 4 first-class SDKs.
use fs;
use PathBuf;
use ;
use ;
use Serialize;
use debug;
use crateMode;
/// Bounds how often a single machine delivers a telemetry ping. Aligned with
/// the cross-SDK "at most one heartbeat per environment every 7 days during
/// SDK activity" contract, and enforced by the stamp file so it survives
/// process restarts.
const HEARTBEAT_INTERVAL: Duration = from_secs;
/// Bounds how often a single PROCESS re-consults the stamp file. Without it,
/// every SDK request would `stat()` the stamp; with it, a hot service does so
/// at most once an hour. This is also what lets a long-running service that
/// crosses the 7-day boundary re-ping at all — before 0.10.0 a `Once` gate
/// made the constructor the only opportunity for the whole process lifetime.
const HEARTBEAT_GUARD_INTERVAL: Duration = from_secs;
/// Total budget for the ENTIRE telemetry path: `/health` probe plus checkpoint
/// POST. One shared deadline, not one timeout per leg — two independent 3 s
/// timeouts would stack into ~6 s of work against an unreachable endpoint
/// (enterprise#1693, the same defect the Python and TypeScript SDKs fixed).
const HEARTBEAT_TIMEOUT: Duration = from_secs;
/// Ceiling on the `/health` probe's share of [`HEARTBEAT_TIMEOUT`]. The probe
/// is the optional leg: it enriches the ping, the POST *is* the ping. Capping
/// it guarantees the POST always has room even when `/health` is blackholed.
const HEALTH_BUDGET_CAP: Duration = from_secs;
/// Minimum remaining budget worth spending on an HTTP request. Below this,
/// skip rather than issue a call that is near-certain to time out before it
/// achieves anything.
const MIN_BUDGET: Duration = from_millis;
/// Bounds how much of a `/health` response the probe will buffer. A real
/// response is a few KB, dominated by a `capabilities` map that grows every
/// release; 1 MiB is orders of magnitude above any legitimate body while
/// capping what a misbehaving or hostile endpoint can make the telemetry task
/// allocate. Exceeding it aborts the parse, which fails open exactly like
/// every other probe failure — the relayed fields stay absent and the ping is
/// still sent without them. Matches the Go SDK's `maxHealthBodyBytes`.
const MAX_HEALTH_BODY_BYTES: usize = 1024 * 1024;
/// Bounds the length of any single value relayed from `/health` onto the wire.
///
/// The values are supplied by whatever is answering at the configured
/// endpoint, and the checkpoint service rejects a request body over 64 KiB
/// with HTTP 413 — so an uncapped relay lets a `/health` response that
/// SUCCEEDS destroy the ping it was supposed to enrich, silently losing every
/// other dimension in the payload. Real values are single-digit-to-teens
/// bytes (`10.4.0`, `Enterprise`, `self_hosted`).
///
/// An over-long value is DROPPED WHOLE, never truncated: a truncated string
/// would be a claim the platform never made, and this field's entire contract
/// is that it relays verbatim or says nothing.
const MAX_RELAYED_VALUE_LEN: usize = 64;
/// Bounds on the `features` array, mirroring the receiver's own `MaxFeatures` /
/// `MaxFeatureBytes`. Applying them client-side means an over-long array is
/// shaped HERE, where the SDK still knows what it dropped, rather than silently
/// at ingest.
///
/// READ WHAT THESE TWO ACTUALLY REACH. The entry cap is live: register 33
/// adapters and the 33rd does not reach the wire. The byte cap is a BACKSTOP
/// that today's only producer cannot trigger — [`register_adapter`] already
/// refuses a name over [`MAX_RELAYED_VALUE_LEN`], so the longest entry it can
/// emit is `"adapter:".len() + 64 == 72` bytes. It is tested directly on
/// [`bound_features`], because a test driven through the registry could not
/// express it.
const MAX_FEATURES: usize = 32;
const MAX_FEATURE_BYTES: usize = 128;
/// Marks a `features[]` entry as an adapter identifier. The vocabulary is
/// SERVER-DEFINED (checkpoint-service `FeatureAdapterPrefix`) and is not this
/// SDK's to extend.
const FEATURE_ADAPTER_PREFIX: &str = "adapter:";
/// Adapter names declared by [`register_adapter`].
///
/// A set, so a framework that registers on every wrapper construction — the
/// ordinary case for an adapter whose constructor runs per request — declares
/// itself once on the wire rather than N times.
/// Declare that a framework adapter is driving this SDK, so the next telemetry
/// heartbeat carries `adapter:<name>` in its `features` array.
///
/// A framework adapter (LangChain, LangGraph, LiteLLM, …) wrapping this SDK is
/// indistinguishable from bare SDK use on every other telemetry dimension —
/// same `sdk`, same `sdk_version`, same endpoint. This is the one call that
/// makes the difference visible, and it is adoption signal only.
///
/// # It adds no request
///
/// The name rides the `features` array of the heartbeat that already fires;
/// there is no second ping, no second endpoint and no new configuration
/// surface. Calling this does not itself send anything.
///
/// Call it before your first API call for day-one attribution: the heartbeat
/// fires on the client's FIRST OUTBOUND REQUEST, not at construction, so a name
/// registered afterwards rides the next heartbeat.
///
/// Idempotent and safe from any thread.
///
/// # The name is not validated against a list, deliberately
///
/// The canonical vocabulary lives on the receiver (checkpoint-service
/// `NormalizeAdapterFeature`, which folds an unrecognised name into
/// `adapter:unknown` at READ time while keeping the raw name on the row). An
/// allowlist here would be a second vocabulary that drifts from the first: a
/// name this SDK build predates would be dropped at the client instead of
/// arriving and rendering as "someone is using an adapter we do not know
/// about" — precisely the signal the unknown bucket exists to preserve.
///
/// So the only transformations are the two the receiver also applies before
/// matching: trim, and lowercase. A name empty after trimming, and a name
/// longer than [`MAX_RELAYED_VALUE_LEN`], are refused SILENTLY — this is a
/// fire-and-forget telemetry declaration on a path whose overriding constraint
/// is that it never disrupts the caller.
///
/// # This SDK ships no adapter of its own
///
/// Unlike the Go, Python, TypeScript and Java SDKs, this crate exports no
/// framework adapter, so nothing here calls this function. It exists for
/// third-party integrations built on top of the crate. The `interceptors`
/// module wraps LLM PROVIDER clients (Anthropic, OpenAI), which is a different
/// dimension from the agent framework driving the SDK and deliberately not
/// reported here.
/// Apply the receiver's array bounds: at most [`MAX_FEATURES`] entries, none
/// over [`MAX_FEATURE_BYTES`] bytes.
///
/// An over-long entry is DROPPED rather than truncated, deliberately differing
/// from the receiver's own `BoundFeatures`. The receiver truncates because it is
/// defending storage against arbitrary clients; here the entry is something this
/// process declared about itself, and a truncated adapter name is a name nothing
/// is running.
/// Render the registry as the `features` array for one ping.
///
/// A `BTreeSet` keeps it sorted, so the wire is deterministic and "which 32
/// survive" is a defined answer rather than a hash-iteration accident.
/// Test-only: empty the registry and return what was there.
/// Test-only: restore a registry saved by [`reset_adapter_registry_for_tests`].
const DEFAULT_CHECKPOINT_URL: &str = "https://checkpoint.getaxonflow.com/v1/ping";
/// Stream classifications written to the telemetry payload. Only the
/// SDK-derived heartbeat values are produced from this code path —
/// see `IsValidIncomingStream` server-side.
const STREAM_SANDBOX: &str = "sandbox";
/// Endpoint-type classifications for the SDK-derived `endpoint_type`
/// field on the telemetry payload. Mirrors Go SDK
/// `ClassifyEndpoint`. The raw URL never leaves the process.
const ENDPOINT_TYPE_LOCALHOST: &str = "localhost";
const ENDPOINT_TYPE_PRIVATE: &str = "private_network";
const ENDPOINT_TYPE_REMOTE: &str = "remote";
const ENDPOINT_TYPE_UNKNOWN: &str = "unknown";
// ============================================================================
// The process-wide gate
// ============================================================================
/// Process-wide heartbeat gate. The stamp file is the source of truth across
/// restarts; these fields gate within a process.
///
/// `last_checked` implements [`HEARTBEAT_GUARD_INTERVAL`]; `in_flight`
/// coalesces concurrent callers onto a single ping rather than one per caller.
/// Claim on the in-flight slot. Releasing on `Drop` rather than at the end of
/// the send is deliberate: the send runs on a spawned task, and a task dropped
/// mid-flight (runtime shutdown, `JoinHandle` abort) would otherwise leave
/// `in_flight` stuck true and suppress telemetry for the rest of the process.
;
/// Synchronous half of the heartbeat decision, run on the CALLER's thread —
/// so it must stay cheap: one mutex acquire and two comparisons, no syscalls
/// and no allocation on the suppressed path.
///
/// This is what makes the request-site trigger affordable. A service handling
/// thousands of requests a second calls this on every one of them; if the
/// 1-hour guard is warm it returns here, having spawned nothing. The `stat()`
/// of the stamp file and all network work happen later — awaited inline on the
/// request path (see [`maybe_send_heartbeat_on_request`]) or on a spawned task
/// via [`maybe_send_heartbeat`] — at most once per
/// [`HEARTBEAT_GUARD_INTERVAL`].
///
/// Returns `None` when this call must not ping.
/// How long the gate waits before re-consulting, given how many attempts in a
/// row have failed to deliver.
///
/// Doubling from [`HEARTBEAT_GUARD_INTERVAL`], capped at
/// [`HEARTBEAT_INTERVAL`]. Without this the SDK has no backoff at all, and
/// two deliberate design choices combine into a defect: the 7-day stamp only
/// advances on DELIVERY, and the gate is now re-evaluated on every request.
/// In a deployment where egress to the checkpoint service is blocked — which
/// is the normal state of the air-gapped and in-VPC self-hosted topologies
/// this SDK supports — every process would issue a `/health` GET against the
/// CUSTOMER'S OWN platform once an hour, indefinitely, and a failed POST
/// beside it. Unsolicited hourly traffic against someone else's platform, for
/// a heartbeat disclosed as weekly, is not defensible.
///
/// Backing off does not lose a ping: the stamp is still untouched, so the
/// first attempt after the widened interval sends normally.
/// Record what an attempt achieved, so the next one can back off.
///
/// Only called when an attempt was actually MADE. A pass that stopped at the
/// fresh 7-day stamp is not a failure and must not widen the interval.
/// Everything the heartbeat decides synchronously: the opt-out, the
/// process-wide gate, and the snapshot of the environment the ping will
/// describe. Returns `None` when this call must not ping.
///
/// Both the production entry point and the tests go through this function, so
/// no test can observe an ordering the shipped path does not have.
/// Fire-and-forget heartbeat. **No longer called from anywhere inside this
/// crate**: `AxonFlowClient::new` no longer pings at all, and
/// `AxonFlowClient::dispatch` uses [`maybe_send_heartbeat_on_request`]. It is
/// retained because `heartbeat` is a public module and removing it would be a
/// breaking change, and because it is the only entry point usable from a
/// caller that cannot await.
///
/// Never blocks and never awaits on the caller's path: the gating decision is
/// a mutex acquire, and everything that can block (the stamp `stat()`, the
/// `/health` probe, the POST) runs on a spawned tokio task.
///
/// **This is NOT what the request path uses, and the reason is delivery.** A spawned send is dropped when
/// the process does not outlive it — measured at 1 delivery in 12 for a
/// compiled one-call binary — so the client's first request awaits the send
/// inline via [`maybe_send_heartbeat_on_request`]. This entry point remains for
/// callers that cannot await.
///
/// `AXONFLOW_TELEMETRY=off` short-circuits before any filesystem or network
/// access — including before the `/health` probe. Anything else allows the
/// ping; the per-machine 7-day stamp file (in `~/Library/Caches/axonflow/` on
/// macOS, `~/.cache/axonflow/` elsewhere) bounds the delivery cadence.
/// The heartbeat trigger for the REQUEST path, awaited inline on the caller's
/// task rather than spawned.
///
/// # Why this is not `maybe_send_heartbeat`
///
/// Spawning drops the ping when the process does not outlive it. Measured on a
/// compiled one-call binary that returns from `main`: the ping was delivered
/// **1 time in 12** — and worse than "no telemetry", the `/health` GET reached
/// the customer's own platform every time while the checkpoint POST was
/// cancelled, so the SDK made an unsolicited request to someone else's server
/// and recorded nothing for it.
///
/// That shape — construct, one call, exit — is a CLI, a Lambda handler, a CI
/// step. It is the population the first-request trigger exists to make visible,
/// so losing it here would have defeated the change that introduced it. Go and
/// Java run their cold path inline for exactly this reason (their issue #1693);
/// this is the same decision.
///
/// # What it costs, stated as a number
///
/// The whole telemetry path is bounded by [`HEARTBEAT_TIMEOUT`] (3 s) — the
/// `/health` probe and the checkpoint POST share that one deadline rather than
/// stacking — so this can add at most ~3 s to a caller's request. The outer
/// timeout here is belt-and-braces on top of that internal budget.
///
/// It is reachable at most once per [`HEARTBEAT_GUARD_INTERVAL`] per process,
/// and only actually sends when a ping is DUE, which the 7-day stamp limits to
/// once per machine per week. On every other request `prepare_heartbeat`
/// returns `None` after one mutex acquire and this function returns having
/// awaited nothing.
pub async
/// Asynchronous half: the 7-day stamp check and the send. Holds the gate slot
/// for its whole lifetime so concurrent callers coalesce onto this one run.
async
// Master switch for the crate's OWN test binary, off by default and armed
// PER THREAD.
//
// Every module's unit tests construct an `AxonFlowClient`, and construction
// consults the heartbeat gate. Without this switch two things go wrong during
// `cargo test`: unrelated tests fire real pings at the production checkpoint
// service (CI hides this by setting `AXONFLOW_TELEMETRY=off` for the whole
// workflow; a developer's `cargo test` does not), and — because the gate is
// process-wide by design — those constructions race the heartbeat tests for
// the in-flight claim, so an assertion about "exactly one ping" depends on
// which other test happened to be running.
//
// Thread-local rather than a global flag, and that distinction is load
// bearing: a global one is only off until the first heartbeat test turns it
// on, and every OTHER test constructing a client during that window can still
// claim the gate. Arming only the running test's thread closes the window
// completely. `prepare_heartbeat` — the only reader — always runs on the
// caller's thread, so this is consulted where it is armed.
//
// `TelemetryTestEnv` is the only thing that arms it, while holding the global
// test lock, and it disarms on drop.
thread_local!
/// Test-only redirection of the stamp file. Keeps the gate tests off the
/// developer's real `~/Library/Caches/axonflow/` stamp — which would otherwise
/// both suppress the tests and clobber a real heartbeat cadence — without
/// adding an environment override to the shipped surface.
/// Outer `None`: no override, use the real path. Outer `Some(None)`: model an
/// environment with NO usable stamp path at all.
static STAMP_PATH_OVERRIDE: = new;
/// Classify the configured AxonFlow endpoint URL into one of
/// `localhost` / `private_network` / `remote` / `unknown`. The raw URL
/// is never sent — only the classification (see issue #1525). Mirrors
/// `ClassifyEndpoint` in the Go SDK.
// v1 telemetry-schema deployment_mode allowlist (axonflow-enterprise#2008).
// Reflects deployment topology only — the prior config.Mode-based
// production/sandbox split moved to the `stream` field.
pub const DEPLOYMENT_MODE_SELF_HOSTED: &str = "self_hosted";
pub const DEPLOYMENT_MODE_COMMUNITY_SAAS: &str = "community_saas";
pub const DEPLOYMENT_MODE_UNKNOWN: &str = "unknown";
/// Classify the configured AxonFlow endpoint into the v1 deployment-mode
/// allowlist (`self_hosted | community_saas | unknown`). Community-SaaS
/// detection fires on either an `*.try.getaxonflow.com` host or
/// `AXONFLOW_TRY=1` (the explicit override path for tenants behind a
/// custom hostname proxying try.getaxonflow.com). Empty/unparseable
/// endpoints resolve to `unknown`.
///
/// This is the SDK's own classification of the URL it was handed. It is a
/// different question from the platform's own `DEPLOYMENT_MODE`, which the
/// platform reports on `/health` and which rides the wire separately as
/// `platform_deployment_mode` — see [`HealthProbe`].
/// Sentinel emitted on the telemetry wire when `ORG_ID` is unset — the
/// default-config Community-mode developer case. See #2277.
pub const ORG_ID_LOCAL_DEV_SENTINEL: &str = "local-dev-org";
/// Returns the `org_id` value to emit on the next telemetry ping. Reads
/// `ORG_ID` from the environment (the operator's explicit configuration
/// for self-hosted deployments, or the `cs_<uuid>` tenant identifier on
/// Community SaaS) and falls back to [`ORG_ID_LOCAL_DEV_SENTINEL`] when
/// unset. Always returns a non-empty string. See #2277.
/// Value reported when the toolchain could not be established at build time.
/// Distinct from any real rustc string, and honest: the field says "not
/// known" rather than naming a channel the build may not have used.
const RUNTIME_VERSION_UNKNOWN: &str = "unknown";
/// Normalise the verbatim `rustc --version` line `build.rs` captured into the
/// low-cardinality `rustc <version>` shape the telemetry warehouse aggregates
/// on — matching the Go SDK's `go1.22` and the Python SDK's `python 3.12.1`.
///
/// `rustc --version` prints `rustc 1.95.0 (59807616e 2026-04-14)`. The commit
/// hash and build date are dropped: they are a per-toolchain-build identifier
/// that would explode the dimension's cardinality without answering the
/// question the field exists for (which Rust versions must the SDK support).
///
/// Anything that does not have a recognisable version token resolves to
/// [`RUNTIME_VERSION_UNKNOWN`] rather than being passed through, so a wrapper
/// that prints something unexpected cannot put arbitrary text on the wire.
/// The compiling toolchain, captured by `build.rs`. `None` when the build
/// script could not run `rustc --version`, which reports `unknown`.
// ============================================================================
// The /health probe
// ============================================================================
/// What a single `/health` fetch established.
///
/// Every field is INDEPENDENT: a response carrying one but not another yields
/// a partially-populated probe rather than discarding all of them. `None`
/// means NOT LEARNED and is omitted from the wire entirely — it never degrades
/// to a default, an empty string, or a JSON `null`.
///
/// # Trust boundary
///
/// These values are whatever is answering at the endpoint the caller
/// configured. The SDK derives nothing from them, verifies nothing about them,
/// and the receiver cannot verify the relay either. They are adoption
/// analytics; they must never gate entitlement, unlock a feature, or enter an
/// authorization or billing decision.
/// Promote one `/health` member to a relayable value.
///
/// Learned only when the member is present, is a JSON string, is non-empty,
/// and is within [`MAX_RELAYED_VALUE_LEN`]. An absent key, a non-string value,
/// an explicit `""`, and an over-long string are all NOT LEARNED — the field
/// stays `None` rather than becoming a value the platform did not report.
/// Probe the configured platform's `/health` endpoint ONCE and extract every
/// telemetry dimension it carries.
///
/// Returns a default (all fields `None`) on ANY failure — no endpoint,
/// unreachable, non-2xx, oversized body, unparseable body — so telemetry
/// degrades to omitting the fields. It never fails the ping and never surfaces
/// an error to the caller.
///
/// This is the SDK's ONLY `/health` fetch on the telemetry path. Every relayed
/// dimension rides this one response. A second request here would double the
/// path's blocking budget and its failure surface — do not add one.
///
/// `budget` comes from the shared deadline, so this leg and the POST cannot
/// stack into a larger combined wait.
async
// ============================================================================
// The payload
// ============================================================================
/// The telemetry wire payload.
///
/// A typed struct rather than a hand-built map so "omitted when not learned"
/// is structural: every relayed field is an `Option` with
/// `skip_serializing_if`, and there is no code path that can put a `null` or a
/// substituted default on the wire for one. Every value is handed to
/// `serde_json` AS A VALUE — nothing is spliced into a JSON fragment — so
/// quotes, backslashes and newlines in a `/health` response are escaped by the
/// serializer rather than breaking it.
/// Immutable snapshot of everything the ping describes, taken once on the
/// caller's thread so the spawned send never re-reads process environment that
/// may have changed underneath it.
/// The ONE HTTP client the telemetry path uses, for both legs.
///
/// A function rather than an inline builder so the tests exercise the SHIPPED
/// construction. When the probe tests built their own client they were testing
/// the test helper: the redirect policy below was live in production and
/// absent from every probe test, and the test written to prove redirects are
/// refused passed a redirect straight through.
///
/// Deliberately built with no `.timeout(...)`: the budget is per-request, set
/// from the shared deadline in [`send_heartbeat`].
///
/// Redirects are REFUSED, and that is load bearing on both legs. reqwest
/// follows up to 10 by default, which would mean:
///
/// * `/health` is no longer one request, and the values relayed would be
/// whatever answered at the redirect TARGET — so the disclosure's
/// "whatever is answering at the endpoint you configured" would be false,
/// and the endpoint's operator would choose who supplies them.
/// * worse on the POST: reqwest re-issues a redirected POST as a bodyless
/// GET, so a 302 on the checkpoint URL yields a 200 carrying NOTHING,
/// `send_heartbeat` reports delivery, and the 7-day stamp advances on a
/// ping that was never sent — telemetry then goes dark for a week.
///
/// A `User-Agent` is set because this is the first SDK feature that contacts
/// the caller's own platform unsolicited; it must be attributable in their
/// access logs. No other default header is set, so the SDK's `Authorization`
/// and `X-License-Key` never reach the probe.
/// Run the telemetry path: probe `/health`, then POST the ping. Returns
/// whether the ping was DELIVERED, which is what licenses the caller to move
/// the 7-day stamp forward.
///
/// # The shared budget
///
/// One deadline covers both legs. The probe gets at most
/// [`HEALTH_BUDGET_CAP`]; the POST gets everything left. This is the whole
/// reason there is a single [`reqwest::Client`] here with NO client-level
/// timeout: a client-level timeout is per-request and would let the two legs
/// stack, which is the defect the other SDKs already fixed.
///
/// The POST is attempted regardless of what the probe did — an unreachable,
/// broken or hostile `/health` costs the ping some of its dimensions, never
/// the ping itself.
async
/// Budget left before `deadline`, saturating at zero rather than panicking on
/// an already-passed instant.
/// Stamp-on-delivery: the stamp only moves when we know the ping landed. A
/// failed ping leaves it untouched so the next run after the in-process guard
/// expires retries. When `stamp_path` is `None` (containerized environments
/// with no usable cache dir) nothing is persisted and the in-process gate is
/// the only rate limit.
async
/// Clear the process-wide gate so an individual test starts from a known
/// state. Tests hold `telemetry_lock()` while doing this — the gate is
/// process-wide by design, so two tests racing on it would see each other's
/// claims.
/// A fresh process: no prior check, nothing in flight, no accumulated
/// backoff.
/// The guard interval has elapsed — and NOTHING else has changed.
///
/// Deliberately distinct from [`reset_gate_for_tests`]: clearing the failure
/// counter here would mean "time passed" also erased the backoff, and the
/// backoff test would then measure one failure over and over instead of
/// consecutive ones.
/// The 7-day boundary has been crossed: the short guard has elapsed AND the
/// last delivery is older than the heartbeat interval.
///
/// Distinct from [`reopen_gate_for_tests`], which models only an hour passing.
/// A test that means "a week later" has to say so, or the in-memory cadence
/// floor refuses its claim and the test reads as a regression.
/// Put the gate into a specific state so a test can ask it to REFUSE.
///
/// Needed because the widened interval is only observable at the moment a
/// claim is declined, and no test can wait an hour. Without it the backoff was
/// pinned only by a test of the pure interval function and a test that read
/// the counter — so substituting the call site with the base interval left the
/// whole suite green while the hourly-probe-forever defect came back.
/// One complete heartbeat pass, awaited rather than spawned.
///
/// Deliberately NOT a re-implementation of the shipped sequence: it calls the
/// same [`prepare_heartbeat`] and [`gated_send`] in the same order that
/// [`maybe_send_heartbeat`] does. The only thing it replaces is the spawn, so
/// a test cannot pass against an ordering the shipped path does not have.
/// The shipped trigger is covered separately, through the real public entry
/// point, by `the_first_request_delivers_the_ping`.
///
/// Returns whether the pass ran at all (i.e. whether the gate let it through).
async