refactor(rules): improve termination detection and block parsing logic

Refactors the termination detection in the rules DSL to properly handle if-block and if-else-block commands.

Adds new functions `commandsTerminateInPre`, `commandTerminatesInPre`, and `ifElseBlockTerminatesInPre`
to recursively check if command sequences terminate in the pre-phase.

Also improves the Parse function to try block syntax first with proper error handling and fallback to YAML.

Includes test cases for dead code detection with terminating handlers in conditional blocks.
This commit is contained in:
yusing
2026-02-24 01:05:54 +08:00
parent 08de9086c3
commit 54be056530
5 changed files with 126 additions and 19 deletions

View File

@@ -69,6 +69,55 @@ header Host example.com {
set resp_header X-Test first
}
header Host example.com {
error 403 "forbidden"
}
`,
want: nil,
},
{
name: "same condition with terminating handler inside if block",
rules: `
header Host example.com {
@default {
error 404 "not found"
}
}
header Host example.com {
error 403 "forbidden"
}
`,
want: ErrDeadRule,
},
{
name: "same condition with terminating handler across if else block",
rules: `
header Host example.com {
@method GET {
error 404 "not found"
} else {
redirect https://example.com
}
}
header Host example.com {
error 403 "forbidden"
}
`,
want: ErrDeadRule,
},
{
name: "same condition with non terminating if branch in if else block",
rules: `
header Host example.com {
@method GET {
set resp_header X-Test first
} else {
error 404 "not found"
}
}
header Host example.com {
error 403 "forbidden"
}
@@ -128,3 +177,15 @@ func TestHasTopLevelLBrace(t *testing.T) {
})
}
}
func TestRulesParse_BlockTriedThenYAMLFails_ReturnsBlockError(t *testing.T) {
input := `default {`
_, blockErr := parseBlockRules(input)
require.Error(t, blockErr)
var rules Rules
err := rules.Parse(input)
require.Error(t, err)
assert.Equal(t, blockErr.Error(), err.Error())
}