vibelang-http 0.3.0

HTTP REST API server for VibeLang
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
//! Melodies endpoint handlers.

use axum::{
    extract::{Path, State},
    http::StatusCode,
    Json,
};
use std::sync::Arc;
use vibelang_core::{
    traits::{MelodyConfig, NoteEvent},
    types::Beat,
    MelodyId, MelodyMessage, VoiceId,
};

use crate::{
    models::{
        ErrorResponse, LoopState, LoopStatus, Melody, MelodyCreate, MelodyEvent, MelodyUpdate,
        StartRequest, StopRequest,
    },
    AppState,
};

/// Resolve a melody identifier (either numeric ID or string name) to a MelodyId.
async fn resolve_melody_id(
    state: &Arc<AppState>,
    identifier: &str,
) -> Result<MelodyId, (StatusCode, Json<ErrorResponse>)> {
    // First, try to parse as a numeric ID
    if let Ok(num_id) = identifier.parse::<u32>() {
        let melody_id = MelodyId::new(num_id);
        let exists = state
            .with_state(|s| s.melodies.contains_key(&melody_id))
            .await;
        if exists {
            return Ok(melody_id);
        }
        // Fall through to try as name if numeric ID not found
    }

    // Try to find by name
    let found = state
        .with_state(|s| {
            s.melodies
                .iter()
                .find(|(_, ms)| ms.config.name == identifier)
                .map(|(id, _)| *id)
        })
        .await;

    match found {
        Some(id) => Ok(id),
        None => Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse::not_found(&format!(
                "Melody '{}' not found",
                identifier
            ))),
        )),
    }
}

/// Convert internal MelodyState to API Melody model
fn melody_to_api(
    _id: &MelodyId,
    state: &vibelang_core::MelodyState,
    voices: &std::collections::HashMap<vibelang_core::VoiceId, vibelang_core::VoiceState>,
) -> Melody {
    // Use the actual name from config
    let name = state.config.name.clone();
    // Get voice name from voice state
    let voice_name = state
        .config
        .voice
        .and_then(|vid| voices.get(&vid))
        .map(|vs| vs.config.name.clone())
        .unwrap_or_default();

    // Get group path from the voice if available
    let group_path = state
        .config
        .voice
        .and_then(|vid| voices.get(&vid))
        .map(|vs| vs.config.group.raw().to_string())
        .unwrap_or_else(|| "0".to_string());

    // Convert playing state to LoopStatus
    let status = LoopStatus {
        state: if state.playing {
            LoopState::Playing
        } else {
            LoopState::Stopped
        },
        start_beat: None,
        stop_beat: None,
    };

    Melody {
        name,
        voice_name,
        group_path,
        loop_beats: state.config.length.to_f64(),
        events: state
            .config
            .notes
            .iter()
            .map(|n| MelodyEvent {
                beat: n.beat.to_f64(),
                note: format!("{}", n.note), // MIDI note number as string
                frequency: None,             // Could calculate from note if needed
                duration: Some(n.duration.to_f64()),
                velocity: Some(n.velocity),
                params: None,
            })
            .collect(),
        params: None,
        status,
        is_looping: true, // Melodies are always looping
        source_location: None,
        notes_patterns: None,
    }
}

/// GET /melodies - List all melodies
pub async fn list_melodies(State(state): State<Arc<AppState>>) -> Json<Vec<Melody>> {
    let melodies = state
        .with_state(|s| {
            s.melodies
                .iter()
                .map(|(id, ms)| melody_to_api(id, ms, &s.voices))
                .collect::<Vec<_>>()
        })
        .await;

    Json(melodies)
}

/// GET /melodies/:id - Get melody by ID or name
pub async fn get_melody(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<Json<Melody>, (StatusCode, Json<ErrorResponse>)> {
    let melody_id = resolve_melody_id(&state, &id).await?;

    let melody = state
        .with_state(|s| {
            s.melodies
                .get(&melody_id)
                .map(|ms| melody_to_api(&melody_id, ms, &s.voices))
        })
        .await;

    match melody {
        Some(m) => Ok(Json(m)),
        None => Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse::not_found(&format!(
                "Melody '{}' not found",
                id
            ))),
        )),
    }
}

/// PATCH /melodies/:id - Update melody by ID or name
///
/// Note: Melody updates (`events` and `loop_beats`) are not supported via API
/// and require script reload. This endpoint currently returns the current state.
pub async fn update_melody(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(update): Json<MelodyUpdate>,
) -> Result<Json<Melody>, (StatusCode, Json<ErrorResponse>)> {
    let _melody_id = resolve_melody_id(&state, &id).await?;

    // Note: events and loop_beats updates require script reload
    if update.events.is_some() || update.loop_beats.is_some() {
        tracing::warn!(
            "Melody {} update requested events or loop_beats change, which requires script reload",
            id
        );
    }

    get_melody(State(state), Path(id)).await
}

