nifi-rust-client 0.2.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
use reqwest::Client;
use serde::de::DeserializeOwned;
use snafu::ResultExt as _;
use url::Url;

use crate::NifiError;
use crate::error::{ApiSnafu, AuthSnafu, HttpSnafu};

/// Client for the Apache NiFi REST API.
#[derive(Debug, Clone)]
pub struct NifiClient {
    base_url: Url,
    http: Client,
    token: Option<String>,
}

impl NifiClient {
    /// Construct a client from pre-built parts. Used by [`crate::NifiClientBuilder`].
    pub(crate) fn from_parts(base_url: Url, http: Client) -> Self {
        Self {
            base_url,
            http,
            token: None,
        }
    }

    /// 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::Api`] with `status == 401`. Re-call
    /// [`login`][Self::login] to obtain a fresh token.
    pub fn token(&self) -> Option<&str> {
        self.token.as_deref()
    }

    /// 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::Api`] with `status == 401`; re-call [`login`][Self::login]
    /// to obtain a fresh one.
    pub fn set_token(&mut self, token: String) {
        self.token = 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.
    pub async fn logout(&mut self) -> Result<(), NifiError> {
        let result = self.delete("/access/logout").await;
        self.token = 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::Api`] with `status == 401`. The
    /// recommended pattern:
    ///
    /// ```no_run
    /// # #[cfg(not(feature = "dynamic"))]
    /// # async fn example(client: &mut nifi_rust_client::NifiClient) -> Result<(), nifi_rust_client::NifiError> {
    /// use nifi_rust_client::NifiError;
    /// match client.flow_api().get_about_info().await {
    ///     Err(NifiError::Api { status: 401, .. }) => {
    ///         client.login("admin", "password").await?;
    ///         // retry the call
    ///     }
    ///     other => { other?; }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Automatic re-login is not built in: storing credentials on the client
    /// would keep plaintext passwords in memory for the lifetime of the process,
    /// which is undesirable in most contexts.
    pub async fn login(&mut 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 = Some(token);
        tracing::info!("NiFi login successful for {username}");
        Ok(())
    }

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

    pub(crate) async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, NifiError> {
        tracing::debug!(method = "GET", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.get(url))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("GET", path, resp).await
    }

    pub(crate) async fn post<B, T>(&self, path: &str, body: &B) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.post(url))
            .json(body)
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("POST", path, resp).await
    }

    pub(crate) async fn put<B, T>(&self, path: &str, body: &B) -> Result<T, NifiError>
    where
        B: serde::Serialize,
        T: DeserializeOwned,
    {
        tracing::debug!(method = "PUT", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.put(url))
            .json(body)
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("PUT", path, resp).await
    }

    /// POST that ignores the response body (for endpoints with no JSON response).
    pub(crate) async fn post_void<B: serde::Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.post(url))
            .json(body)
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "POST",
            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 = "POST", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "POST", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// PUT that ignores the response body (for endpoints with no JSON response).
    #[allow(dead_code)]
    pub(crate) async fn put_void<B: serde::Serialize>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "PUT", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.put(url))
            .json(body)
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "PUT",
            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 = "PUT", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "PUT", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// POST with no request body; deserializes the JSON response.
    pub(crate) async fn post_no_body<T: DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.post(url))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("POST", path, resp).await
    }

    /// POST with no request body; ignores the response body.
    pub(crate) async fn post_void_no_body(&self, path: &str) -> Result<(), NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.post(url))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "POST",
            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 = "POST", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "POST", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// PUT with no request body; deserializes the JSON response.
    pub(crate) async fn put_no_body<T: DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "PUT", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.put(url))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("PUT", path, resp).await
    }

    /// PUT with no request body; ignores the response body.
    #[allow(dead_code)]
    pub(crate) async fn put_void_no_body(&self, path: &str) -> Result<(), NifiError> {
        tracing::debug!(method = "PUT", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.put(url))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "PUT",
            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 = "PUT", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "PUT", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// POST with `application/octet-stream` body.
    ///
    /// Used for binary upload endpoints (e.g. NAR upload).
    /// `filename` is sent as the `Filename` request header when provided.
    pub(crate) async fn post_octet_stream<T: DeserializeOwned>(
        &self,
        path: &str,
        filename: Option<&str>,
        data: Vec<u8>,
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let builder = self
            .authenticated(self.http.post(url))
            .header("Content-Type", "application/octet-stream")
            .body(data);
        let builder = if let Some(name) = filename {
            builder.header("Filename", name)
        } else {
            builder
        };
        let resp = builder.send().await.context(HttpSnafu)?;
        Self::deserialize("POST", path, resp).await
    }

    /// POST with `application/octet-stream` body; ignores the response body.
    ///
    /// Used for binary upload endpoints that return no JSON response.
    /// `filename` is sent as the `Filename` request header when provided.
    pub(crate) async fn post_void_octet_stream(
        &self,
        path: &str,
        filename: Option<&str>,
        data: Vec<u8>,
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let builder = self
            .authenticated(self.http.post(url))
            .header("Content-Type", "application/octet-stream")
            .body(data);
        let builder = if let Some(name) = filename {
            builder.header("Filename", name)
        } else {
            builder
        };
        let resp = builder.send().await.context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "POST",
            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 = "POST", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "POST", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// POST with query parameters; ignores the response body.
    ///
    /// Used for endpoints that accept query parameters and have no JSON response body.
    #[allow(dead_code)]
    pub(crate) async fn post_void_with_query<B: serde::Serialize>(
        &self,
        path: &str,
        body: &B,
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "POST", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.post(url).query(query))
            .json(body)
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "POST",
            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 = "POST", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "POST", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    /// 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.
    pub(crate) async fn get_void(&self, path: &str) -> Result<(), NifiError> {
        tracing::debug!(method = "GET", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.get(url))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "GET",
            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 = "GET", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "GET", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    pub(crate) async fn get_with_query<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "GET", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.get(url).query(query))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("GET", path, resp).await
    }

    pub(crate) async fn get_void_with_query(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "GET", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.get(url).query(query))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "GET",
            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 = "GET", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "GET", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    pub(crate) async fn delete_returning_with_query<T: DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "DELETE", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.delete(url).query(query))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("DELETE", path, resp).await
    }

    pub(crate) async fn delete_with_query(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<(), NifiError> {
        tracing::debug!(method = "DELETE", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.delete(url).query(query))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "DELETE",
            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 = "DELETE", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "DELETE", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

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

    pub(crate) async fn delete_returning<T: DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<T, NifiError> {
        tracing::debug!(method = "DELETE", path, "NiFi API request");
        let url = self.api_url(path);
        let resp = self
            .authenticated(self.http.delete(url))
            .send()
            .await
            .context(HttpSnafu)?;
        Self::deserialize("DELETE", path, resp).await
    }

    pub(crate) async fn delete(&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))
            .send()
            .await
            .context(HttpSnafu)?;
        let status = resp.status();
        tracing::debug!(
            method = "DELETE",
            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 = "DELETE", path, status = status.as_u16(), %body, "NiFi API raw error body");
        let message = extract_error_message(&body);
        tracing::warn!(method = "DELETE", path, status = status.as_u16(), %message, "NiFi API error");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    fn authenticated(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
        match &self.token {
            Some(token) => req.bearer_auth(token),
            None => {
                tracing::warn!(
                    "sending NiFi API request without a bearer token — call login() first"
                );
                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");
        ApiSnafu {
            status: status.as_u16(),
            message,
        }
        .fail()
    }

    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())
}