rise-deploy 0.16.4

A simple and powerful CLI for deploying containerized applications
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
use super::models::*;
use crate::db::models::User;
use crate::db::{extensions as db_extensions, projects};
use crate::server::state::AppState;
use axum::{
    extract::{Extension as AxumExtension, Path, State},
    http::StatusCode,
    Json,
};

/// List all available extension types (registered providers)
pub async fn list_extension_types(
    State(state): State<AppState>,
    AxumExtension(_user): AxumExtension<User>,
) -> Result<Json<ListExtensionTypesResponse>, (StatusCode, String)> {
    // Note: This endpoint doesn't require project access - it lists all available
    // extension types that any authenticated user can see and potentially enable on their projects

    let extension_types: Vec<ExtensionTypeMetadata> = state
        .extension_registry
        .iter()
        .map(|(_registry_key, extension)| ExtensionTypeMetadata {
            extension_type: extension.extension_type().to_string(),
            display_name: extension.display_name().to_string(),
            description: extension.description().to_string(),
            documentation: extension.documentation().to_string(),
            spec_schema: extension.spec_schema(),
        })
        .collect();

    Ok(Json(ListExtensionTypesResponse { extension_types }))
}

/// Create or upsert extension for project
pub async fn create_extension(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path((project_name, extension_name)): Path<(String, String)>,
    Json(payload): Json<CreateExtensionRequest>,
) -> Result<Json<CreateExtensionResponse>, (StatusCode, String)> {
    // Get project and verify access
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    // Check project ownership/access
    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    // Get extension handler by type
    let extension = state
        .extension_registry
        .get(&payload.extension_type)
        .ok_or((
            StatusCode::BAD_REQUEST,
            format!("Unknown extension type: {}", payload.extension_type),
        ))?;

    // Validate spec
    extension
        .validate_spec(&payload.spec)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid spec: {}", e)))?;

    // Create extension (will fail if already exists)
    let _ext_record = db_extensions::create(
        &state.db_pool,
        project.id,
        &extension_name,
        &payload.extension_type,
        &payload.spec,
    )
    .await
    .map_err(|e| {
        // Check if it's a unique constraint violation
        let error_msg = e.to_string();
        if error_msg.contains("duplicate key") || error_msg.contains("unique constraint") {
            (
                StatusCode::CONFLICT,
                format!("Extension '{}' already exists", extension_name),
            )
        } else {
            (StatusCode::INTERNAL_SERVER_ERROR, error_msg)
        }
    })?;

    // Call extension's spec update hook (with empty old_spec for new extensions)
    extension
        .on_spec_updated(
            &serde_json::json!({}),
            &payload.spec,
            project.id,
            &extension_name,
            &state.db_pool,
        )
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Fetch updated extension to get the latest status (may have been initialized by on_spec_updated)
    let ext_record =
        db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
            .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Format status using the extension provider
    let status_summary = extension.format_status(&ext_record.status);

    Ok(Json(CreateExtensionResponse {
        extension: Extension {
            extension: ext_record.extension,
            extension_type: extension.extension_type().to_string(),
            spec: ext_record.spec,
            status: ext_record.status,
            status_summary,
            created: ext_record.created_at.to_rfc3339(),
            updated: ext_record.updated_at.to_rfc3339(),
        },
    }))
}

/// Update extension (PUT for full replace, PATCH for partial update)
pub async fn update_extension(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path((project_name, extension_name)): Path<(String, String)>,
    Json(payload): Json<UpdateExtensionRequest>,
) -> Result<Json<UpdateExtensionResponse>, (StatusCode, String)> {
    // Get project and verify access
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    // Check project ownership/access
    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    // Get existing extension to determine its type
    let existing =
        db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
            .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Get extension handler by type
    let extension = state
        .extension_registry
        .get(&existing.extension_type)
        .ok_or((
            StatusCode::BAD_REQUEST,
            format!("Unknown extension type: {}", existing.extension_type),
        ))?;

    // Validate new spec
    extension
        .validate_spec(&payload.spec)
        .await
        .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid spec: {}", e)))?;

    // Update extension (upsert will update existing, keeping the extension_type)
    let _ext_record = db_extensions::upsert(
        &state.db_pool,
        project.id,
        &extension_name,
        &existing.extension_type,
        &payload.spec,
    )
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Call extension's spec update hook
    extension
        .on_spec_updated(
            &existing.spec,
            &payload.spec,
            project.id,
            &extension_name,
            &state.db_pool,
        )
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Fetch updated extension to get the latest status (may have been modified by on_spec_updated)
    let ext_record =
        db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
            .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Format status using the extension provider
    let status_summary = extension.format_status(&ext_record.status);

    Ok(Json(UpdateExtensionResponse {
        extension: Extension {
            extension: ext_record.extension,
            extension_type: extension.extension_type().to_string(),
            spec: ext_record.spec,
            status: ext_record.status,
            status_summary,
            created: ext_record.created_at.to_rfc3339(),
            updated: ext_record.updated_at.to_rfc3339(),
        },
    }))
}