/// POST /melodies/:id/start - Start a melody by ID or name
pub async fn start_melody(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(_req): Json<Option<StartRequest>>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let melody_id = resolve_melody_id(&state, &id).await?;

    if let Err(e) = state
        .send(MelodyMessage::Start { id: melody_id }.into())
        .await
    {
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal(&format!(
                "Failed to start melody: {}",
                e
            ))),
        ));
    }

    Ok(StatusCode::OK)
}

/// POST /melodies/:id/stop - Stop a melody by ID or name
pub async fn stop_melody(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Json(_req): Json<Option<StopRequest>>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let melody_id = resolve_melody_id(&state, &id).await?;

    if let Err(e) = state
        .send(MelodyMessage::Stop { id: melody_id }.into())
        .await
    {
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal(&format!(
                "Failed to stop melody: {}",
                e
            ))),
        ));
    }

    Ok(StatusCode::OK)
}

/// Parse a note string to MIDI note number.
/// Supports formats like "C4", "60", "C#4", "Db4".
fn parse_note(note: &str) -> u8 {
    // Try parsing as number first
    if let Ok(n) = note.parse::<u8>() {
        return n;
    }

    // Parse note name
    let note_upper = note.to_uppercase();
    let mut chars = note_upper.chars().peekable();

    let base = match chars.next() {
        Some('C') => 0,
        Some('D') => 2,
        Some('E') => 4,
        Some('F') => 5,
        Some('G') => 7,
        Some('A') => 9,
        Some('B') => 11,
        _ => return 60, // Default to middle C
    };

    let mut offset = 0i8;
    while let Some(&c) = chars.peek() {
        match c {
            '#' => {
                offset += 1;
                chars.next();
            }
            'B' if chars.clone().count() > 1 => {
                offset -= 1;
                chars.next();
            } // 'b' for flat
            _ => break,
        }
    }

    // Parse octave
    let octave: i8 = chars.collect::<String>().parse().unwrap_or(4);

    ((octave + 1) * 12 + base as i8 + offset).clamp(0, 127) as u8
}

/// POST /melodies - Create a new melody
pub async fn create_melody(
    State(state): State<Arc<AppState>>,
    Json(req): Json<MelodyCreate>,
) -> Result<(StatusCode, Json<Melody>), (StatusCode, Json<ErrorResponse>)> {
    // Find voice by name
    let voice_id = state
        .with_state(|s| {
            s.voices
                .iter()
                .find(|(_, v)| v.config.name == req.voice_name)
                .map(|(id, _)| *id)
        })
        .await;

    let voice_id = match voice_id {
        Some(id) => id,
        None => {
            // Try parsing as numeric ID
            match req.voice_name.parse::<u32>() {
                Ok(n) => VoiceId::new(n),
                Err(_) => {
                    return Err((
                        StatusCode::BAD_REQUEST,
                        Json(ErrorResponse::bad_request(&format!(
                            "Voice '{}' not found",
                            req.voice_name
                        ))),
                    ));
                }
            }
        }
    };

    // Generate melody ID from name hash
    let melody_id = state
        .with_state(|s| {
            let id = req
                .name
                .bytes()
                .fold(1u32, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u32));
            let mut id = id % 10000 + 1;
            while s.melodies.contains_key(&MelodyId::new(id)) {
                id += 1;
            }
            MelodyId::new(id)
        })
        .await;

    // Convert events to NoteEvents
    let notes: Vec<NoteEvent> = req
        .events
        .iter()
        .map(|e| {
            NoteEvent::new(
                e.beat,
                parse_note(&e.note),
                e.velocity.unwrap_or(0.8),
                e.duration.unwrap_or(1.0),
            )
        })
        .collect();

    let config = MelodyConfig {
        name: req.name.clone(),
        voice: Some(voice_id),
        notes,
        length: Beat::from_f64(req.loop_beats),
        swing: 0.0,
    };

    if let Err(e) = state
        .send(
            MelodyMessage::Create {
                id: melody_id,
                config,
            }
            .into(),
        )
        .await
    {
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal(&format!(
                "Failed to create melody: {}",
                e
            ))),
        ));
    }

    // Return the created melody
    let melody = state
        .with_state(|s| {
            s.melodies
                .get(&melody_id)
                .map(|ms| melody_to_api(&melody_id, ms, &s.voices))
        })
        .await;

    match melody {
        Some(m) => Ok((StatusCode::CREATED, Json(m))),
        None => Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal(
                "Melody created but not found in state",
            )),
        )),
    }
}

/// DELETE /melodies/:id - Delete a melody by ID or name
pub async fn delete_melody(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
) -> Result<StatusCode, (StatusCode, Json<ErrorResponse>)> {
    let melody_id = resolve_melody_id(&state, &id).await?;

    if let Err(e) = state
        .send(MelodyMessage::Delete { id: melody_id }.into())
        .await
    {
        return Err((
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal(&format!(
                "Failed to delete melody: {}",
                e
            ))),
        ));
    }

    Ok(StatusCode::NO_CONTENT)
}