bestool-alertd 2.0.2

(Internal) BES tooling: Alert daemon
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
use std::{sync::Arc, time::Duration};

use bestool_alertd::{AlertDefinition, InternalContext};
use bestool_postgres::pool::{PgPool, create_pool};

async fn setup_test_db(table_name: &str) -> (PgPool, String) {
	let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set for tests");
	let pool = create_pool(&db_url, "bestool-alertd-test").await.unwrap();

	let client = pool.get().await.unwrap();

	// Create a unique test table for this test
	let create_sql = format!(
		"CREATE TABLE IF NOT EXISTS {} (
			id SERIAL PRIMARY KEY,
			name TEXT NOT NULL,
			value REAL NOT NULL,
			error_count INTEGER NOT NULL,
			created_at TIMESTAMP DEFAULT NOW(),
			updated_at TIMESTAMP DEFAULT NOW()
		)",
		table_name
	);
	client.execute(&create_sql, &[]).await.unwrap();

	// Clean up any existing test data in this table
	let delete_sql = format!("DELETE FROM {}", table_name);
	client.execute(&delete_sql, &[]).await.unwrap();

	(pool, table_name.to_string())
}

#[tokio::test]
async fn test_numerical_threshold_normal_trigger() {
	let (pool, table_name) = setup_test_db("test_metrics_normal").await;

	// Insert test data
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count) VALUES ('cpu_usage', 95.5, 10)",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT value FROM {} WHERE name = 'cpu_usage'"
numerical:
  - field: value
    alert-at: 90
    clear-at: 50
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// First run - not yet triggered, should trigger because value >= 90
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should trigger when value >= alert-at"
	);

	// Second run - already triggered, should stay triggered because value > clear-at
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should stay triggered when value > clear-at"
	);

	// Update to clear the alert
	let client = ctx.pg_pool.get().await.unwrap();
	let update_sql = format!(
		"UPDATE {} SET value = 40 WHERE name = 'cpu_usage'",
		table_name
	);
	client.execute(&update_sql, &[]).await.unwrap();

	// Third run - should clear because value <= clear-at
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_break(),
		"Should clear when value <= clear-at (40 <= 50)"
	);
}

#[tokio::test]
async fn test_numerical_threshold_inverted_trigger() {
	let (pool, table_name) = setup_test_db("test_metrics_inverted").await;

	// Insert test data with low free space
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count) VALUES ('free_space_gb', 5.0, 0)",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT value FROM {} WHERE name = 'free_space_gb'"
numerical:
  - field: value
    alert-at: 10
    clear-at: 50
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// First run - not yet triggered, should trigger because value <= 10 (inverted)
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should trigger when value <= alert-at (inverted)"
	);

	// Second run - already triggered, should stay triggered because value < clear-at
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should stay triggered when value < clear-at (inverted)"
	);

	// Update to clear the alert
	let client = ctx.pg_pool.get().await.unwrap();
	let update_sql = format!(
		"UPDATE {} SET value = 60 WHERE name = 'free_space_gb'",
		table_name
	);
	client.execute(&update_sql, &[]).await.unwrap();

	// Third run - should clear because value >= clear-at (inverted)
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_break(),
		"Should clear when value >= clear-at (60 >= 50, inverted)"
	);
}

#[tokio::test]
async fn test_when_changed_simple() {
	let (pool, table_name) = setup_test_db("test_metrics_changed_simple").await;

	// Insert initial data
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count) VALUES ('errors', 100.0, 5)",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT error_count FROM {} WHERE name = 'errors'"
when-changed: true
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});

	// First execution - should trigger (first run always triggers)
	alert.execute(ctx.clone(), None, true, &[]).await.unwrap();
	// No error means it executed

	// Second execution with same data - would trigger but when-changed should prevent it
	// We can't easily test this without the full scheduler state, but we can verify the serialization

	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());
	let _ = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();

	// Verify context has rows
	assert!(tera_ctx.get("rows").is_some());
}

#[tokio::test]
async fn test_when_changed_with_except() {
	let (pool, table_name) = setup_test_db("test_metrics_changed_except").await;

	// Insert initial data
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count, created_at, updated_at)
		 VALUES ('test', 100.0, 5, NOW(), NOW())",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT error_count, created_at, updated_at FROM {} WHERE name = 'test'"
