omni-dev 0.26.0

A powerful Git commit message analysis and amendment toolkit
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
//! In-memory, TTL-bounded cache for near-static JIRA catalogue API responses.
//!
//! Wraps [`AtlassianClient::get_link_types`], [`get_fields`], [`get_projects`],
//! and [`get_boards`] so that repeated MCP calls within a single server process
//! do not re-fetch catalogue data that admins change rarely. See ADR-0024.
//!
//! Single-flight is achieved without an extra mutex: a stale-or-empty read
//! upgrades to a write lock and double-checks before fetching, so concurrent
//! waiters serialise on the lock and only the first fetches.
//!
//! Parameterised client methods (`get_projects(limit)`,
//! `get_boards(project, board_type, limit)`) are cached by **fetching the full
//! unfiltered result** and applying limits/filters at the caller; this keeps
//! the cache hit rate independent of caller arguments.
//!
//! [`get_fields`]: AtlassianClient::get_fields
//! [`get_projects`]: AtlassianClient::get_projects
//! [`get_boards`]: AtlassianClient::get_boards

use std::future::Future;
use std::sync::Arc;
use std::time::{Duration, Instant};

use anyhow::Result;
use tokio::sync::RwLock;

use crate::atlassian::client::{
    AgileBoardList, AtlassianClient, JiraField, JiraLinkType, JiraProjectList,
};

/// Default cache lifetime. Catalogue data changes rarely (admin-only).
pub const DEFAULT_TTL: Duration = Duration::from_secs(3600);

/// One cached catalogue result, tagged with the JIRA instance it came from.
struct CacheEntry<T> {
    instance_url: String,
    fetched_at: Instant,
    value: Arc<T>,
}

/// Shared cache for the four near-static JIRA catalogues.
///
/// Cloning is cheap (wrap in `Arc<CatalogueCache>` at the owner). Each catalogue
/// has its own `RwLock`, so contention on one does not block the others.
pub struct CatalogueCache {
    link_types: RwLock<Option<CacheEntry<Vec<JiraLinkType>>>>,
    fields: RwLock<Option<CacheEntry<Vec<JiraField>>>>,
    projects: RwLock<Option<CacheEntry<JiraProjectList>>>,
    boards: RwLock<Option<CacheEntry<AgileBoardList>>>,
    ttl: Duration,
}

impl CatalogueCache {
    /// Constructs a cache with the given entry lifetime.
    #[must_use]
    pub fn new(ttl: Duration) -> Self {
        Self {
            link_types: RwLock::new(None),
            fields: RwLock::new(None),
            projects: RwLock::new(None),
            boards: RwLock::new(None),
            ttl,
        }
    }

    /// Returns the cached link-type catalogue, fetching it on miss/expiry.
    pub async fn link_types(&self, client: &AtlassianClient) -> Result<Arc<Vec<JiraLinkType>>> {
        get_or_fetch(
            &self.link_types,
            client.instance_url(),
            self.ttl,
            || async { client.get_link_types().await },
        )
        .await
    }

    /// Returns the cached field catalogue, fetching it on miss/expiry.
    pub async fn fields(&self, client: &AtlassianClient) -> Result<Arc<Vec<JiraField>>> {
        get_or_fetch(&self.fields, client.instance_url(), self.ttl, || async {
            client.get_fields().await
        })
        .await
    }

    /// Returns the cached project list (unbounded), fetching it on miss/expiry.
    ///
    /// Always fetches with `limit=0` (unlimited); callers slice/filter the
    /// returned list.
    pub async fn projects(&self, client: &AtlassianClient) -> Result<Arc<JiraProjectList>> {
        get_or_fetch(&self.projects, client.instance_url(), self.ttl, || async {
            client.get_projects(0).await
        })
        .await
    }

    /// Returns the cached board list (unfiltered, unbounded), fetching on
    /// miss/expiry.
    ///
    /// Always fetches with `project=None`, `board_type=None`, `limit=0`;
    /// callers apply filters/slicing.
    pub async fn boards(&self, client: &AtlassianClient) -> Result<Arc<AgileBoardList>> {
        get_or_fetch(&self.boards, client.instance_url(), self.ttl, || async {
            client.get_boards(None, None, 0).await
        })
        .await
    }
}

