commit-bridge 0.1.0

Seamless workflow dispatch for remote git dependencies.
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
//! Axum route handlers.

// Needed to bypass a warning raised inside the `#[rovo]` macro.
#![allow(missing_docs, clippy::missing_docs_in_private_items)]

use crate::error::HandlerError;
use crate::model::{
    CreateSubscription, HalLink, SubscriptionHal, SubscriptionLinks, SubscriptionPage,
    SubscriptionPageLinks, SubscriptionWithBranch, UpdateSubscription,
};
use crate::repository::subscription::SubscriptionRepository;

use crate::state::AppState;
use axum::{
    Json,
    extract::{Path, Query, State},
};
use rovo::rovo;
use serde::Deserialize;
use tracing::info;

/// Maps a [`SubscriptionWithBranch`] to its HAL representation.
fn map_to_hal(sub_with_branch: SubscriptionWithBranch) -> SubscriptionHal {
    let id = sub_with_branch.subscription.id;
    SubscriptionHal {
        subscription: sub_with_branch.subscription,
        source_branch: sub_with_branch.source_branch,
        links: SubscriptionLinks {
            self_link: HalLink {
                href: format!("/subscriptions/{}", id),
            },
            update: HalLink {
                href: format!("/subscriptions/{}", id),
            },
            delete: HalLink {
                href: format!("/subscriptions/{}", id),
            },
        },
    }
}

/// Create a new subscription mapping.
///
/// Creates a new subscription mapping between a source branch and a target repository.
///
/// # Responses
///
/// 201: Json<SubscriptionHal> - Subscription created successfully
/// 401: () - Unauthorized
/// 408: () - Request timeout
/// 422: () - Validation error
/// 500: () - Internal server error
///
/// # Metadata
///
/// @tag subscriptions
#[allow(rustdoc::invalid_html_tags)]
#[rovo]
pub async fn create_subscription(
    state: State<AppState>,
    payload: Json<CreateSubscription>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    create_subscription_inner(state, payload).await
}

/// Internal implementation of [`create_subscription`].
async fn create_subscription_inner(
    State(state): State<AppState>,
    Json(payload): Json<CreateSubscription>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    let sub_with_branch = state.repository.create(&payload).await?;

    info!(
        "Registered new subscription for branch ID {} (repo: {}, branch: {}): {:?}",
        sub_with_branch.subscription.branch_id,
        sub_with_branch.source_branch.repo_url,
        sub_with_branch.source_branch.name,
        sub_with_branch.subscription
    );

    Ok(Json(map_to_hal(sub_with_branch)))
}

/// Query parameters for listing subscriptions.
#[derive(Debug, Deserialize, rovo::schemars::JsonSchema)]
pub struct ListSubscriptionsQuery {
    /// Maximum number of subscriptions to return.
    pub limit: Option<usize>,
    /// The ID of the last subscription in the previous page.
    pub last_id: Option<i64>,
}

/// List subscriptions.
///
/// Returns a paginated list of all subscription mappings in the system.
///
/// # Query Parameters
///
/// - `limit`: The maximum number of subscriptions to return.
/// - `last_id`: The ID of the last subscription in the previous page.
///
/// # Responses
///
/// 200: Json<SubscriptionPage> - Paginated list of subscriptions
/// 401: () - Unauthorized
/// 408: () - Request timeout
/// 500: () - Internal server error
///
/// # Metadata
///
/// @tag subscriptions
#[allow(rustdoc::invalid_html_tags)]
#[rovo]
pub async fn list_subscriptions(
    state: State<AppState>,
    query: Query<ListSubscriptionsQuery>,
) -> Result<Json<SubscriptionPage>, HandlerError> {
    list_subscriptions_inner(state, query).await
}

