reasonkit-web 0.1.7

High-performance MCP server for browser automation, web capture, and content extraction. Rust-powered CDP client for AI agents.
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
//! # Database-Backed Settings Handlers
//!
//! Settings storage and synchronization with PostgreSQL backend.
//! Requires `portal` feature flag.

#[cfg(feature = "portal")]
use axum::{
    extract::{Json, Path, State},
    http::StatusCode,
    response::IntoResponse,
};

#[cfg(feature = "portal")]
use serde::{Deserialize, Serialize};

#[cfg(feature = "portal")]
use uuid::Uuid;

#[cfg(feature = "portal")]
use crate::portal::auth_db::PortalState;
#[cfg(feature = "portal")]
use crate::portal::db::{queries::SettingsRepository, DbError};
#[cfg(feature = "portal")]
use crate::portal::middleware::AuthClaims;

/// Settings response
#[cfg(feature = "portal")]
#[derive(Debug, Serialize)]
pub struct SettingsResponse {
    pub settings: Vec<SettingItem>,
    pub version: i32,
}

/// Individual setting item
#[cfg(feature = "portal")]
#[derive(Debug, Serialize)]
pub struct SettingItem {
    pub key: String,
    pub value: serde_json::Value,
    pub version: i32,
    pub updated_at: String,
}

/// Update settings request
#[cfg(feature = "portal")]
#[derive(Debug, Deserialize)]
pub struct UpdateSettingsRequest {
    pub settings: Vec<SettingUpdate>,
}

/// Individual setting update
#[cfg(feature = "portal")]
#[derive(Debug, Deserialize)]
pub struct SettingUpdate {
    pub key: String,
    pub value: serde_json::Value,
}

/// Sync request
#[cfg(feature = "portal")]
#[derive(Debug, Deserialize)]
pub struct SyncRequest {
    pub since_version: Option<i32>,
    pub changes: Option<Vec<SettingUpdate>>,
}

/// Sync response
#[cfg(feature = "portal")]
#[derive(Debug, Serialize)]
pub struct SyncResponse {
    pub success: bool,
    pub server_changes: Vec<SettingItem>,
    pub conflicts: Vec<ConflictItem>,
    pub current_version: i32,
}

/// Conflict item for sync
#[cfg(feature = "portal")]
#[derive(Debug, Serialize)]
pub struct ConflictItem {
    pub key: String,
    pub client_value: serde_json::Value,
    pub server_value: serde_json::Value,
    pub server_version: i32,
}

/// Get all settings for current user
#[cfg(feature = "portal")]
pub async fn get_settings(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    let settings_repo = SettingsRepository::new(state.db.pool());

    match settings_repo.get_all(user_id).await {
        Ok(settings) => {
            let max_version = settings.iter().map(|s| s.version).max().unwrap_or(0);
            let items: Vec<SettingItem> = settings
                .into_iter()
                .map(|s| SettingItem {
                    key: s.key,
                    value: s.value,
                    version: s.version,
                    updated_at: s.updated_at.to_rfc3339(),
                })
                .collect();

            (
                StatusCode::OK,
                Json(serde_json::json!({
                    "settings": items,
                    "version": max_version
                })),
            )
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "Failed to fetch settings"})),
            )
        }
    }
}

/// Get a specific setting
#[cfg(feature = "portal")]
pub async fn get_setting(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
    Path(key): Path<String>,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    let settings_repo = SettingsRepository::new(state.db.pool());

    match settings_repo.get(user_id, &key).await {
        Ok(setting) => (
            StatusCode::OK,
            Json(serde_json::json!({
                "key": setting.key,
                "value": setting.value,
                "version": setting.version,
                "updated_at": setting.updated_at.to_rfc3339()
            })),
        ),
        Err(DbError::NotFound) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({"error": "Setting not found"})),
        ),
        Err(e) => {
            tracing::error!("Database error: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "Failed to fetch setting"})),
            )
        }
    }
}