impl Default for CatalogueCache {
    fn default() -> Self {
        Self::new(DEFAULT_TTL)
    }
}

/// Read-fast-path / write-on-miss lookup for a single cache slot.
///
/// On miss or expiry, the write lock is held for the duration of the fetch so
/// that concurrent waiters see the populated entry on re-check rather than
/// each issuing their own request. Errors do not poison the cache: the slot
/// is left untouched and the error propagates.
async fn get_or_fetch<T, F, Fut>(
    slot: &RwLock<Option<CacheEntry<T>>>,
    instance_url: &str,
    ttl: Duration,
    fetch: F,
) -> Result<Arc<T>>
where
    T: Send + Sync,
    F: FnOnce() -> Fut + Send,
    Fut: Future<Output = Result<T>> + Send,
{
    if let Some(value) = read_fresh(slot, instance_url, ttl).await {
        return Ok(value);
    }

    let mut guard = slot.write().await;
    if let Some(entry) = guard.as_ref() {
        if entry.instance_url == instance_url && entry.fetched_at.elapsed() < ttl {
            return Ok(Arc::clone(&entry.value));
        }
    }

    let value = Arc::new(fetch().await?);
    *guard = Some(CacheEntry {
        instance_url: instance_url.to_string(),
        fetched_at: Instant::now(),
        value: Arc::clone(&value),
    });
    Ok(value)
}

