nifi-rust-client 0.10.1

Apache NiFi REST API client library
Documentation
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
#![deny(missing_docs)]
use std::sync::Arc;

use reqwest::Client;
use serde::de::DeserializeOwned;
use snafu::ResultExt as _;
use tokio::sync::RwLock;
use url::Url;

use crate::NifiError;
use crate::config::auth::AuthProvider;
use crate::error::{AuthSnafu, HttpSnafu};

/// Client for the Apache NiFi REST API.
pub struct NifiClient {
    base_url: Url,
    http: Client,
    token: Arc<RwLock<Option<String>>>,
    auth_provider: Option<Arc<dyn AuthProvider>>,
    proxied_entities_chain: Option<String>,
    #[allow(dead_code)]
    retry_policy: Option<crate::config::retry::RetryPolicy>,
}

impl Clone for NifiClient {
    fn clone(&self) -> Self {
        Self {
            base_url: self.base_url.clone(),
            http: self.http.clone(),
            token: Arc::clone(&self.token),
            auth_provider: self.auth_provider.clone(),
            proxied_entities_chain: self.proxied_entities_chain.clone(),
            retry_policy: self.retry_policy.clone(),
        }
    }
}

impl std::fmt::Debug for NifiClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NifiClient")
            .field("base_url", &self.base_url)
            .field(
                "auth_provider",
                &self.auth_provider.as_ref().map(|c| format!("{c:?}")),
            )
            .field("proxied_entities_chain", &self.proxied_entities_chain)
            .field("retry_policy", &self.retry_policy)
            .finish_non_exhaustive()
    }
}

impl NifiClient {
    /// Construct a client from pre-built parts. Used by [`crate::NifiClientBuilder`].
    pub(crate) fn from_parts(
        base_url: Url,
        http: Client,
        auth_provider: Option<Arc<dyn AuthProvider>>,
        proxied_entities_chain: Option<String>,
        retry_policy: Option<crate::config::retry::RetryPolicy>,
    ) -> Self {
        Self {
            base_url,
            http,
            token: Arc::new(RwLock::new(None)),
            auth_provider,
            proxied_entities_chain,
            retry_policy,
        }
    }

    /// Return the current bearer token, if one has been set.
    ///
    /// The token is a NiFi-issued JWT. You can persist it between process restarts
    /// and restore it with [`set_token`][Self::set_token] to avoid re-authenticating.
    /// The token will eventually expire (NiFi default: 12 hours); when it does, any
    /// API call returns [`NifiError::Unauthorized`]. Re-call
    /// [`login`][Self::login] to obtain a fresh token.
    pub async fn token(&self) -> Option<String> {
        self.token.read().await.clone()
    }

    /// Restore a previously obtained bearer token.
    ///
    /// Useful for CLI tools that persist the token in a file between sessions.
    /// If the token has expired, the next API call will return
    /// [`NifiError::Unauthorized`]; re-call [`login`][Self::login]
    /// to obtain a fresh one.
    pub async fn set_token(&self, token: String) {
        *self.token.write().await = Some(token);
    }

    /// Invalidate the current bearer token and clear it from the client.
    ///
    /// Sends `DELETE /nifi-api/access/logout` to invalidate the token server-side,
    /// then clears the local token unconditionally so that subsequent requests are
    /// not sent with a stale credential.
    ///
    /// If the server returns an error (e.g. `401` because the token had already
    /// expired) the local token is still cleared and the error is returned to the
    /// caller.
    #[tracing::instrument(skip(self))]
    pub async fn logout(&self) -> Result<(), NifiError> {
        let result = self.delete_inner("/access/logout").await;
        *self.token.write().await = None;
        if result.is_ok() {
            tracing::info!("NiFi logout successful");
        }
        result
    }

