hooks

package
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 4 Imported by: 0

README

haistack-hooks (pkg/hooks)

Small FHIR intercept SPI for HTTP and core write paths.

Four intentional extension points (not a full HAPI interceptor bus).


What it does

Points (hooks.go):

Point Constant When
Incoming hooks.Incoming HTTP routed, before handler
PreStorage hooks.PreStorage Core write, before persist
PostCommit hooks.PostCommit After successful WriteSession commit
Outgoing hooks.Outgoing Before response envelope serialized

Event:

type Event struct {
    Point        Point
    Action       Action
    ResourceType string
    ID           string
    Operation    string
    Resource     *types.ResourceEnvelope // mutable: PreStorage, Outgoing
    Previous     *types.ResourceEnvelope
}

Actions: ActionRead, ActionCreate, ActionUpdate, ActionPatch, ActionDelete, ActionSearch, ActionHistory, ActionTransaction, ActionBatch, ActionOperation, ActionMetadata.

Registry:

  • NewRegistry(), On(point, Func), Run(ctx, point, event)
  • Registration order preserved; first error stops later funcs on that point (TestRegistryRunsInOrderAndStopsOnError)
  • Unknown points rejected (TestRegistryRejectsUnknownPoint)
  • Nil registry Run → noop

Failure semantics:

  • Incoming / PreStorage / Outgoing errors abort the operation
  • PostCommit errors ignored in core (_ = s.hooks.Run(...)) — TestPostCommitHookSeesPersistedResource

Wire the same hooks.Hooks into core.ResourceServiceConfig.Hooks and http.Config.Hooks, or runtime.Builder.WithHooks.

Do not add new point types here — use HTTP middleware for CORS/rate limits.


How it fits in the ecosystem

HTTP ──► Incoming (pkg/http) ──► handler ──► core
                                                  │
                                            PreStorage
                                                  │
                                            WriteSession
                                                  │
                                            PostCommit (errors ignored)
                                                  │
HTTP ◄── Outgoing ◄── formattedResponseWriter

Incoming/Outgoing are HTTP-aware (actionFromRoute in http/hooks.go). PreStorage/PostCommit are write-path only.


When to use it

  • Audit/metrics on writes
  • PreStorage enrichment (keep idempotent)
  • Outgoing redaction/strip internal extensions
  • Incoming guards (maintenance mode, custom headers)
  • Domain rejection via *core.ServiceError from PreStorage

Avoid long work in hooks; use pkg/jobs from PostCommit if needed. Do not rely on PostCommit for must-not-lose side effects.


Usage modes

1. Runtime builder
reg := hooks.NewRegistry()
_ = reg.On(hooks.PreStorage, func(ctx context.Context, event *hooks.Event) error {
    return nil
})
rt, err := runtime.New().WithSQLite(path).WithHooks(reg).Build(ctx)
2. Manual core + HTTP
reg := hooks.NewRegistry()
_ = reg.On(hooks.Incoming, func(ctx context.Context, event *hooks.Event) error {
    return nil
})
svc, _ := core.NewResourceService(core.ResourceServiceConfig{Hooks: reg, /* stores */})
handler, _ := haihttp.NewHandler(haihttp.Config{Hooks: reg, /* ... */})
3. PreStorage mutate or reject

From core/hooks_test.go:

_ = reg.On(hooks.PreStorage, func(_ context.Context, event *hooks.Event) error {
    if strings.Contains(string(event.Resource.JSON), "Blocked") {
        return errors.New("blocked")
    }
    event.Resource.JSON = []byte(`{"resourceType":"Patient","id":"pat-1",...}`)
    return nil
})
4. PostCommit (non-fatal)
_ = reg.On(hooks.PostCommit, func(_ context.Context, event *hooks.Event) error {
    return errors.New("ignored") // write still succeeds
})
5. Outgoing shaping

