server-less 0.6.0

Composable derive macros for common Rust patterns
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
//! Tests for the standalone #[openapi] macro.

#![allow(dead_code)]

use server_less::openapi;

// ============================================================================
// Standalone Mode Tests (no sibling protocols)
// ============================================================================

#[derive(Clone)]
struct StandaloneService;

#[openapi(prefix = "/api")]
impl StandaloneService {
    /// Get status
    pub fn get_status(&self) -> String {
        "ok".to_string()
    }

    /// List items
    pub fn list_items(&self) -> Vec<String> {
        vec![]
    }

    /// Create item
    pub fn create_item(&self, name: String) -> String {
        name
    }
}

#[test]
fn test_openapi_standalone_generates_spec() {
    let spec = StandaloneService::openapi_spec();

    assert_eq!(spec["openapi"], "3.0.0");
    assert_eq!(spec["info"]["title"], "StandaloneService");
}

#[test]
fn test_openapi_standalone_has_paths() {
    let spec = StandaloneService::openapi_spec();
    let paths = &spec["paths"];

    // Should have paths derived from method conventions
    assert!(paths.is_object(), "Should have paths object");

    // get_status -> GET /api/status
    assert!(
        paths["/api/status"]["get"].is_object(),
        "Should have GET /api/status. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );

    // list_items -> GET /api/items
    assert!(
        paths["/api/items"]["get"].is_object(),
        "Should have GET /api/items"
    );

    // create_item -> POST /api/item (or /api/items depending on convention)
    assert!(
        paths["/api/item"]["post"].is_object() || paths["/api/items"]["post"].is_object(),
        "Should have POST /api/item or /api/items. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

// ============================================================================
// Protocol-Aware Mode Tests (with sibling protocols)
// ============================================================================

use server_less::{http, jsonrpc};

#[derive(Clone)]
struct ProtocolAwareService;

// NOTE: #[openapi] must come FIRST to detect sibling protocol attributes
#[openapi]
#[http(prefix = "/api", openapi = false)]
#[jsonrpc(path = "/rpc")]
impl ProtocolAwareService {
    /// Get status via HTTP
    pub fn get_status(&self) -> String {
        "ok".to_string()
    }

    /// Add numbers via JSON-RPC
    pub fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

#[test]
fn test_openapi_protocol_aware_detects_http() {
    let spec = ProtocolAwareService::openapi_spec();
    let paths = &spec["paths"];

    // Should have HTTP paths from #[http]
    assert!(
        paths["/api/status"]["get"].is_object(),
        "Should have HTTP endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

#[test]
fn test_openapi_protocol_aware_detects_jsonrpc() {
    let spec = ProtocolAwareService::openapi_spec();
    let paths = &spec["paths"];

    // Should have JSON-RPC path from #[jsonrpc]
    assert!(
        paths["/rpc"]["post"].is_object(),
        "Should have JSON-RPC endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

#[test]
fn test_openapi_protocol_aware_combined_spec() {
    let spec = ProtocolAwareService::openapi_spec();

    assert_eq!(spec["openapi"], "3.0.0");
    assert_eq!(spec["info"]["title"], "ProtocolAwareService");

    let paths = &spec["paths"];

    // Count total endpoints - should have both HTTP and JSON-RPC
    let path_count = paths.as_object().map(|o| o.len()).unwrap_or(0);
    assert!(
        path_count >= 2,
        "Should have at least 2 paths (HTTP + JSON-RPC). Got: {}",
        path_count
    );
}

// Test with WebSocket
use server_less::ws;

#[derive(Clone)]
struct HttpWsService;

#[openapi]
#[http(prefix = "/api", openapi = false)]
#[ws(path = "/ws")]
impl HttpWsService {
    pub fn get_info(&self) -> String {
        "info".to_string()
    }

    pub fn echo(&self, msg: String) -> String {
        msg
    }
}

#[test]
fn test_openapi_protocol_aware_with_ws() {
    let spec = HttpWsService::openapi_spec();
    let paths = &spec["paths"];

    // Should have HTTP path (get_info -> GET /api/infos)
    assert!(
        paths["/api/infos"]["get"].is_object(),
        "Should have HTTP endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );

    // Should have WebSocket path
    assert!(
        paths["/ws"]["get"].is_object(),
        "Should have WebSocket endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

// Test with GraphQL
use server_less::graphql;

#[derive(Clone)]
struct HttpGraphqlService;

#[openapi]
#[http(prefix = "/api", openapi = false)]
#[graphql]
impl HttpGraphqlService {
    pub fn get_status(&self) -> String {
        "ok".to_string()
    }
}

#[test]
fn test_openapi_protocol_aware_with_graphql() {
    let spec = HttpGraphqlService::openapi_spec();
    let paths = &spec["paths"];

    // Should have HTTP path
    assert!(
        paths["/api/status"]["get"].is_object(),
        "Should have HTTP endpoint"
    );

    // Should have GraphQL paths
    assert!(
        paths["/graphql"]["post"].is_object(),
        "Should have GraphQL POST endpoint. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

// Test HTTP-only with openapi (should still detect)
#[derive(Clone)]
struct HttpOnlyWithOpenapi;

#[openapi]
#[http(openapi = false)]
impl HttpOnlyWithOpenapi {
    pub fn list_things(&self) -> Vec<String> {
        vec![]
    }
}

#[test]
fn test_openapi_detects_single_protocol() {
    let spec = HttpOnlyWithOpenapi::openapi_spec();
    let paths = &spec["paths"];

    assert!(
        paths["/things"]["get"].is_object(),
        "Should have HTTP endpoint from detected #[http]. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

// ============================================================================
// Enhanced Attributes Tests (tags, deprecated, description)
// ============================================================================

#[allow(unused_imports)]
use server_less::response;
#[allow(unused_imports)]
use server_less::route;

#[derive(Clone)]
struct EnhancedAttrsService;

#[openapi(prefix = "/api")]
impl EnhancedAttrsService {
    /// Get user by ID
    ///
    /// Fetch a user by their unique ID from the database.
    /// Returns the user's data as a JSON string.
    #[route(tags = "users,public")]
    pub fn get_user(&self, id: String) -> String {
        id
    }

    /// Create user (deprecated)
    #[route(tags = "users", deprecated)]
    #[response(description = "User created successfully")]
    pub fn create_user(&self, name: String) -> String {
        name
    }

    /// Hidden endpoint
    #[route(hidden)]
    pub fn internal_method(&self) -> String {
        "secret".to_string()
    }
}

#[test]
fn test_openapi_tags_attribute() {
    let spec = EnhancedAttrsService::openapi_spec();
    let paths = &spec["paths"];

    let get_user = &paths["/api/users/{id}"]["get"];
    assert!(get_user.is_object(), "Should have get_user endpoint");

    let tags = get_user["tags"].as_array();
    assert!(tags.is_some(), "Should have tags array");
    let tags = tags.unwrap();
    assert!(
        tags.iter().any(|t| t.as_str() == Some("users")),
        "Should have 'users' tag. Tags: {:?}",
        tags
    );
    assert!(
        tags.iter().any(|t| t.as_str() == Some("public")),
        "Should have 'public' tag. Tags: {:?}",
        tags
    );
}

#[test]
fn test_openapi_deprecated_attribute() {
    let spec = EnhancedAttrsService::openapi_spec();
    let paths = &spec["paths"];

    let create_user = &paths["/api/users"]["post"];
    assert!(create_user.is_object(), "Should have create_user endpoint");

    assert_eq!(
        create_user["deprecated"], true,
        "Should be marked as deprecated"
    );
}

#[test]
fn test_openapi_description_from_doc_comment() {
    let spec = EnhancedAttrsService::openapi_spec();
    let paths = &spec["paths"];

    let get_user = &paths["/api/users/{id}"]["get"];
    assert!(get_user.is_object(), "Should have get_user endpoint");

    // Summary should be the first line of the doc comment
    assert_eq!(
        get_user["summary"].as_str(),
        Some("Get user by ID"),
        "Summary should be first line of doc comment"
    );

    // Description should be the full doc comment
    let description = get_user["description"].as_str();
    assert!(
        description.is_some(),
        "Should have description from doc comment"
    );
    assert!(
        description
            .unwrap()
            .contains("Fetch a user by their unique ID"),
        "Description should contain full doc text. Got: {:?}",
        description
    );
}

#[test]
fn test_openapi_response_description_attribute() {
    let spec = EnhancedAttrsService::openapi_spec();
    let paths = &spec["paths"];

    let create_user = &paths["/api/users"]["post"];
    assert!(create_user.is_object(), "Should have create_user endpoint");

    let response_200 = &create_user["responses"]["200"];
    assert_eq!(
        response_200["description"].as_str(),
        Some("User created successfully"),
        "Should have custom response description"
    );
}

#[test]
fn test_openapi_hidden_excludes_from_spec() {
    let spec = EnhancedAttrsService::openapi_spec();
    let paths = &spec["paths"];

    // internal_method should NOT appear in the spec
    let internal = &paths["/api/internal-methods"]["get"];
    assert!(
        internal.is_null(),
        "Hidden endpoint should not appear in spec. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );
}

// ============================================================================
// param(help) wired into standalone #[openapi] JSON
// ============================================================================

#[derive(Clone)]
struct ParamHelpStandaloneService;

#[allow(unused_variables)]
#[openapi(prefix = "/api")]
impl ParamHelpStandaloneService {
    /// Find users by name
    pub fn find_users(
        &self,
        #[param(help = "Substring to match against user names")]
        name: String,
    ) -> Vec<String> {
        vec![name]
    }

    /// Get item by ID
    pub fn get_item(
        &self,
        id: String,
        #[param(help = "Maximum number of results")]
        limit: Option<u32>,
    ) -> String {
        id
    }
}

#[test]
fn test_param_help_in_standalone_openapi_query_param() {
    let spec = ParamHelpStandaloneService::openapi_spec();
    let paths = &spec["paths"];

    let find_users = &paths["/api/users"]["get"];
    assert!(
        find_users.is_object(),
        "Should have GET /api/users. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );

    let parameters = find_users["parameters"]
        .as_array()
        .expect("Should have parameters array");

    let name_param = parameters
        .iter()
        .find(|p| p["name"].as_str() == Some("name"))
        .expect("'name' parameter should appear in find_users OpenAPI spec");

    assert_eq!(
        name_param["description"].as_str(),
        Some("Substring to match against user names"),
        "#[param(help = \"...\")] should populate the OpenAPI parameter description in standalone mode"
    );
}

#[test]
fn test_param_help_in_standalone_openapi_optional_query_param() {
    let spec = ParamHelpStandaloneService::openapi_spec();
    let paths = &spec["paths"];

    // get_item -> GET /api/items/{id}
    let get_item = &paths["/api/items/{id}"]["get"];
    assert!(
        get_item.is_object(),
        "Should have GET /api/items/{{id}}. Paths: {}",
        serde_json::to_string_pretty(paths).unwrap()
    );

    let parameters = get_item["parameters"]
        .as_array()
        .expect("Should have parameters array");

    let limit_param = parameters
        .iter()
        .find(|p| p["name"].as_str() == Some("limit"))
        .expect("'limit' parameter should appear in get_item OpenAPI spec");

    assert_eq!(
        limit_param["description"].as_str(),
        Some("Maximum number of results"),
        "#[param(help = \"...\")] should populate the description for optional query params in standalone mode"
    );
}