Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/go-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ jobs:
uses: golangci/golangci-lint-action@v9
with:
args: --timeout=30m
version: v2.13.2
version: v2.15.0

- name: Run govulncheck
run: |
Expand Down
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **JSON serializes hierarchical sentinel parents** ([#59]) — adds the public
`SentinelParents` accessor and an additive `sentinel_ancestors` JSON field containing
flattened, deduplicated parent sentinel texts while preserving the existing `sentinels` field.
The new field preserves ancestor membership, not the parent-child graph.

- **Repository community health and security governance** ([#67]) — adds `SECURITY.md` defining supported release lines and private vulnerability reporting, adds `CODE_OF_CONDUCT.md` (Contributor Covenant v2.1), and updates `CONTRIBUTING.md` references.

- **Conditional stack capture in `stacktrace`** ([#40]) — new helpers capture a stack trace only when the cause chain does not already carry one, mirroring `emperror.dev/errors`'s `WrapIf`/`WithStackIf` pattern without pulling traces into the zero-dependency core:
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,9 @@ need to tag it; use `Wrap` when you also want to add context about where/why it
#### Hierarchical sentinels

Pass parent sentinels to build a taxonomy. A child matches itself *and* every parent.
`errx.SentinelParents(child)` returns its direct parents for inspection; treat the returned
slice as read-only. The JSON serializer keeps direct values in `sentinels` and writes the
flattened, deduplicated parent texts to `sentinel_ancestors`.

```go
var (
Expand Down Expand Up @@ -636,6 +639,8 @@ when you need to pass plain `error` values.

### Inspection

- **`SentinelParents(c Classified) []Classified`** — direct parents of an errx sentinel;
returns nil for other classifications. Treat the returned slice as read-only.
- **`IsDisplayable(err error) bool`** / **`DisplayText(err error) string`**
- **`DisplayTextDefault(err error, def string) string`** — fallback on a miss.
- **`DisplayTextOrEmpty(err error) string`** — `""` on a miss; safe for user surfaces.
Expand Down
12 changes: 12 additions & 0 deletions errx.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,18 @@ func NewSentinel(text string, parents ...Classified) Classified {
return &sentinel{text: text, parents: parents}
}

// SentinelParents returns the direct parents of c when c is an errx sentinel.
// It returns nil when c is nil or is not a sentinel.
//
// The returned slice aliases internal storage and must be treated as read-only.
func SentinelParents(c Classified) []Classified {
s, ok := c.(*sentinel)
if !ok || s == nil {
return nil
}
return s.parents
}

// Wrap wraps an error with additional context text and optional classification sentinels.
// The attached classification sentinels can be used later to identify the error using errors.Is,
// as well as add displayable errors.
Expand Down
20 changes: 20 additions & 0 deletions errx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ func TestNewSentinel(t *testing.T) {
}
}

func TestSentinelParents(t *testing.T) {
root := errx.NewSentinel("root")
parent := errx.NewSentinel("parent", root)
child := errx.NewSentinel("child", parent)

parents := errx.SentinelParents(child)
if len(parents) != 1 || parents[0] != parent {
t.Fatalf("SentinelParents(child) = %v, want [parent]", parents)
}
if got := errx.SentinelParents(root); got != nil {
t.Errorf("SentinelParents(root) = %v, want nil", got)
}
if got := errx.SentinelParents(errx.NewDisplayable("display")); got != nil {
t.Errorf("SentinelParents(displayable) = %v, want nil", got)
}
if got := errx.SentinelParents(nil); got != nil {
t.Errorf("SentinelParents(nil) = %v, want nil", got)
}
}

// TestWrapWithTag tests wrapping with a classification tag
func TestWrapWithTag(t *testing.T) {
tag := errx.NewSentinel("tag error")
Expand Down
12 changes: 12 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@ func Example() {
// Error is classified as not found
}

func ExampleSentinelParents() {
ErrDatabase := errx.NewSentinel("database")
ErrTimeout := errx.NewSentinel("timeout", ErrDatabase)

for _, parent := range errx.SentinelParents(ErrTimeout) {
fmt.Println(parent.Error())
}

// Output:
// database
}

// ExampleWrap demonstrates wrapping errors with context and tags
func ExampleWrap() {
ErrDatabase := errx.NewSentinel("database error")
Expand Down
11 changes: 9 additions & 2 deletions json/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,8 @@ jsonBytes, _ := errxjson.Marshal(err, errxjson.WithAttributes(false))
### WithSentinels

Include sentinel text in the output. The default is `true`; pass `false` to omit the
`sentinels` field when those messages are internal implementation details.
`sentinels` and `sentinel_ancestors` fields when those messages are internal
implementation details.

```go
jsonBytes, _ := errxjson.Marshal(err, errxjson.WithSentinels(false))
Expand Down Expand Up @@ -165,6 +166,7 @@ The serialized error has the following structure:
"message": "error message from Error()",
"display_text": "user-facing message (if displayable error present)",
"sentinels": ["list", "of", "sentinel", "texts"],
"sentinel_ancestors": ["parent", "grandparent"],
"attributes": [
{"key": "user_id", "value": 123},
{"key": "action", "value": "delete"}
Expand Down Expand Up @@ -196,6 +198,11 @@ Sentinels with attributed or traced parents keep their own sentinel text;
classifications with a displayable anywhere in their chain remain excluded from
`sentinels` and provide `display_text` instead.

The `sentinel_ancestors` field contains pure-sentinel parents of the direct sentinels
at that serialized error level. It traverses parents depth-first in declaration order
and deduplicates by text; parents attached to a cause appear on that cause rather
than leaking into the outer error. `WithSentinels(false)` omits both sentinel fields.

## Examples

### Displayable Error
Expand Down Expand Up @@ -292,5 +299,5 @@ json.Unmarshal(jsonBytes, &serialized)
## Limitations

- **No Deserialization**: This package does not provide deserialization (JSON to error) functionality. Errors are runtime constructs and cannot be meaningfully reconstructed from JSON.
- **Sentinel Hierarchy**: Parent sentinels in hierarchical relationships are not serialized - only direct sentinels are included.
- **Sentinel Hierarchy**: `sentinel_ancestors` preserves a flattened, deduplicated list of parent texts, while `sentinels` contains direct classifications. The JSON does not identify which direct sentinel owns each parent, preserve parent-child edges, or distinguish sentinels with the same text. A future registry-backed decoder could resolve known texts to local sentinels, but this payload cannot reconstruct the original graph.
- **Attribute Ordering**: The order of attributes in the JSON output is stable for a given error but should not be relied upon for semantic meaning.
78 changes: 73 additions & 5 deletions json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ type SerializedError struct {
// Sentinels lists all classification sentinel texts found in this error
Sentinels []string `json:"sentinels,omitempty"`

// SentinelAncestors lists the deduplicated parent sentinel texts for this error level.
SentinelAncestors []string `json:"sentinel_ancestors,omitempty"`

// Attributes contains structured key-value pairs attached to this error
Attributes []SerializedAttr `json:"attributes,omitempty"`

Expand Down Expand Up @@ -271,6 +274,7 @@ func toSerializedError(err error, cfg *config, visited *visitedSet, depth int) *
// classifications and the node itself (if it's a pure sentinel) count.
if cfg.includeSentinels {
result.Sentinels = sentinelsForLevel(levelCls, node)
result.SentinelAncestors = sentinelAncestorsForLevel(levelCls, node)
}

// Attributes: chain-wide (errx.ExtractAttrs walks the chain).
Expand Down Expand Up @@ -362,6 +366,64 @@ func sentinelsForLevel(classifications []errx.Classified, node error) []string {
return sentinels
}

// sentinelAncestorsForLevel returns the pure-sentinel parents of the
// classifications attached to this error level or represented by its node.
// Parents are traversed depth-first in declaration order and deduplicated by text.
func sentinelAncestorsForLevel(classifications []errx.Classified, node error) []string {
var ancestors []string
var seenTexts map[string]bool
var visited map[errx.Classified]bool

for _, cls := range classifications {
if isPureSentinel(cls) {
addSentinelParents(cls, &ancestors, &seenTexts, &visited)
}
}
if cls, ok := node.(errx.Classified); ok && isPureSentinel(cls) {
addSentinelParents(cls, &ancestors, &seenTexts, &visited)
}

return ancestors
}

// addSentinelParents appends pure-sentinel parents and their ancestors,
// guarding against repeated sentinels and malformed cycles.
func addSentinelParents(
cls errx.Classified,
ancestors *[]string,
seenTexts *map[string]bool,
visited *map[errx.Classified]bool,
) {
parents := errx.SentinelParents(cls)
if len(parents) == 0 {
return
}

// SentinelParents only returns a non-empty slice for the internal,
// pointer-backed sentinel type, which is safe to use as a map key.
if *visited == nil {
*visited = make(map[errx.Classified]bool)
}
if (*visited)[cls] {
return
}
(*visited)[cls] = true

for _, parent := range parents {
// The root passed the chain-wide displayable check before this walk.
// Every reachable parent is therefore non-displayable, so checking
// its own kind is enough and avoids rescanning its entire subtree.
if !isPureSentinelKind(parent) {
continue
}
text := parent.Error()
if !rememberSentinel(text, seenTexts) {
*ancestors = append(*ancestors, text)
}
addSentinelParents(parent, ancestors, seenTexts, visited)
}
}

// serializeAttributes extracts and serializes attributes from an error.
// Attribute values whose JSON encoding fails (e.g. a func() value) are
// replaced with a fmt.Sprintf("%+v", v) fallback string so a single bad
Expand Down Expand Up @@ -541,20 +603,26 @@ func addPureSentinels(classifications []errx.Classified, sentinels *[]string, se
}
}

// isPureSentinel excludes attribute and trace carriers by their own type,
// isPureSentinelKind excludes attribute and trace carriers by their own type,
// including empty external implementations. An attributed or traced parent
// does not change a sentinel's kind. Displayable detection remains chain-wide
// because errx does not yet expose a displayable-kind interface.
func isPureSentinel(cls errx.Classified) bool {
// does not change a sentinel's kind.
func isPureSentinelKind(cls errx.Classified) bool {
// Use the public attribute interface here when issue #63 introduces it.
switch cls.(type) {
case interface{ Attrs() []errx.Attr }, stacktrace.Tracer:
return false
default:
return !errx.IsDisplayable(cls)
return true
}
}

// isPureSentinel also excludes classifications with a displayable anywhere in
// their chain. Detection remains chain-wide because errx does not yet expose
// a displayable-kind interface.
func isPureSentinel(cls errx.Classified) bool {
return isPureSentinelKind(cls) && !errx.IsDisplayable(cls)
}

// addSelfAsPureSentinel checks if the error itself is a pure sentinel and adds it.
func addSelfAsPureSentinel(err error, sentinels *[]string, seen *map[string]bool) {
cls, ok := err.(errx.Classified)
Expand Down
21 changes: 21 additions & 0 deletions json/json_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,24 @@ func BenchmarkMarshal_FreshStackTrace(b *testing.B) {
_, _ = errxjson.Marshal(err)
}
}

// BenchmarkMarshal_SentinelAncestorDAG guards against repeatedly searching
// each parent's subtree while collecting ancestors. The shared leaf is the
// first parent, and each new sentinel also points to the previous one.
func BenchmarkMarshal_SentinelAncestorDAG(b *testing.B) {
for _, depth := range []int{32, 64, 128} {
b.Run(fmt.Sprintf("depth_%d", depth), func(b *testing.B) {
leaf := errx.NewSentinel("leaf")
current := leaf
for i := 0; i < depth; i++ {
current = errx.NewSentinel(fmt.Sprintf("node_%d", i), leaf, current)
}
err := errx.Classify(errors.New("base"), current)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = errxjson.Marshal(err)
}
})
}
}
Loading
Loading