HTTP formattedResponseWriter runs Outgoing before serialize (http/hooks_test.go, writer.go).


Examples (APIs from this repo)

err := reg.On(hooks.Incoming, fn)
err = reg.Run(ctx, hooks.Incoming, &hooks.Event{
    Action: hooks.ActionRead, ResourceType: "Patient", ID: "p1",
})

Func signature:

type Func func(ctx context.Context, event *hooks.Event) error

Mutate resource (TestRegistryMutatesEventResource): replace event.Resource in PreStorage.

Incoming non-ServiceError → HTTP invalidRequest("incoming hook rejected request", err).

Ordering: hooks a, b, c on Incoming — if b errors, c skipped.


Where it fits

HTTP ──► Incoming ──► handler ──► core ──► PreStorage ──► WriteSession ──► PostCommit
                                                                              │
HTTP ◄── Outgoing ◄── envelope ◄────────────────────────────────────────────┘

One registry instance keeps HTTP and core policy aligned.


Limits

  • Four points only — no ad-hoc pointcut constants
  • PostCommit failures swallowed — use durable queues
  • Synchronous — blocks request path
  • PreStorage/PostCommit not on read-only core paths (reads use HTTP Incoming/Outgoing)
  • Register hooks at startup; Registry is mutex-safe for concurrent Run
  • Raw error responses may bypass Outgoing resource mutation

Documentation

Overview

Package hooks is a small FHIR intercept SPI for HAIStack.

HAPI's interceptor bus has dozens of pointcuts. This package keeps four:

  • Incoming — HTTP request after routing, before the handler runs
  • PreStorage — core write path, after validation/id assignment, before persist
  • PostCommit — core write path, after the write session commits
  • Outgoing — HTTP response, before a resource envelope is serialized

Register Func values on a Registry with On, then wire the same Registry into core.ResourceServiceConfig.Hooks and http.Config.Hooks (runtime.Builder.WithHooks does both). Hooks run in registration order. Incoming, pre-storage, and outgoing errors abort the request; post-commit errors are ignored so a successful write is not reported as failure.

Do not add more pointcuts here. Extend by registering another Func on one of these four, or by wrapping HTTP middleware for transport concerns.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Action

type Action string

Action names the FHIR interaction that triggered the hook.

const (
	ActionRead        Action = "read"
	ActionCreate      Action = "create"
	ActionUpdate      Action = "update"
	ActionPatch       Action = "patch"
	ActionDelete      Action = "delete"
	ActionSearch      Action = "search"
	ActionHistory     Action = "history"
	ActionTransaction Action = "transaction"
	ActionBatch       Action = "batch"
	ActionOperation   Action = "operation"
	ActionMetadata    Action = "metadata"
)

type Event

type Event struct {
	Point        Point
	Action       Action
	ResourceType string
	ID           string
	Operation    string
	Resource     *types.ResourceEnvelope
	Previous     *types.ResourceEnvelope
}

Event is the payload delivered to a hook. Resource is mutable on pre-storage and outgoing so a hook can replace or annotate it.

type Func

type Func func(ctx context.Context, event *Event) error

Func is one intercept callback.

type Hooks

type Hooks interface {
	Run(ctx context.Context, point Point, event *Event) error
}

Hooks runs the four intercept stages. Registry implements it.

type Point

type Point string

Point is one of the four intercept stages.

const (
	Incoming   Point = "incoming"
	PreStorage Point = "pre-storage"
	PostCommit Point = "post-commit"
	Outgoing   Point = "outgoing"
)

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry holds Func values for the four points.

func NewRegistry

func NewRegistry() *Registry

NewRegistry returns an empty hook registry.

func (*Registry) On

func (r *Registry) On(point Point, fn Func) error

On registers fn for point. Unknown points are rejected.

func (*Registry) Run

func (r *Registry) Run(ctx context.Context, point Point, event *Event) error

Run invokes registered funcs for point in registration order.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL