pasta_lua 0.2.3

Pasta Lua - Lua integration for Pasta DSL
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
-- ============================================================================
-- Task 1.2: CALLBACK.try_route / CALLBACK.sweep テスト
-- Task 3.1: CALLBACK ID generation and staging テスト
-- Requirements: 1.1, 1.2, 5.1, 5.2, 5.3, R4 (callback chaining)
-- ============================================================================

local describe = require("lua_test.test").describe
local test = require("lua_test.test").test
local expect = require("lua_test.test").expect
local mocks = require("lua_test.mocks")

-- 共通リロード: callback/store(reset_res=true なら res も)を package.loaded から
-- 一括リロードする(スイート分離規約)。呼び出し前に mocks.install を済ませること。
local function reload_callback_modules(reset_res)
    package.loaded["pasta.shiori.event.callback"] = nil
    package.loaded["pasta.store"] = nil
    if reset_res then
        package.loaded["pasta.shiori.res"] = nil
    end
    local STORE = require("pasta.store")
    local CALLBACK = require("pasta.shiori.event.callback")
    CALLBACK.reset()
    return CALLBACK, STORE
end

-- ============================================================================
-- Task 3.1: ID generation and staging tests
-- ============================================================================
describe("CALLBACK - ID generation and staging", function()
    local CALLBACK, STORE

    local function setup()
        mocks.reset()
        mocks.install()
        -- pasta.shiori.res は従来からリロード対象外(reset_res=false)
        CALLBACK, STORE = reload_callback_modules(false)
    end

    test("next_event_id generates sequential IDs", function()
        setup()
        expect(CALLBACK.next_event_id()):toBe("OnPastaCallBack1")
        expect(CALLBACK.next_event_id()):toBe("OnPastaCallBack2")
        expect(CALLBACK.next_event_id()):toBe("OnPastaCallBack3")
    end)

    test("reset clears ID counter", function()
        setup()
        CALLBACK.next_event_id() -- 1
        CALLBACK.next_event_id() -- 2
        CALLBACK.reset()
        expect(CALLBACK.next_event_id()):toBe("OnPastaCallBack1")
    end)

    test("stage_pending → consume_staged registers entry in pending", function()
        setup()
        CALLBACK.stage_pending("OnPastaCallBack1", 1000, "test timeout")

        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)
        local act = { name = "test" }

        local consumed = CALLBACK.consume_staged(co, act)
        expect(consumed):toBe(true)
        expect(CALLBACK.pending["OnPastaCallBack1"]).not_:toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack1"].co):toBe(co)
        expect(CALLBACK.pending["OnPastaCallBack1"].act):toBe(act)
        expect(CALLBACK.pending["OnPastaCallBack1"].timeout_at):toBe(1000)
        expect(CALLBACK.pending["OnPastaCallBack1"].on_timeout):toBe("test timeout")
    end)

    test("consume_staged sets STORE.co_callback", function()
        setup()
        CALLBACK.stage_pending("OnPastaCallBack1", 1000, nil)

        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)

        CALLBACK.consume_staged(co, {})
        expect(STORE.co_callback):toBe(co)
    end)

    test("consume_staged returns false when nothing staged", function()
        setup()
        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)

        local consumed = CALLBACK.consume_staged(co, {})
        expect(consumed):toBe(false)
    end)

    test("multiple stage_pending without consume raises error", function()
        setup()
        CALLBACK.stage_pending("OnPastaCallBack1", 1000, nil)

        local ok, err = pcall(function()
            CALLBACK.stage_pending("OnPastaCallBack2", 2000, "second")
        end)
        expect(ok):toBe(false)
        expect(tostring(err):find("multiple staging detected")).not_:toBe(nil)
    end)

    test("reset clears pending, staged, and STORE.co_callback", function()
        setup()
        CALLBACK.stage_pending("OnPastaCallBack1", 1000, nil)
        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)
        CALLBACK.consume_staged(co, {})

        expect(STORE.co_callback):toBe(co)
        CALLBACK.reset()
        expect(STORE.co_callback):toBe(nil)
        expect(next(CALLBACK.pending)):toBe(nil)
    end)
end)