    /// Authenticate with NiFi using single-user credentials.
    ///
    /// Obtains a JWT token from `/nifi-api/access/token` and stores it on the
    /// client for all subsequent requests.
    ///
    /// # Token lifetime and expiry
    ///
    /// NiFi JWTs expire after 12 hours by default (configurable server-side via
    /// `nifi.security.user.login.identity.provider.expiration`). Once expired,
    /// any API call returns [`NifiError::Unauthorized`]. Configure an
    /// [`AuthProvider`] on the builder to enable
    /// automatic token refresh on 401 responses.
    #[tracing::instrument(skip(self, username, password))]
    pub async fn login(&self, username: &str, password: &str) -> Result<(), NifiError> {
        tracing::debug!(method = "POST", path = "/access/token", "NiFi API request");
        let url = self.api_url("/access/token");
        let resp = self
            .http
            .post(url)
            .form(&[("username", username), ("password", password)])
            .send()
            .await
            .context(HttpSnafu)?;

        let status = resp.status();
        tracing::debug!(
            method = "POST",
            path = "/access/token",
            status = status.as_u16(),
            "NiFi API response"
        );
        if !status.is_success() {
            let body = resp.text().await.unwrap_or_else(|_| status.to_string());
            tracing::debug!(
                method = "POST",
                path = "/access/token",
                status = status.as_u16(),
                %body,
                "NiFi API raw error body"
            );
            let message = extract_error_message(&body);
            tracing::warn!(
                method = "POST",
                path = "/access/token",
                status = status.as_u16(),
                %message,
                "NiFi API error"
            );
            return AuthSnafu { message }.fail();
        }

        let token = resp.text().await.context(HttpSnafu)?;
        *self.token.write().await = Some(token);
        tracing::info!("NiFi login successful for {username}");
        Ok(())
    }

    /// Authenticate using the configured [`AuthProvider`].
    ///
    /// Returns [`NifiError::Auth`] if no auth provider has been configured.
    #[tracing::instrument(skip(self))]
    pub async fn authenticate(&self) -> Result<(), NifiError> {
        let provider = self.auth_provider.as_ref().ok_or_else(|| NifiError::Auth {
            message: "no auth provider configured".to_string(),
        })?;
        provider.authenticate(self).await
    }

    // ── Auth-retry wrapper ────────────────────────────────────────────────────

    /// Execute `f`, and if it returns `NifiError::Unauthorized` and a credential
    /// provider is configured, refresh the token and retry once.
    #[tracing::instrument(skip_all)]
    async fn with_auth_retry<T, F, Fut>(&self, f: F) -> Result<T, NifiError>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, NifiError>>,
    {
        match f().await {
            Err(NifiError::Unauthorized { .. }) if self.auth_provider.is_some() => {
                tracing::info!("received 401, refreshing token via auth provider");
                self.authenticate().await?;
                f().await
            }
            other => other,
        }
    }

    // ── Transient-error retry wrapper ──────────────────────────────────────────