/// Patch extension (merge with nulls removing fields)
pub async fn patch_extension(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path((project_name, extension_name)): Path<(String, String)>,
    Json(payload): Json<UpdateExtensionRequest>,
) -> Result<Json<UpdateExtensionResponse>, (StatusCode, String)> {
    // Get project and verify access
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    // Check project ownership/access
    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    // Get existing extension
    let existing =
        db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
            .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Merge specs (null values in payload remove fields from existing)
    let merged_spec = merge_json_with_nulls(&existing.spec, &payload.spec);

    // Get extension handler by type
    let extension = state
        .extension_registry
        .get(&existing.extension_type)
        .ok_or((
            StatusCode::BAD_REQUEST,
            format!("Unknown extension type: {}", existing.extension_type),
        ))?;

    // Validate merged spec
    extension.validate_spec(&merged_spec).await.map_err(|e| {
        (
            StatusCode::BAD_REQUEST,
            format!("Invalid spec after merge: {}", e),
        )
    })?;

    // Update extension with merged spec
    let _ext_record = db_extensions::upsert(
        &state.db_pool,
        project.id,
        &extension_name,
        &existing.extension_type,
        &merged_spec,
    )
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Call extension's spec update hook
    extension
        .on_spec_updated(
            &existing.spec,
            &merged_spec,
            project.id,
            &extension_name,
            &state.db_pool,
        )
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // Fetch updated extension to get the latest status (may have been modified by on_spec_updated)
    let ext_record =
        db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
            .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Format status using the extension provider
    let status_summary = extension.format_status(&ext_record.status);

    Ok(Json(UpdateExtensionResponse {
        extension: Extension {
            extension: ext_record.extension,
            extension_type: extension.extension_type().to_string(),
            spec: ext_record.spec,
            status: ext_record.status,
            status_summary,
            created: ext_record.created_at.to_rfc3339(),
            updated: ext_record.updated_at.to_rfc3339(),
        },
    }))
}

/// List extensions for project
pub async fn list_extensions(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path(project_name): Path<String>,
) -> Result<Json<ListExtensionsResponse>, (StatusCode, String)> {
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    let extensions = db_extensions::list_by_project(&state.db_pool, project.id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let extensions: Vec<Extension> = extensions
        .into_iter()
        .map(|e| {
            // Get extension provider by type to format status
            let status_summary = state
                .extension_registry
                .get(&e.extension_type)
                .map(|ext| ext.format_status(&e.status))
                .unwrap_or_else(|| "Unknown".to_string());

            Extension {
                extension: e.extension,
                extension_type: e.extension_type,
                spec: e.spec,
                status: e.status,
                status_summary,
                created: e.created_at.to_rfc3339(),
                updated: e.updated_at.to_rfc3339(),
            }
        })
        .collect();

    Ok(Json(ListExtensionsResponse { extensions }))
}

/// Get extension by name
pub async fn get_extension(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path((project_name, extension_name)): Path<(String, String)>,
) -> Result<Json<Extension>, (StatusCode, String)> {
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    let ext = db_extensions::find_by_project_and_name(&state.db_pool, project.id, &extension_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Extension not found".to_string()))?;

    // Get extension provider by type to format status
    let status_summary = state
        .extension_registry
        .get(&ext.extension_type)
        .map(|ext_provider| ext_provider.format_status(&ext.status))
        .unwrap_or_else(|| "Unknown".to_string());

    Ok(Json(Extension {
        extension: ext.extension,
        extension_type: ext.extension_type,
        spec: ext.spec,
        status: ext.status,
        status_summary,
        created: ext.created_at.to_rfc3339(),
        updated: ext.updated_at.to_rfc3339(),
    }))
}

/// Delete extension (mark for deletion)
pub async fn delete_extension(
    State(state): State<AppState>,
    AxumExtension(user): AxumExtension<User>,
    Path((project_name, extension_name)): Path<(String, String)>,
) -> Result<StatusCode, (StatusCode, String)> {
    let project = projects::find_by_name(&state.db_pool, &project_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
        .ok_or((StatusCode::NOT_FOUND, "Project not found".to_string()))?;

    let has_access = check_project_access(&state, &user, project.id).await?;
    if !has_access {
        return Err((StatusCode::FORBIDDEN, "Access denied".to_string()));
    }

    db_extensions::mark_deleted(&state.db_pool, project.id, &extension_name)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    Ok(StatusCode::NO_CONTENT)
}

/// Helper to check if user has access to project
async fn check_project_access(
    state: &AppState,
    user: &User,
    project_id: uuid::Uuid,
) -> Result<bool, (StatusCode, String)> {
    // Check if user is admin
    if state.is_admin(&user.email) {
        return Ok(true);
    }

    // Check if user has access to project (owner or team member)
    let accessible_projects = projects::list_accessible_by_user(&state.db_pool, user.id)
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    Ok(accessible_projects.iter().any(|p| p.id == project_id))
}

/// Merge JSON values, treating null in update as field deletion
fn merge_json_with_nulls(
    existing: &serde_json::Value,
    update: &serde_json::Value,
) -> serde_json::Value {
    use serde_json::Value;

    match (existing, update) {
        (Value::Object(existing_map), Value::Object(update_map)) => {
            let mut result = existing_map.clone();
            for (key, value) in update_map.iter() {
                if value.is_null() {
                    // Null means remove the field
                    result.remove(key);
                } else if let Some(existing_value) = existing_map.get(key) {
                    // Recursively merge nested objects
                    result.insert(key.clone(), merge_json_with_nulls(existing_value, value));
                } else {
                    // New field
                    result.insert(key.clone(), value.clone());
                }
            }
            Value::Object(result)
        }
        _ => {
            // For non-objects, just replace with update value
            update.clone()
        }
    }
}