when-changed:
  except: [created_at, updated_at]
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// Read initial data
	let _ = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();

	let rows = tera_ctx.get("rows").unwrap();
	assert!(!rows.as_array().unwrap().is_empty());

	// Update only timestamps - when-changed should consider this unchanged
	tokio::time::sleep(Duration::from_millis(10)).await;
	let client = ctx.pg_pool.get().await.unwrap();
	let update_sql = format!(
		"UPDATE {} SET updated_at = NOW() WHERE name = 'test'",
		table_name
	);
	client.execute(&update_sql, &[]).await.unwrap();

	// The serialization should be the same because we excluded timestamp columns
	// This would be verified in the scheduler's change detection logic
}

#[tokio::test]
async fn test_when_changed_with_only() {
	let (pool, table_name) = setup_test_db("test_metrics_changed_only").await;

	// Insert initial data
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count) VALUES ('test', 100.0, 5)",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT error_count, value FROM {} WHERE name = 'test'"
when-changed:
  only: [error_count]
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// Read initial data
	let _ = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();

	// Update value (not in 'only' list) - should be considered unchanged
	let client = ctx.pg_pool.get().await.unwrap();
	let update_sql1 = format!("UPDATE {} SET value = 200 WHERE name = 'test'", table_name);
	client.execute(&update_sql1, &[]).await.unwrap();

	// Update error_count (in 'only' list) - should be considered changed
	let update_sql2 = format!(
		"UPDATE {} SET error_count = 10 WHERE name = 'test'",
		table_name
	);
	client.execute(&update_sql2, &[]).await.unwrap();

	let mut tera_ctx2 = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());
	let _ = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx2,
			false,
		)
		.await
		.unwrap();

	// Both contexts should have rows
	assert!(tera_ctx.get("rows").is_some());
	assert!(tera_ctx2.get("rows").is_some());
}

#[tokio::test]
async fn test_numerical_and_when_changed_together() {
	let (pool, table_name) = setup_test_db("test_metrics_combo").await;

	// Insert initial data
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count, created_at)
		 VALUES ('combo', 95.0, 100, NOW())",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT value, error_count, created_at FROM {} WHERE name = 'combo'"
numerical:
  - field: value
    alert-at: 90
    clear-at: 50
when-changed:
  except: [created_at]
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// First run - should trigger due to numerical threshold
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should trigger when numerical threshold exceeded"
	);

	// Verify rows are in context
	assert!(tera_ctx.get("rows").is_some());
	let rows = tera_ctx.get("rows").unwrap().as_array().unwrap();
	assert_eq!(rows.len(), 1);
}

#[tokio::test]
async fn test_multiple_numerical_thresholds() {
	let (pool, table_name) = setup_test_db("test_metrics_multi").await;

	// Insert test data with multiple fields
	let client = pool.get().await.unwrap();
	let insert_sql = format!(
		"INSERT INTO {} (name, value, error_count) VALUES ('multi', 95.0, 150)",
		table_name
	);
	client.execute(&insert_sql, &[]).await.unwrap();

	let yaml = format!(
		r#"
sql: "SELECT value as cpu, error_count as errors FROM {} WHERE name = 'multi'"
numerical:
  - field: cpu
    alert-at: 90
    clear-at: 50
  - field: errors
    alert-at: 100
    clear-at: 50
send:
  - id: test
    subject: Test
    template: Test
"#,
		table_name
	);

	let mut alert: AlertDefinition = serde_yaml::from_str(&yaml).unwrap();
	alert.file = "test.yml".into();
	let (alert, _) = alert.normalise(&Default::default()).unwrap();

	let ctx = Arc::new(InternalContext {
		pg_pool: pool,
		http_client: reqwest::Client::new(),
		canopy_client: None,
	});
	let mut tera_ctx = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());

	// Should trigger because both thresholds are exceeded
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx,
			false,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should trigger when any threshold is exceeded"
	);

	// Lower cpu but keep errors high
	let client = ctx.pg_pool.get().await.unwrap();
	let update_sql1 = format!("UPDATE {} SET value = 40 WHERE name = 'multi'", table_name);
	client.execute(&update_sql1, &[]).await.unwrap();

	let mut tera_ctx2 = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx2,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_continue(),
		"Should stay triggered because errors threshold still exceeded"
	);

	// Lower both to clear
	let update_sql2 = format!(
		"UPDATE {} SET error_count = 30 WHERE name = 'multi'",
		table_name
	);
	client.execute(&update_sql2, &[]).await.unwrap();

	let mut tera_ctx3 = bestool_alertd::templates::build_context(&alert, jiff::Timestamp::now());
	let result = alert
		.read_sources(
			&ctx.pg_pool,
			jiff::Timestamp::now() - alert.interval_duration,
			&mut tera_ctx3,
			true,
		)
		.await
		.unwrap();
	assert!(
		result.is_break(),
		"Should clear when all thresholds are below clear-at"
	);
}