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
//! Operation contracts for the Cloud Monitoring API API (v3).
//!
//! Auto-generated from the GCP Discovery Document.
//! **Do not edit manually** — modify the manifest and re-run codegen.
//!
//! These are the raw HTTP operations with correct URLs, methods,
//! and parameter ordering. The hand-written `api/monitoring.rs` wraps
//! these with ergonomic builders, operation polling, etc.
use crate::types::monitoring::*;
use crate::{GcpHttpClient, Result};
/// Raw HTTP operations for the Cloud Monitoring API API.
///
/// These methods encode the correct URL paths, HTTP methods, and
/// parameter ordering from the GCP Discovery Document.
/// They are `pub(crate)` — use the ergonomic wrappers in
/// [`super::monitoring::MonitoringClient`] instead.
pub struct MonitoringOps<'a> {
pub(crate) client: &'a GcpHttpClient,
}
impl<'a> MonitoringOps<'a> {
pub(crate) fn new(client: &'a GcpHttpClient) -> Self {
Self { client }
}
fn base_url(&self) -> &str {
#[cfg(any(test, feature = "test-support"))]
{
if let Some(ref base) = self.client.base_url {
return base.trim_end_matches('/');
}
}
"https://monitoring.googleapis.com"
}
/// Lists metric descriptors that match a filter.
///
/// **GCP API**: `GET v3/{+name}/metricDescriptors`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) on which to execute the request. The for *(required)*
///
/// # Query Parameters
/// - `activeOnly` — Optional. If true, only metrics and monitored resource types that have recent data (within roughly 25 hours) will be inc
/// - `filter` — Optional. If this field is empty, all custom and system-defined metric descriptors are returned. Otherwise, the filter (
/// - `pageSize` — Optional. A positive number that is the maximum number of results to return. The default and maximum value is 10,000. If
/// - `pageToken` — Optional. If this field is not empty then it must contain the nextPageToken value returned by a previous call to this me
///
/// # Response
/// [`ListMetricDescriptorsResponse`]
#[allow(dead_code)]
pub(crate) async fn list_metric_descriptors(
&self,
name: &str,
filter: &str,
page_size: &str,
page_token: &str,
) -> Result<ListMetricDescriptorsResponse> {
let url = format!("{}/v3/{}/metricDescriptors", self.base_url(), name,);
let url = crate::append_query_params(
url,
&[
("filter", filter),
("pageSize", page_size),
("pageToken", page_token),
],
);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse list_metric_descriptors response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Gets a single metric descriptor.
///
/// **GCP API**: `GET v3/{+name}`
///
/// # Path Parameters
/// - `name` — Required. The metric descriptor on which to execute the request. The format is: projects/[PROJECT_ID_OR_NUMBER]/metricDe *(required)*
///
/// # Response
/// [`MetricDescriptor`]
#[allow(dead_code)]
pub(crate) async fn get_metric_descriptor(&self, name: &str) -> Result<MetricDescriptor> {
let url = format!("{}/v3/{}", self.base_url(), name,);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse get_metric_descriptor response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Lists monitored resource descriptors that match a filter.
///
/// **GCP API**: `GET v3/{+name}/monitoredResourceDescriptors`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) on which to execute the request. The for *(required)*
///
/// # Query Parameters
/// - `filter` — An optional filter (https://cloud.google.com/monitoring/api/v3/filters) describing the descriptors to be returned. The f
/// - `pageSize` — A positive number that is the maximum number of results to return.
/// - `pageToken` — If this field is not empty then it must contain the nextPageToken value returned by a previous call to this method. Usin
///
/// # Response
/// [`ListMonitoredResourceDescriptorsResponse`]
#[allow(dead_code)]
pub(crate) async fn list_monitored_resource_descriptors(
&self,
name: &str,
filter: &str,
page_size: &str,
page_token: &str,
) -> Result<ListMonitoredResourceDescriptorsResponse> {
let url = format!(
"{}/v3/{}/monitoredResourceDescriptors",
self.base_url(),
name,
);
let url = crate::append_query_params(
url,
&[
("filter", filter),
("pageSize", page_size),
("pageToken", page_token),
],
);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse list_monitored_resource_descriptors response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Gets a single monitored resource descriptor.
///
/// **GCP API**: `GET v3/{+name}`
///
/// # Path Parameters
/// - `name` — Required. The monitored resource descriptor to get. The format is: projects/[PROJECT_ID_OR_NUMBER]/monitoredResourceDesc *(required)*
///
/// # Response
/// [`MonitoredResourceDescriptor`]
#[allow(dead_code)]
pub(crate) async fn get_monitored_resource_descriptor(
&self,
name: &str,
) -> Result<MonitoredResourceDescriptor> {
let url = format!("{}/v3/{}", self.base_url(), name,);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse get_monitored_resource_descriptor response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Lists the existing alerting policies for the workspace.
///
/// **GCP API**: `GET v3/{+name}/alertPolicies`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) whose alert policies are to be listed. T *(required)*
///
/// # Query Parameters
/// - `filter` — Optional. If provided, this field specifies the criteria that must be met by alert policies to be included in the respon
/// - `orderBy` — Optional. A comma-separated list of fields by which to sort the result. Supports the same set of field references as the
/// - `pageSize` — Optional. The maximum number of results to return in a single response.
/// - `pageToken` — Optional. If this field is not empty then it must contain the nextPageToken value returned by a previous call to this me
///
/// # Response
/// [`ListAlertPoliciesResponse`]
#[allow(dead_code)]
pub(crate) async fn list_alert_policies(
&self,
name: &str,
filter: &str,
page_size: &str,
page_token: &str,
) -> Result<ListAlertPoliciesResponse> {
let url = format!("{}/v3/{}/alertPolicies", self.base_url(), name,);
let url = crate::append_query_params(
url,
&[
("filter", filter),
("pageSize", page_size),
("pageToken", page_token),
],
);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse list_alert_policies response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Creates a new alerting policy.Design your application to single-thread API calls that
/// modify the state of alerting policies in a single project. This includes calls to
/// CreateAlertPolicy, DeleteAlertPolicy and UpdateAlertPolicy.
///
/// **GCP API**: `POST v3/{+name}/alertPolicies`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) in which to create the alerting policy. *(required)*
///
/// # Request Body
/// [`AlertPolicy`]
///
/// # Response
/// [`AlertPolicy`]
#[allow(dead_code)]
pub(crate) async fn create_alert_policy(
&self,
name: &str,
body: &AlertPolicy,
) -> Result<AlertPolicy> {
let url = format!("{}/v3/{}/alertPolicies", self.base_url(), name,);
let response = self.client.post(&url, body).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse create_alert_policy response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Deletes an alerting policy.Design your application to single-thread API calls that
/// modify the state of alerting policies in a single project. This includes calls to
/// CreateAlertPolicy, DeleteAlertPolicy and UpdateAlertPolicy.
///
/// **GCP API**: `DELETE v3/{+name}`
///
/// # Path Parameters
/// - `name` — Required. The alerting policy to delete. The format is: projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID] *(required)*
///
/// # Response
/// [`MonitoringEmpty`]
#[allow(dead_code)]
pub(crate) async fn delete_alert_policy(&self, name: &str) -> Result<MonitoringEmpty> {
let url = format!("{}/v3/{}", self.base_url(), name,);
let response = self.client.delete(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse delete_alert_policy response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Lists the notification channels that have been created for the project. To list the
/// types of notification channels that are supported, use the
/// ListNotificationChannelDescriptors method.
///
/// **GCP API**: `GET v3/{+name}/notificationChannels`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) on which to execute the request. The for *(required)*
///
/// # Query Parameters
/// - `filter` — Optional. If provided, this field specifies the criteria that must be met by notification channels to be included in the
/// - `orderBy` — Optional. A comma-separated list of fields by which to sort the result. Supports the same set of fields as in filter. En
/// - `pageSize` — Optional. The maximum number of results to return in a single response. If not set to a positive number, a reasonable va
/// - `pageToken` — Optional. If non-empty, page_token must contain a value returned as the next_page_token in a previous response to reques
///
/// # Response
/// [`ListNotificationChannelsResponse`]
#[allow(dead_code)]
pub(crate) async fn list_notification_channels(
&self,
name: &str,
filter: &str,
page_size: &str,
page_token: &str,
) -> Result<ListNotificationChannelsResponse> {
let url = format!("{}/v3/{}/notificationChannels", self.base_url(), name,);
let url = crate::append_query_params(
url,
&[
("filter", filter),
("pageSize", page_size),
("pageToken", page_token),
],
);
let response = self.client.get(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse list_notification_channels response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Creates a new notification channel, representing a single notification endpoint such as
/// an email address, SMS number, or PagerDuty service.Design your application to single-
/// thread API calls that modify the state of notification channels in a single project.
/// This includes calls to CreateNotificationChannel, DeleteNotificationChannel and
/// UpdateNotificationChannel.
///
/// **GCP API**: `POST v3/{+name}/notificationChannels`
///
/// # Path Parameters
/// - `name` — Required. The project (https://cloud.google.com/monitoring/api/v3#project_name) on which to execute the request. The for *(required)*
///
/// # Request Body
/// [`NotificationChannel`]
///
/// # Response
/// [`NotificationChannel`]
#[allow(dead_code)]
pub(crate) async fn create_notification_channel(
&self,
name: &str,
body: &NotificationChannel,
) -> Result<NotificationChannel> {
let url = format!("{}/v3/{}/notificationChannels", self.base_url(), name,);
let response = self.client.post(&url, body).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse create_notification_channel response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
/// Deletes a notification channel.Design your application to single-thread API calls that
/// modify the state of notification channels in a single project. This includes calls to
/// CreateNotificationChannel, DeleteNotificationChannel and UpdateNotificationChannel.
///
/// **GCP API**: `DELETE v3/{+name}`
///
/// # Path Parameters
/// - `name` — Required. The channel for which to execute the request. The format is: projects/[PROJECT_ID_OR_NUMBER]/notificationChann *(required)*
///
/// # Query Parameters
/// - `force` — If true, the notification channel will be deleted regardless of its use in alert policies (the policies will be updated
///
/// # Response
/// [`MonitoringEmpty`]
#[allow(dead_code)]
pub(crate) async fn delete_notification_channel(&self, name: &str) -> Result<MonitoringEmpty> {
let url = format!("{}/v3/{}", self.base_url(), name,);
let response = self.client.delete(&url).await?;
serde_json::from_slice(&response).map_err(|e| crate::GcpError::InvalidResponse {
message: format!("Failed to parse delete_notification_channel response: {e}"),
body: Some(String::from_utf8_lossy(&response).to_string()),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_list_metric_descriptors() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name/metricDescriptors?filter=test-filter&pageSize=test-pageSize&pageToken=test-pageToken")
.returning_json(serde_json::to_value(ListMetricDescriptorsResponse::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops
.list_metric_descriptors(
"test-name",
"test-filter",
"test-pageSize",
"test-pageToken",
)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_get_metric_descriptor() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name")
.returning_json(serde_json::to_value(MetricDescriptor::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops.get_metric_descriptor("test-name").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_list_monitored_resource_descriptors() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name/monitoredResourceDescriptors?filter=test-filter&pageSize=test-pageSize&pageToken=test-pageToken")
.returning_json(serde_json::to_value(ListMonitoredResourceDescriptorsResponse::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops
.list_monitored_resource_descriptors(
"test-name",
"test-filter",
"test-pageSize",
"test-pageToken",
)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_get_monitored_resource_descriptor() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name")
.returning_json(serde_json::to_value(MonitoredResourceDescriptor::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops.get_monitored_resource_descriptor("test-name").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_list_alert_policies() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name/alertPolicies?filter=test-filter&pageSize=test-pageSize&pageToken=test-pageToken")
.returning_json(serde_json::to_value(ListAlertPoliciesResponse::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops
.list_alert_policies(
"test-name",
"test-filter",
"test-pageSize",
"test-pageToken",
)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_create_alert_policy() {
let mut mock = crate::MockClient::new();
mock.expect_post("/v3/test-name/alertPolicies")
.returning_json(serde_json::to_value(AlertPolicy::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let body = AlertPolicy::fixture();
let result = ops.create_alert_policy("test-name", &body).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_delete_alert_policy() {
let mut mock = crate::MockClient::new();
mock.expect_delete("/v3/test-name")
.returning_json(serde_json::to_value(MonitoringEmpty::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops.delete_alert_policy("test-name").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_list_notification_channels() {
let mut mock = crate::MockClient::new();
mock.expect_get("/v3/test-name/notificationChannels?filter=test-filter&pageSize=test-pageSize&pageToken=test-pageToken")
.returning_json(serde_json::to_value(ListNotificationChannelsResponse::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops
.list_notification_channels(
"test-name",
"test-filter",
"test-pageSize",
"test-pageToken",
)
.await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_create_notification_channel() {
let mut mock = crate::MockClient::new();
mock.expect_post("/v3/test-name/notificationChannels")
.returning_json(serde_json::to_value(NotificationChannel::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let body = NotificationChannel::fixture();
let result = ops.create_notification_channel("test-name", &body).await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_delete_notification_channel() {
let mut mock = crate::MockClient::new();
mock.expect_delete("/v3/test-name")
.returning_json(serde_json::to_value(MonitoringEmpty::fixture()).unwrap());
let client = crate::GcpHttpClient::from_mock(mock);
let ops = MonitoringOps::new(&client);
let result = ops.delete_notification_channel("test-name").await;
assert!(result.is_ok());
}
}