    /// Execute `f` with optional transient-error retry using exponential backoff.
    ///
    /// When a [`RetryPolicy`](crate::config::retry::RetryPolicy) is configured, retries
    /// [retryable](NifiError::is_retryable) errors up to `max_retries` times.
    /// Each attempt goes through [`with_auth_retry`] so 401 handling still works.
    #[tracing::instrument(skip_all)]
    async fn with_retry<T, F, Fut>(&self, f: F) -> Result<T, NifiError>
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Result<T, NifiError>>,
    {
        let Some(policy) = &self.retry_policy else {
            return self.with_auth_retry(&f).await;
        };

        let mut last_err: Option<NifiError> = None;
        for attempt in 0..=policy.max_retries {
            if attempt > 0 {
                let backoff = policy.backoff_for(attempt - 1);
                tracing::info!(
                    attempt,
                    backoff_ms = backoff.as_millis() as u64,
                    "retrying after transient error"
                );
                tokio::time::sleep(backoff).await;
            }
            match self.with_auth_retry(&f).await {
                Ok(v) => return Ok(v),
                Err(e) if e.is_retryable() => {
                    tracing::warn!(attempt, error = %e, "transient error, will retry");
                    last_err = Some(e);
                }
                Err(e) => return Err(e),
            }
        }
        // Safety: the loop always executes at least once (attempt 0..=max_retries),
        // and every iteration that reaches here sets `last_err`.
        match last_err {
            Some(e) => Err(e),
            // unreachable: loop runs at least once and non-retryable errors return early
            None => self.with_auth_retry(&f).await,
        }
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    #[tracing::instrument(skip(self))]
    pub(crate) async fn get<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("GET", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, body))]
    pub(crate) async fn post<B, T>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
    ) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::deserialize("POST", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, body))]
    pub(crate) async fn put<B, T>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
    ) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        self.with_retry(|| async {
            tracing::debug!(method = "PUT", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.put(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::deserialize("PUT", path, resp).await
        })
        .await
    }

    /// POST with no request body; deserializes the JSON response.
    #[tracing::instrument(skip(self))]
    pub(crate) async fn post_no_body<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("POST", path, resp).await
        })
        .await
    }

    /// POST with no request body; ignores the response body.
    ///
    /// Called by both the static per-version emitter (for POST endpoints
    /// with no body and an empty response) and the dynamic canonical
    /// emitter. No current NiFi 2.x spec triggers the static path, so
    /// this helper is only reached via generated code in `$OUT_DIR` that
    /// clippy's dead-code lint cannot see. Kept available via
    /// `#[allow(dead_code)]` rather than deleted.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self))]
    pub(crate) async fn post_void_no_body(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void("POST", path, resp).await
        })
        .await
    }

    /// POST with a JSON body; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(POST, Json body, Empty response)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, body))]
    pub(crate) async fn post_void<B: serde::Serialize>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::check_void("POST", path, resp).await
        })
        .await
    }

    /// PUT with no request body; deserializes the JSON response.
    #[tracing::instrument(skip(self))]
    pub(crate) async fn put_no_body<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "PUT", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.put(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("PUT", path, resp).await
        })
        .await
    }

    /// PUT with a JSON body; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(PUT, Json body, Empty response)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, body))]
    pub(crate) async fn put_void<B: serde::Serialize>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "PUT", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.put(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::check_void("PUT", path, resp).await
        })
        .await
    }

    /// PUT with no request body; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(PUT, no body, Empty response)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self))]
    pub(crate) async fn put_void_no_body(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "PUT", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.put(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void("PUT", path, resp).await
        })
        .await
    }

    /// POST with `application/octet-stream` body.
    ///
    /// Used for binary upload endpoints (e.g. NAR upload).
    /// Pass `("Filename", name)` in `extra_headers` when the endpoint
    /// requires a filename header.
    #[tracing::instrument(skip(self, data))]
    pub(crate) async fn post_octet_stream<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        data: Vec<u8>,
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self
                .authenticated(self.http.post(url))
                .await
                .header("Content-Type", "application/octet-stream")
                .body(data.clone());
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("POST", path, resp).await
        })
        .await
    }

    /// POST with `multipart/form-data` body.
    ///
    /// Used for file-upload endpoints such as
    /// `POST /process-groups/{id}/process-groups/upload`. Sends a single form
    /// part named `"file"` carrying the given filename and raw bytes. The
    /// `Content-Type` header (including the generated boundary) is set by
    /// reqwest when `.multipart(form)` is called.
    #[tracing::instrument(skip(self, data))]
    pub(crate) async fn post_multipart<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        filename: &str,
        data: Vec<u8>,
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let part =
                reqwest::multipart::Part::bytes(data.clone()).file_name(filename.to_string());
            let form = reqwest::multipart::Form::new().part("file", part);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.multipart(form).send().await.context(HttpSnafu)?;
            Self::deserialize("POST", path, resp).await
        })
        .await
    }

    /// GET that ignores the response body (for endpoints with no JSON response).
    ///
    /// Treats 302 as success in addition to 2xx: NiFi's `GET /access/logout/complete`
    /// responds with a redirect once the logout is complete.
    ///
    /// Called from generated static-emitter code; clippy cannot see those
    /// call sites, and dynamic-only builds skip per-version emission so the
    /// helper appears unused there.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self))]
    pub(crate) async fn get_void(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void_with_redirect("GET", path, resp).await
        })
        .await
    }

    /// GET with query parameters; ignores the response body.
    ///
    /// Called by both the static per-version emitter (for GET endpoints
    /// with query params and an empty response) and the dynamic canonical
    /// emitter. No current NiFi 2.x spec triggers the static path, so
    /// this helper is only reached via generated code in `$OUT_DIR` that
    /// clippy's dead-code lint cannot see. Kept available via
    /// `#[allow(dead_code)]` rather than deleted.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, query))]
    pub(crate) async fn get_void_with_query(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void_with_redirect("GET", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, query))]
    pub(crate) async fn get_with_query<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        query: &[(&str, String)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("GET", path, resp).await
        })
        .await
    }

    /// GET returning raw text (`text/plain`).
    #[tracing::instrument(skip(self))]
    pub(crate) async fn get_text(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<String, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::text("GET", path, resp).await
        })
        .await
    }

    /// GET returning raw bytes (`application/octet-stream` or `*/*`).
    #[tracing::instrument(skip(self))]
    pub(crate) async fn get_bytes(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<Vec<u8>, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::bytes("GET", path, resp).await
        })
        .await
    }

    /// GET with query parameters returning raw bytes.
    #[tracing::instrument(skip(self, query))]
    pub(crate) async fn get_bytes_with_query(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        query: &[(&str, String)],
    ) -> Result<Vec<u8>, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "GET", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.get(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::bytes("GET", path, resp).await
        })
        .await
    }

    /// POST with `application/octet-stream` body; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(POST, OctetStream body, Empty response)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, data))]
    pub(crate) async fn post_void_octet_stream(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        data: Vec<u8>,
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self
                .authenticated(self.http.post(url))
                .await
                .header("Content-Type", "application/octet-stream")
                .body(data.clone());
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void("POST", path, resp).await
        })
        .await
    }

    /// POST with `multipart/form-data` body; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(POST, Multipart body, Empty response)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, data))]
    pub(crate) async fn post_void_multipart(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        filename: &str,
        data: Vec<u8>,
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let part =
                reqwest::multipart::Part::bytes(data.clone()).file_name(filename.to_string());
            let form = reqwest::multipart::Form::new().part("file", part);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.multipart(form).send().await.context(HttpSnafu)?;
            Self::check_void("POST", path, resp).await
        })
        .await
    }

    /// POST a JSON body and return the `text/plain` response body.
    ///
    /// Called from generated static-emitter code; clippy cannot see those
    /// call sites, and dynamic-only builds skip per-version emission so the
    /// helper appears unused there.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, body))]
    pub(crate) async fn post_returning_text<B: serde::Serialize>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
    ) -> Result<String, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::text("POST", path, resp).await
        })
        .await
    }

    /// POST an `application/octet-stream` body and return the `text/plain` response body.
    ///
    /// Called from generated static-emitter code; clippy cannot see those
    /// call sites, and dynamic-only builds skip per-version emission so the
    /// helper appears unused there.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, data))]
    pub(crate) async fn post_octet_stream_returning_text(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        data: Vec<u8>,
    ) -> Result<String, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self
                .authenticated(self.http.post(url))
                .await
                .header("Content-Type", "application/octet-stream")
                .body(data.clone());
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::text("POST", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, query))]
    pub(crate) async fn delete_returning_with_query<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        query: &[(&str, String)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "DELETE", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.delete(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("DELETE", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, query))]
    pub(crate) async fn delete_with_query(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "DELETE", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.delete(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void("DELETE", path, resp).await
        })
        .await
    }

    /// POST with a JSON body and query parameters; ignores the response body.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(POST, any body, Empty response, query params)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, body, query))]
    pub(crate) async fn post_void_with_query<B: serde::Serialize>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::check_void("POST", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self, body, query))]
    pub(crate) async fn post_with_query<B, T>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
        query: &[(&str, String)],
    ) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        self.with_retry(|| async {
            tracing::debug!(method = "POST", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.post(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::deserialize("POST", path, resp).await
        })
        .await
    }

    /// PUT with a JSON body and query parameters; deserializes the JSON response.
    ///
    /// Kept available for forward compatibility — the emitter dispatch table at
    /// `emit::method` references this helper for the `(PUT, Json body, Non-empty response, query params)`
    /// combination, but no current NiFi 2.x spec triggers that path.
    #[allow(dead_code)]
    #[tracing::instrument(skip(self, body, query))]
    pub(crate) async fn put_with_query<B, T>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
        body: &B,
        query: &[(&str, String)],
    ) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        self.with_retry(|| async {
            tracing::debug!(method = "PUT", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.put(url).query(query)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.json(body).send().await.context(HttpSnafu)?;
            Self::deserialize("PUT", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self))]
    pub(crate) async fn delete_returning<T: DeserializeOwned>(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<T, NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "DELETE", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.delete(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::deserialize("DELETE", path, resp).await
        })
        .await
    }

    #[tracing::instrument(skip(self))]
    pub(crate) async fn delete(
        &self,
        path: &str,
        extra_headers: &[(&str, &str)],
    ) -> Result<(), NifiError> {
        self.with_retry(|| async {
            tracing::debug!(method = "DELETE", path, "NiFi API request");
            let url = self.api_url(path);
            let mut req = self.authenticated(self.http.delete(url)).await;
            for (name, value) in extra_headers {
                req = req.header(*name, *value);
            }
            let resp = req.send().await.context(HttpSnafu)?;
            Self::check_void("DELETE", path, resp).await
        })
        .await
    }

    /// Inner delete without auth retry, used by `logout` to avoid retrying
    /// the logout call itself.
    async fn delete_inner(&self, path: &str) -> Result<(), NifiError> {
        tracing::debug!(method = "DELETE", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.delete(url))
            .await
            .send()
            .await
            .context(HttpSnafu)?;
        Self::check_void("DELETE", path, resp).await
    }

    async fn authenticated(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        let guard = self.token.read().await;
        let mut req = match guard.as_deref() {
            Some(token) => req.bearer_auth(token),
            None => {
                tracing::warn!(
                    "sending NiFi API request without a bearer token — call login() first"
                );
                req
            }
        };
        if let Some(chain) = &self.proxied_entities_chain {
            req = req.header("X-ProxiedEntitiesChain", chain);
        }
        req
    }

    async fn deserialize<T: DeserializeOwned>(
        method: &str,
        path: &str,
        resp: reqwest::Response,
    ) -> Result<T, NifiError> {
        let status = resp.status();
        tracing::debug!(method, path, status = status.as_u16(), "NiFi API response");
        if status.is_success() {
            return resp.json::<T>().await.context(HttpSnafu);
        }
        let body = resp.text().await.unwrap_or_else(|_| status.to_string());
        tracing::debug!(method, path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method, path, status = status.as_u16(), %message, "NiFi API error");
        Err(crate::error::api_error(status.as_u16(), message))
    }

    /// Check a void response (no JSON body expected). Returns `Ok(())` on success,
    /// or the appropriate error.
    async fn check_void(
        method: &str,
        path: &str,
        resp: reqwest::Response,
    ) -> Result<(), NifiError> {
        let status = resp.status();
        tracing::debug!(method, path, status = status.as_u16(), "NiFi API response");
        if status.is_success() {
            return Ok(());
        }
        let body = resp.text().await.unwrap_or_else(|_| status.to_string());
        tracing::debug!(method, path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method, path, status = status.as_u16(), %message, "NiFi API error");
        Err(crate::error::api_error(status.as_u16(), message))
    }

    /// Read a raw `text/plain` (or equivalent) response body as a `String`.
    async fn text(method: &str, path: &str, resp: reqwest::Response) -> Result<String, NifiError> {
        let status = resp.status();
        tracing::debug!(method, path, status = status.as_u16(), "NiFi API response");
        if status.is_success() {
            return resp.text().await.context(HttpSnafu);
        }
        let body = resp.text().await.unwrap_or_else(|_| status.to_string());
        tracing::debug!(method, path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method, path, status = status.as_u16(), %message, "NiFi API error");
        Err(crate::error::api_error(status.as_u16(), message))
    }

    /// Read a raw `application/octet-stream` (or equivalent) response body as bytes.
    async fn bytes(
        method: &str,
        path: &str,
        resp: reqwest::Response,
    ) -> Result<Vec<u8>, NifiError> {
        let status = resp.status();
        tracing::debug!(method, path, status = status.as_u16(), "NiFi API response");
        if status.is_success() {
            let b = resp.bytes().await.context(HttpSnafu)?;
            return Ok(b.to_vec());
        }
        let body = resp.text().await.unwrap_or_else(|_| status.to_string());
        tracing::debug!(method, path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method, path, status = status.as_u16(), %message, "NiFi API error");
        Err(crate::error::api_error(status.as_u16(), message))
    }

    /// Like `check_void`, but also treats 302 as success.
    async fn check_void_with_redirect(
        method: &str,
        path: &str,
        resp: reqwest::Response,
    ) -> Result<(), NifiError> {
        let status = resp.status();
        tracing::debug!(method, path, status = status.as_u16(), "NiFi API response");
        if status.is_success() || status.as_u16() == 302 {
            return Ok(());
        }
        let body = resp.text().await.unwrap_or_else(|_| status.to_string());
        tracing::debug!(method, path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method, path, status = status.as_u16(), %message, "NiFi API error");
        Err(crate::error::api_error(status.as_u16(), message))
    }

    pub(crate) fn api_url(&self, path: &str) -> Url {
        let mut url = self.base_url.clone();
        url.set_path(&format!("/nifi-api{path}"));
        url
    }
}

/// Extract a human-readable message from a NiFi error response body.
///
/// NiFi returns either a JSON object with a `"message"` field or plain text.
/// Logs the raw body at `debug` level before extracting.
pub fn extract_error_message(body: &str) -> String {
    serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v["message"].as_str().map(str::to_owned))
        .unwrap_or_else(|| body.to_owned())
}