-- ============================================================================
-- Task 1.2: try_route / sweep tests
-- ============================================================================
describe("CALLBACK.try_route", function()
    local CALLBACK

    local function setup()
        mocks.reset()
        mocks.install()
        CALLBACK = reload_callback_modules(true)
    end

    test("returns nil when req.id does not match any pending entry", function()
        setup()
        local req = { id = "OnUnknown", reference = {} }
        local result = CALLBACK.try_route(req)
        expect(result):toBe(nil)
    end)

    test("resumes coroutine with 1-based refs and returns 200 OK response", function()
        setup()
        local received_refs = nil
        -- The coroutine first yields to become suspended,
        -- then try_route resumes it with refs
        local co2 = coroutine.create(function()
            local refs = coroutine.yield()    -- first yield to become suspended
            received_refs = refs
            coroutine.yield("hello world\\e") -- yield response
        end)
        coroutine.resume(co2)                 -- initial resume to reach first yield

        local act = { name = "test_act" }
        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co2,
            act = act,
            timeout_at = 999999,
            on_timeout = "timeout reason",
        }

        local req = {
            id = "OnPastaCallBack1",
            reference = { [0] = "2.6.77" },
        }
        local result = CALLBACK.try_route(req)

        -- Refs should be 1-based
        expect(received_refs[1]):toBe("2.6.77")
        -- Entry should be removed
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        -- Response should be 200 OK
        expect(result:find("200 OK")).not_:toBe(nil)
        expect(result:find("Value: hello world\\e")).not_:toBe(nil)
    end)

    test("converts multiple 0-indexed references to 1-based array", function()
        setup()
        local received_refs = nil
        local co = coroutine.create(function()
            local refs = coroutine.yield()
            received_refs = refs
            coroutine.yield("result")
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 999999,
            on_timeout = nil,
        }

        local req = {
            id = "OnPastaCallBack1",
            reference = { [0] = "val0", [1] = "val1", [2] = "val2" },
        }
        CALLBACK.try_route(req)

        expect(received_refs[1]):toBe("val0")
        expect(received_refs[2]):toBe("val1")
        expect(received_refs[3]):toBe("val2")
    end)

    test("handles callback chaining (R4) via consume_staged", function()
        setup()
        -- Coroutine that chains: receives refs, stages a new pending, yields
        local co = coroutine.create(function()
            coroutine.yield() -- first callback wait (refs は本テストでは未使用)
            -- After receiving refs, stage another callback (simulating get_property again)
            CALLBACK.stage_pending("OnPastaCallBack2", 999999, "chained timeout")
            coroutine.yield("intermediate response") -- yield again for second callback
        end)
        coroutine.resume(co)

        local act = { name = "test_act" }
        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = act,
            timeout_at = 999999,
            on_timeout = nil,
        }

        local req = {
            id = "OnPastaCallBack1",
            reference = { [0] = "first_value" },
        }
        local result = CALLBACK.try_route(req)

        -- Original entry removed
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        -- Chained entry registered via consume_staged
        expect(CALLBACK.pending["OnPastaCallBack2"]).not_:toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack2"].co):toBe(co)
        expect(CALLBACK.pending["OnPastaCallBack2"].on_timeout):toBe("chained timeout")
        -- Response from intermediate yield
        expect(result:find("200 OK")).not_:toBe(nil)
    end)

    -- ========================================================================
    -- 3.49 (G3) 境界回帰テスト: reference 欠落 req のハードニング
    -- Rust 境界(lua_request.rs)は reference テーブルを常時生成するが、
    -- Lua 側から直接 EVENT.fire/try_route を呼ぶ経路では欠落しうる。
    -- 旧実装は pending 削除後に nil 添字エラーとなり待機コルーチンを孤児化していた。
    -- ========================================================================
    test("try_route: reference 欠落 req でもエラーにならず空 refs で resume する (3.49 G3)", function()
        setup()
        local received_refs = "not_set"
        local co = coroutine.create(function()
            received_refs = coroutine.yield()
            coroutine.yield("recovered\\e")
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 999999,
            on_timeout = nil,
        }

        -- reference フィールドなしの req
        local result = CALLBACK.try_route({ id = "OnPastaCallBack1" })

        expect(type(received_refs)):toBe("table")
        expect(next(received_refs)):toBe(nil)
        expect(result:find("200 OK")).not_:toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
    end)

    test("propagates error when coroutine errors during resume", function()
        setup()
        local co = coroutine.create(function()
            coroutine.yield()
            error("coroutine exploded")
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 999999,
            on_timeout = nil,
        }

        local req = {
            id = "OnPastaCallBack1",
            reference = { [0] = "val" },
        }
        local ok, err = pcall(function()
            CALLBACK.try_route(req)
        end)
        expect(ok):toBe(false)
        expect(tostring(err):find("coroutine exploded")).not_:toBe(nil)
    end)
end)