/// Internal implementation of [`list_subscriptions`].
async fn list_subscriptions_inner(
    State(state): State<AppState>,
    Query(query): Query<ListSubscriptionsQuery>,
) -> Result<Json<SubscriptionPage>, HandlerError> {
    let limit = query
        .limit
        .unwrap_or(state.config.database.subscriptions_list_limit)
        .min(state.config.database.subscriptions_list_limit_cap);
    let last_id = query.last_id.unwrap_or_default();

    let subscriptions = state
        .repository
        .list_paginated_with_branches(last_id, limit as i64)
        .await?;

    let data: Vec<SubscriptionHal> = subscriptions.into_iter().map(map_to_hal).collect();

    let next_id = data.last().map(|s| s.subscription.id).unwrap_or(last_id);
    let remaining_count = state.repository.count_remaining(next_id).await?;

    let next_link = data
        .last()
        .filter(|_| remaining_count > 0)
        .map(|s| HalLink {
            href: format!(
                "/subscriptions?limit={}&last_id={}",
                limit, s.subscription.id
            ),
        });

    Ok(Json(SubscriptionPage {
        data,
        remaining_count,
        links: SubscriptionPageLinks { next: next_link },
    }))
}

/// Get a single subscription.
///
/// Retrieve a subscription mapping by its ID.
///
/// # Path Parameters
///
/// id: The unique identifier of the subscription
///
/// # Responses
///
/// 200: Json<SubscriptionHal> - Successfully retrieved the subscription
/// 401: () - Unauthorized
/// 404: () - Subscription was not found
/// 408: () - Request timeout
/// 500: () - Internal server error
///
/// # Metadata
///
/// @tag subscriptions
#[allow(rustdoc::invalid_html_tags)]
#[rovo]
pub async fn get_subscription(
    state: State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    get_subscription_inner(state, Path(id)).await
}

/// Internal implementation of [`get_subscription`].
async fn get_subscription_inner(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    let sub_with_branch = state
        .repository
        .get_by_id_with_branch(id)
        .await?
        .ok_or(HandlerError::NotFound)?;
    Ok(Json(map_to_hal(sub_with_branch)))
}

/// Update an existing subscription.
///
/// Updates the target repository, event type, and/or GitHub App installation ID of a subscription.
///
/// # Path Parameters
///
/// id: The unique identifier of the subscription to update
///
/// # Responses
///
/// 200: Json<SubscriptionHal> - Subscription updated successfully
/// 401: () - Unauthorized
/// 404: () - Subscription was not found
/// 408: () - Request timeout
/// 422: () - Validation error
/// 500: () - Internal server error
///
/// # Metadata
///
/// @tag subscriptions
#[allow(rustdoc::invalid_html_tags)]
#[rovo]
pub async fn update_subscription(
    state: State<AppState>,
    Path(id): Path<i64>,
    payload: Json<UpdateSubscription>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    update_subscription_inner(state, Path(id), payload).await
}

/// Internal implementation of [`update_subscription`].
async fn update_subscription_inner(
    State(state): State<AppState>,
    Path(id): Path<i64>,
    Json(payload): Json<UpdateSubscription>,
) -> Result<Json<SubscriptionHal>, HandlerError> {
    state.repository.update(id, &payload).await?;
    let sub_with_branch = state
        .repository
        .get_by_id_with_branch(id)
        .await?
        .ok_or(HandlerError::NotFound)?;

    Ok(Json(map_to_hal(sub_with_branch)))
}

/// Delete a subscription.
///
/// Permanently deletes a subscription mapping by its ID.
///
/// # Path Parameters
///
/// id: The unique identifier of the subscription to delete
///
/// # Responses
///
/// 204: () - Subscription deleted successfully
/// 401: () - Unauthorized
/// 404: () - Subscription was not found
/// 408: () - Request timeout
/// 500: () - Internal server error
///
/// # Metadata
///
/// @tag subscriptions
#[allow(rustdoc::invalid_html_tags)]
#[rovo]
pub async fn delete_subscription(
    state: State<AppState>,
    Path(id): Path<i64>,
) -> Result<(), HandlerError> {
    delete_subscription_inner(state, Path(id)).await
}