/// Update settings (batch)
#[cfg(feature = "portal")]
pub async fn update_settings(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
    Json(req): Json<UpdateSettingsRequest>,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    let settings_repo = SettingsRepository::new(state.db.pool());
    let mut updated = Vec::new();
    let mut errors = Vec::new();

    for setting in req.settings {
        // Validate key format
        if setting.key.is_empty() || setting.key.len() > 255 {
            errors.push(format!("Invalid key: {}", setting.key));
            continue;
        }

        match settings_repo
            .set(user_id, &setting.key, setting.value.clone())
            .await
        {
            Ok(s) => {
                updated.push(SettingItem {
                    key: s.key,
                    value: s.value,
                    version: s.version,
                    updated_at: s.updated_at.to_rfc3339(),
                });
            }
            Err(e) => {
                tracing::error!("Failed to update setting {}: {}", setting.key, e);
                errors.push(format!("Failed to update: {}", setting.key));
            }
        }
    }

    let max_version = updated.iter().map(|s| s.version).max().unwrap_or(0);

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "success": errors.is_empty(),
            "updated": updated,
            "errors": errors,
            "version": max_version
        })),
    )
}

/// Set a specific setting
#[cfg(feature = "portal")]
pub async fn set_setting(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
    Path(key): Path<String>,
    Json(value): Json<serde_json::Value>,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    // Validate key
    if key.is_empty() || key.len() > 255 {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({"error": "Invalid key format"})),
        );
    }

    let settings_repo = SettingsRepository::new(state.db.pool());

    match settings_repo.set(user_id, &key, value).await {
        Ok(setting) => {
            tracing::info!("Setting {} updated for user {}", key, user_id);
            (
                StatusCode::OK,
                Json(serde_json::json!({
                    "success": true,
                    "key": setting.key,
                    "value": setting.value,
                    "version": setting.version,
                    "updated_at": setting.updated_at.to_rfc3339()
                })),
            )
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "Failed to update setting"})),
            )
        }
    }
}

/// Delete a setting
#[cfg(feature = "portal")]
pub async fn delete_setting(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
    Path(key): Path<String>,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    let settings_repo = SettingsRepository::new(state.db.pool());

    match settings_repo.delete(user_id, &key).await {
        Ok(()) => {
            tracing::info!("Setting {} deleted for user {}", key, user_id);
            (
                StatusCode::OK,
                Json(serde_json::json!({
                    "success": true,
                    "deleted": key
                })),
            )
        }
        Err(e) => {
            tracing::error!("Database error: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({"error": "Failed to delete setting"})),
            )
        }
    }
}

/// Sync settings (bidirectional)
#[cfg(feature = "portal")]
pub async fn sync_settings(
    State(state): State<PortalState>,
    AuthClaims(claims): AuthClaims,
    Json(req): Json<SyncRequest>,
) -> impl IntoResponse {
    let user_id = match Uuid::parse_str(&claims.sub) {
        Ok(id) => id,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({"error": "Invalid user ID"})),
            );
        }
    };

    let settings_repo = SettingsRepository::new(state.db.pool());
    let mut conflicts = Vec::new();
    let mut applied = Vec::new();

    // Apply client changes if any
    if let Some(changes) = req.changes {
        for change in changes {
            // Check for conflicts
            if let Ok(existing) = settings_repo.get(user_id, &change.key).await {
                let since = req.since_version.unwrap_or(0);
                if existing.version > since {
                    // Conflict: server has newer version
                    conflicts.push(ConflictItem {
                        key: change.key.clone(),
                        client_value: change.value.clone(),
                        server_value: existing.value,
                        server_version: existing.version,
                    });
                    continue;
                }
            }

            // No conflict, apply change
            if let Ok(s) = settings_repo.set(user_id, &change.key, change.value).await {
                applied.push(s.key);
            }
        }
    }

    // Get server changes since client version
    let since_version = req.since_version.unwrap_or(0);
    let server_changes = match settings_repo
        .get_changes_since(user_id, since_version)
        .await
    {
        Ok(changes) => changes
            .into_iter()
            .filter(|s| !applied.contains(&s.key))
            .map(|s| SettingItem {
                key: s.key,
                value: s.value,
                version: s.version,
                updated_at: s.updated_at.to_rfc3339(),
            })
            .collect(),
        Err(e) => {
            tracing::error!("Database error: {}", e);
            Vec::new()
        }
    };

    // Get current max version
    let current_version = match settings_repo.get_all(user_id).await {
        Ok(all) => all.iter().map(|s| s.version).max().unwrap_or(0),
        Err(_) => 0,
    };

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "success": conflicts.is_empty(),
            "server_changes": server_changes,
            "conflicts": conflicts,
            "current_version": current_version,
            "applied_count": applied.len()
        })),
    )
}