describe("CALLBACK.sweep", function()
    local CALLBACK
    local warn_calls

    local function setup()
        warn_calls = {}
        mocks.reset()
        mocks.install({
            log = {
                trace = function() end,
                debug = function() end,
                info = function() end,
                warn = function(msg) warn_calls[#warn_calls + 1] = msg end,
                error = function() end,
            },
        })
        CALLBACK = reload_callback_modules(true)
    end

    test("does nothing when no entries exist", function()
        setup()
        local result = CALLBACK.sweep(1000)
        expect(result):toBe(nil)
    end)

    test("does nothing when entries have not timed out", function()
        setup()
        local co = coroutine.create(function()
            coroutine.yield()
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 2000,
            on_timeout = "timeout",
        }

        local result = CALLBACK.sweep(1000)
        expect(result):toBe(nil)
        -- Entry should still exist
        expect(CALLBACK.pending["OnPastaCallBack1"]).not_:toBe(nil)
    end)

    test("resumes with nil,on_timeout and returns 500 when on_timeout is string", function()
        setup()
        local received_args = {}
        local co = coroutine.create(function()
            local val, reason = coroutine.yield()
            received_args.val = val
            received_args.reason = reason
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 100,
            on_timeout = "callback timeout: get_property",
        }

        local result = CALLBACK.sweep(200)

        -- Coroutine resumed with nil, on_timeout
        expect(received_args.val):toBe(nil)
        expect(received_args.reason):toBe("callback timeout: get_property")
        -- Entry removed
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        -- 500 response returned
        expect(result:find("500 Internal Server Error")).not_:toBe(nil)
        -- 3.49 (G3) 随伴更新: sweep が RES.err 経路へ統一され、ヘッダーキーは
        -- res.lua 正準の "X-Error-Reason" となった(旧: インライン構築の "X-ERROR-REASON")
        expect(result:find("X%-Error%-Reason: callback timeout: get_property")).not_:toBe(nil)
        -- log.warn called
        expect(#warn_calls):toBe(1)
        expect(warn_calls[1]:find("OnPastaCallBack1")).not_:toBe(nil)
    end)

    test("resumes with nil and returns nil when on_timeout is nil", function()
        setup()
        local resumed = false
        local received_val = "not_set"
        local co = coroutine.create(function()
            local val = coroutine.yield()
            received_val = val
            resumed = true
        end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 100,
            on_timeout = nil,
        }

        local result = CALLBACK.sweep(200)

        expect(resumed):toBe(true)
        expect(received_val):toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        expect(result):toBe(nil)
        expect(#warn_calls):toBe(0)
    end)

    test("returns only first string on_timeout as 500 among multiple timeouts", function()
        setup()
        -- Create two timed-out entries with string on_timeout
        local co1 = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co1)
        local co2 = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co2)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co1,
            act = {},
            timeout_at = 50,
            on_timeout = "timeout reason 1",
        }
        CALLBACK.pending["OnPastaCallBack2"] = {
            co = co2,
            act = {},
            timeout_at = 60,
            on_timeout = "timeout reason 2",
        }

        local result = CALLBACK.sweep(200)

        -- Both entries removed
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack2"]):toBe(nil)
        -- Only one 500 response (the first one encountered)
        expect(result:find("500 Internal Server Error")).not_:toBe(nil)
        -- Both should have been logged
        expect(#warn_calls):toBe(2)
    end)

    -- ========================================================================
    -- 3.49 (G3) 境界回帰テスト: sweep タイムアウト 500 の RES.err 経路統一
    -- (X-Error-Reason 正準ケーシング・標準ヘッダー付与・空文字列正規化)
    -- ========================================================================
    test("sweep: タイムアウト 500 は RES.err 経路で X-Error-Reason 正準ヘッダーを出力する (3.49 G3)", function()
        setup()
        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 100,
            on_timeout = "timeout via sweep",
        }

        local result = CALLBACK.sweep(200)

        expect(result:find("500 Internal Server Error", 1, true)).not_:toBe(nil)
        -- 正準ケーシングを plain find(大文字小文字厳密)で固定
        expect(result:find("X-Error-Reason: timeout via sweep", 1, true)).not_:toBe(nil)
        expect(result:find("X-ERROR-REASON", 1, true)):toBe(nil)
        -- RES.build 標準ヘッダー3種を含む(旧インライン構築でも同一だが経路統一を固定)
        expect(result:find("Charset: ", 1, true)).not_:toBe(nil)
        expect(result:find("Sender: ", 1, true)).not_:toBe(nil)
        expect(result:find("SecurityLevel: ", 1, true)).not_:toBe(nil)
    end)

    test("sweep: 空文字列 on_timeout は RES.err 規約で Unknown error に正規化される (3.49 G3)", function()
        setup()
        local co = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co,
            act = {},
            timeout_at = 100,
            on_timeout = "",
        }

        local result = CALLBACK.sweep(200)

        expect(result:find("500 Internal Server Error", 1, true)).not_:toBe(nil)
        expect(result:find("X-Error-Reason: Unknown error", 1, true)).not_:toBe(nil)
    end)

    test("handles mixed on_timeout types (string and nil)", function()
        setup()
        local co1 = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co1)
        local co2 = coroutine.create(function() coroutine.yield() end)
        coroutine.resume(co2)

        CALLBACK.pending["OnPastaCallBack1"] = {
            co = co1,
            act = {},
            timeout_at = 50,
            on_timeout = nil,
        }
        CALLBACK.pending["OnPastaCallBack2"] = {
            co = co2,
            act = {},
            timeout_at = 60,
            on_timeout = "timeout reason",
        }

        local result = CALLBACK.sweep(200)

        -- Both removed
        expect(CALLBACK.pending["OnPastaCallBack1"]):toBe(nil)
        expect(CALLBACK.pending["OnPastaCallBack2"]):toBe(nil)
        -- Only one warn call (the string one)
        expect(#warn_calls):toBe(1)
        -- Response may or may not be nil depending on iteration order,
        -- but at least one had string on_timeout
        if result then
            expect(result:find("500 Internal Server Error")).not_:toBe(nil)
        end
    end)
end)