async fn read_fresh<T>(
    slot: &RwLock<Option<CacheEntry<T>>>,
    instance_url: &str,
    ttl: Duration,
) -> Option<Arc<T>>
where
    T: Send + Sync,
{
    let guard = slot.read().await;
    let entry = guard.as_ref()?;
    if entry.instance_url == instance_url && entry.fetched_at.elapsed() < ttl {
        Some(Arc::clone(&entry.value))
    } else {
        None
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn mock_client(base_url: &str) -> AtlassianClient {
        AtlassianClient::new(base_url, "u@t.com", "tok").unwrap()
    }

    fn link_types_body() -> serde_json::Value {
        serde_json::json!({
            "issueLinkTypes": [
                {"id": "1", "name": "Blocks", "inward": "is blocked by", "outward": "blocks"}
            ]
        })
    }

    fn fields_body() -> serde_json::Value {
        serde_json::json!([
            {"id": "summary", "name": "Summary", "custom": false}
        ])
    }

    fn projects_body() -> serde_json::Value {
        serde_json::json!({
            "values": [{"id": "10001", "key": "PROJ", "name": "Project"}],
            "total": 1,
            "isLast": true
        })
    }

    fn boards_body() -> serde_json::Value {
        serde_json::json!({
            "values": [{"id": 1, "name": "B", "type": "scrum"}],
            "isLast": true
        })
    }

    #[tokio::test]
    async fn link_types_cached_after_first_call() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(ResponseTemplate::new(200).set_body_json(link_types_body()))
            .expect(1)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_secs(60));

        let a = cache.link_types(&client).await.unwrap();
        let b = cache.link_types(&client).await.unwrap();

        assert_eq!(a.len(), 1);
        assert_eq!(b.len(), 1);
        assert_eq!(a[0].name, "Blocks");
    }

    #[tokio::test]
    async fn fields_cached_after_first_call() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/field"))
            .respond_with(ResponseTemplate::new(200).set_body_json(fields_body()))
            .expect(1)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_secs(60));

        let _ = cache.fields(&client).await.unwrap();
        let second = cache.fields(&client).await.unwrap();
        assert_eq!(second[0].name, "Summary");
    }

    #[tokio::test]
    async fn projects_cached_after_first_call() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/project/search"))
            .respond_with(ResponseTemplate::new(200).set_body_json(projects_body()))
            .expect(1)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_secs(60));

        let _ = cache.projects(&client).await.unwrap();
        let second = cache.projects(&client).await.unwrap();
        assert_eq!(second.projects[0].key, "PROJ");
    }

    #[tokio::test]
    async fn boards_cached_after_first_call() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/agile/1.0/board"))
            .respond_with(ResponseTemplate::new(200).set_body_json(boards_body()))
            .expect(1)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_secs(60));

        let _ = cache.boards(&client).await.unwrap();
        let second = cache.boards(&client).await.unwrap();
        assert_eq!(second.boards[0].name, "B");
    }

    #[tokio::test]
    async fn cache_refetches_after_ttl_expiry() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(ResponseTemplate::new(200).set_body_json(link_types_body()))
            .expect(2)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_millis(20));

        let _ = cache.link_types(&client).await.unwrap();
        tokio::time::sleep(Duration::from_millis(40)).await;
        let _ = cache.link_types(&client).await.unwrap();
    }

    #[tokio::test]
    async fn cache_refetches_when_instance_url_changes() {
        let server_a = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(ResponseTemplate::new(200).set_body_json(link_types_body()))
            .expect(1)
            .mount(&server_a)
            .await;
        let server_b = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(ResponseTemplate::new(200).set_body_json(link_types_body()))
            .expect(1)
            .mount(&server_b)
            .await;

        let cache = CatalogueCache::new(Duration::from_secs(60));
        let client_a = mock_client(&server_a.uri());
        let client_b = mock_client(&server_b.uri());

        let _ = cache.link_types(&client_a).await.unwrap();
        let _ = cache.link_types(&client_b).await.unwrap();
        // Re-call against A: cache now holds B's entry, so a refetch from A is
        // expected. Server A's `.expect(1)` will fail if we re-hit it here,
        // which is the correct semantics — cache holds at most one entry.
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn concurrent_refresh_shares_a_single_fetch() {
        // Exercise the write-lock double-check (the inner
        // `Arc::clone(&entry.value)` return) under a deterministically
        // engineered race.
        //
        // Strategy:
        //
        //  1. Hold an external write lock on the slot, pre-populated with
        //     a *stale* entry. While held, every task that calls
        //     `read_fresh` blocks on the slot's read lock.
        //  2. Spawn two tasks calling `cache.link_types(&client)`. They
        //     both park inside `read_fresh` waiting for the read lock.
        //  3. Drop the external write lock. Both tasks wake, acquire read
        //     locks concurrently (multiple readers permitted), observe
        //     `Some(stale)` and short-circuit to `None`, drop their read
        //     locks, and queue for the write lock.
        //  4. The first to acquire the write lock fetches (with a
        //     server-side delay so contention is unambiguous), populates
        //     the slot fresh, and releases.
        //  5. The second wakes, finds `Some(fresh)`, and returns via the
        //     double-check — covering line 139.
        //
        // A naive "spawn against a cold slot" race does not exercise the
        // double-check because the first task's write lock blocks all
        // subsequent `read_fresh` reads, so later tasks observe the
        // populated slot via `read_fresh`'s fast path instead of through
        // the write-lock-then-double-check path.
        //
        // Multi-thread runtime is required so the two readers run on
        // separate workers and the read-lock acquisitions truly overlap.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(link_types_body())
                    .set_delay(Duration::from_millis(100)),
            )
            .expect(1)
            .mount(&server)
            .await;

        let cache = Arc::new(CatalogueCache::new(Duration::from_secs(60)));
        let url = server.uri();

        let mut gate = cache.link_types.write().await;
        *gate = Some(CacheEntry {
            instance_url: url.clone(),
            fetched_at: Instant::now()
                .checked_sub(Duration::from_secs(3600 * 24))
                .unwrap(),
            value: Arc::new(Vec::new()),
        });

        let mut handles = Vec::new();
        for _ in 0..2 {
            let cache = Arc::clone(&cache);
            let url = url.clone();
            handles.push(tokio::spawn(async move {
                let client = mock_client(&url);
                cache.link_types(&client).await.unwrap()
            }));
        }

        // Both tasks now block on `slot.read().await` inside `read_fresh`
        // because we hold the write gate.
        tokio::time::sleep(Duration::from_millis(50)).await;
        drop(gate);

        for h in handles {
            let v = h.await.unwrap();
            assert_eq!(v.len(), 1);
            assert_eq!(v[0].name, "Blocks");
        }
    }

    #[tokio::test]
    async fn cache_does_not_populate_on_error() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/rest/api/3/issueLinkType"))
            .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
            .expect(2)
            .mount(&server)
            .await;
        let client = mock_client(&server.uri());
        let cache = CatalogueCache::new(Duration::from_secs(60));

        assert!(cache.link_types(&client).await.is_err());
        assert!(cache.link_types(&client).await.is_err());
    }
}