/// Internal implementation of [`delete_subscription`].
async fn delete_subscription_inner(
    State(state): State<AppState>,
    Path(id): Path<i64>,
) -> Result<(), HandlerError> {
    state.repository.delete_subscription_and_cascade(id).await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::panic,
        clippy::expect_used,
        clippy::todo,
        clippy::unimplemented,
        clippy::indexing_slicing
    )]

    use super::*;
    use crate::domain::{BranchName, EventType, RepoUrl, TargetRepo};
    use crate::model::CreateSubscription;
    use crate::state::AppState;
    use crate::test_utils::create_test_db;
    use axum::Json;
    use axum::extract::State;

    #[tokio::test]
    async fn test_crud_subscription() {
        let pool = create_test_db().await;
        let config = crate::test_utils::create_test_config();
        let state = AppState {
            config: std::sync::Arc::new(config),
            repository: std::sync::Arc::new(crate::repository::SqliteRepository::new(pool.clone())),
            db_pool: pool.clone(),
        };
        let payload = CreateSubscription {
            source_repo_url: RepoUrl::new("https://github.com/org/repo".to_string()).unwrap(),
            source_branch_name: BranchName::new("main".to_string()).unwrap(),
            target_repo: TargetRepo::new("org/target".to_string()).unwrap(),
            event_type: EventType::new("dispatch".to_string()).unwrap(),
            gh_app_installation_id: 1,
        };

        // Create
        let res = create_subscription_inner(State(state.clone()), Json(payload))
            .await
            .unwrap();
        let id = res.subscription.id;
        assert_eq!(res.links.self_link.href, format!("/subscriptions/{}", id));

        // List
        let list = list_subscriptions_inner(
            State(state.clone()),
            Query(ListSubscriptionsQuery {
                limit: None,
                last_id: None,
            }),
        )
        .await
        .unwrap();
        assert_eq!(list.data.len(), 1);
        assert_eq!(
            list.data[0].links.self_link.href,
            format!("/subscriptions/{}", id)
        );
        assert_eq!(list.remaining_count, 0);

        // Get
        let get = get_subscription_inner(State(state.clone()), Path(id))
            .await
            .unwrap();
        assert_eq!(get.subscription.id, id);
        assert_eq!(get.links.self_link.href, format!("/subscriptions/{}", id));

        // Update
        let update_payload = UpdateSubscription {
            target_repo: Some(TargetRepo::new("org/new-target".to_string()).unwrap()),
            event_type: None,
            gh_app_installation_id: None,
        };
        let updated =
            update_subscription_inner(State(state.clone()), Path(id), Json(update_payload))
                .await
                .unwrap();
        assert_eq!(
            updated.subscription.target_repo,
            TargetRepo::new("org/new-target".to_string()).unwrap()
        );

        assert_eq!(
            updated.links.self_link.href,
            format!("/subscriptions/{}", id)
        );

        // Delete
        delete_subscription_inner(State(state.clone()), Path(id))
            .await
            .unwrap();

        // Verify delete
        let get_after_delete = get_subscription_inner(State(state.clone()), Path(id)).await;
        assert!(get_after_delete.is_err());
    }

    #[tokio::test]
    async fn test_non_existent_subscription_returns_not_found() {
        let pool = create_test_db().await;
        let config = crate::test_utils::create_test_config();
        let state = AppState {
            config: std::sync::Arc::new(config),
            repository: std::sync::Arc::new(crate::repository::SqliteRepository::new(pool.clone())),
            db_pool: pool.clone(),
        };

        // Try getting a non-existent subscription
        let get_res = get_subscription_inner(State(state.clone()), Path(999)).await;
        assert!(matches!(get_res, Err(HandlerError::NotFound)));

        // Try updating a non-existent subscription
        let update_payload = UpdateSubscription {
            target_repo: Some(TargetRepo::new("org/new-target".to_string()).unwrap()),
            event_type: None,
            gh_app_installation_id: None,
        };
        let update_res =
            update_subscription_inner(State(state.clone()), Path(999), Json(update_payload)).await;
        assert!(matches!(update_res, Err(HandlerError::NotFound)));

        // Try deleting a non-existent subscription
        let delete_res = delete_subscription_inner(State(state.clone()), Path(999)).await;
        assert!(matches!(delete_res, Err(HandlerError::NotFound)));
    }

    #[tokio::test]
    async fn test_list_subscriptions_pagination() {
        let pool = create_test_db().await;
        let config = crate::test_utils::create_test_config();
        let state = AppState {
            config: std::sync::Arc::new(config),
            repository: std::sync::Arc::new(crate::repository::SqliteRepository::new(pool.clone())),
            db_pool: pool.clone(),
        };

        // Create 3 subscriptions
        //
        // Lint needs to be silenced here because the `#[tokio::test]` macro
        // probably interferes with the nesting count.
        #[allow(clippy::excessive_nesting)]
        for i in 0..3 {
            let payload = CreateSubscription {
                source_repo_url: RepoUrl::new(format!("https://github.com/org/repo{}", i)).unwrap(),
                source_branch_name: BranchName::new("main".to_string()).unwrap(),
                target_repo: TargetRepo::new("org/target".to_string()).unwrap(),
                event_type: EventType::new("dispatch".to_string()).unwrap(),
                gh_app_installation_id: 1,
            };
            let _ = create_subscription_inner(State(state.clone()), Json(payload))
                .await
                .unwrap();
        }

        // Fetch first page (limit 2)
        let page1 = list_subscriptions_inner(
            State(state.clone()),
            Query(ListSubscriptionsQuery {
                limit: Some(2),
                last_id: None,
            }),
        )
        .await
        .unwrap();
        assert_eq!(page1.data.len(), 2);
        assert_eq!(page1.remaining_count, 1);
        assert!(page1.links.next.is_some());

        // Fetch second page
        let last_id = page1.data.last().unwrap().subscription.id;
        let page2 = list_subscriptions_inner(
            State(state.clone()),
            Query(ListSubscriptionsQuery {
                limit: Some(2),
                last_id: Some(last_id),
            }),
        )
        .await
        .unwrap();
        assert_eq!(page2.data.len(), 1);
        assert_eq!(page2.remaining_count, 0);
        assert!(page2.links.next.is_none());
    }

    #[tokio::test]
    async fn test_cascading_branch_cleanup() {
        let pool = create_test_db().await;
        let config = crate::test_utils::create_test_config();
        let state = AppState {
            config: std::sync::Arc::new(config),
            repository: std::sync::Arc::new(crate::repository::SqliteRepository::new(pool.clone())),
            db_pool: pool.clone(),
        };
        let payload = CreateSubscription {
            source_repo_url: RepoUrl::new("https://github.com/org/repo".to_string()).unwrap(),
            source_branch_name: BranchName::new("main".to_string()).unwrap(),
            target_repo: TargetRepo::new("org/target".to_string()).unwrap(),
            event_type: EventType::new("dispatch".to_string()).unwrap(),
            gh_app_installation_id: 1,
        };

        // Create two subscriptions for the same branch
        let sub1 = create_subscription_inner(State(state.clone()), Json(payload.clone()))
            .await
            .unwrap();
        let sub2 = create_subscription_inner(State(state.clone()), Json(payload))
            .await
            .unwrap();

        let branch_id = sub1.subscription.branch_id;

        // Verify branch exists
        let branch: Option<(i64,)> = sqlx::query_as("SELECT id FROM branches WHERE id = ?")
            .bind(branch_id)
            .fetch_optional(&pool)
            .await
            .unwrap();
        assert!(branch.is_some());

        // Delete first subscription
        delete_subscription_inner(State(state.clone()), Path(sub1.subscription.id))
            .await
            .unwrap();

        // Branch should still exist
        let branch_still_exists: Option<(i64,)> =
            sqlx::query_as("SELECT id FROM branches WHERE id = ?")
                .bind(branch_id)
                .fetch_optional(&pool)
                .await
                .unwrap();
        assert!(branch_still_exists.is_some());

        // Delete second subscription
        delete_subscription_inner(State(state.clone()), Path(sub2.subscription.id))
            .await
            .unwrap();

        // Branch should be gone
        let branch_gone: Option<(i64,)> = sqlx::query_as("SELECT id FROM branches WHERE id = ?")
            .bind(branch_id)
            .fetch_optional(&pool)
            .await
            .unwrap();
        assert!(branch_gone.is_none());
    }
}