Documentation
¶
Overview ¶
Package projection runs versioned read models (ADR-0005).
A Projection version N keeps its read model in its own tables, by convention <table>_vN, and is built by the Consumer <name>@vN. Readers query a view <table> that the service's own migrations point at the active version; the library never runs DDL. During a version bump a newer version builds as a shadow beside the active one:
p, err := projection.New(rt, projection.Config{
Name: "tasks",
Active: projection.Version{N: 1, Handler: tasksV1},
Shadow: &projection.Version{N: 2, Handler: tasksV2},
})
err = consumer.Group(p.Consumers()).Run(ctx)
Each version's Consumer runs Transactional, so its writes through postgres.Conn (postgres.Stage in memory) commit with its Cursor. Await waits for the active version only; CaughtUp tells whether the shadow (or the active version, without a shadow) has caught up.
Change notifications ¶
A handler of the active version calls Notify(ctx, entity, id) for every entity it changed. The Change {Tenant, Entity, ID} is sent inside the Cursor transaction, so Subscriptions see it only after the commit and never for a failed transaction. In the shadow, Notify does nothing. A PgRuntime sends it on the channel <schema>.changes, and Subscribe receives it through the runtime's notify.Listener; an InMemoryRuntime delivers it in process. A Change with Gap set means changes may have been lost: refetch everything shown.
Version bump ¶
Changing a read model's shape, or repairing its data, is a version bump. It spans two releases plus a cleanup:
- Release N: a migration creates <table>_vN+1, and the code registers version N+1 as the Shadow. It builds from the first event while readers keep using version N, which stays live.
- Release N+1, once CaughtUp reports true: a migration switches the view, guarded by a DO block that raises while the shadow lags by more than a threshold (see below). The code makes N+1 the Active version and drops version N.
- A later release drops <table>_vN and its Cursor row (DELETE FROM public.consumer_cursors WHERE name = '<name>@vN').
The migration of release N+1 for a Projection "tasks" going to version 2:
DO $$
BEGIN
IF public.consumer_pending('tasks@v2', 100) > 100 THEN
RAISE EXCEPTION 'projection tasks@v2 is not caught up';
END IF;
END
$$;
CREATE OR REPLACE VIEW tasks AS SELECT id, title, done FROM tasks_v2;
The threshold (100 here) bounds how many events the new active version may still have to process when the view switches. consumer_pending raises by itself while the shadow is Stopped or has no Cursor. CREATE OR REPLACE VIEW only accepts a view that keeps every column with its type, which pods of release N still read during the rollout; removing or retyping a column takes a later bump.
Reset clears every version and rewinds its Cursor in one transaction. It is for prototypes and development only.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrOutsideHandler reports Notify called outside the Handler of a // Projection version. ErrOutsideHandler = errors.New("projection: notify outside a projection handler") // ErrEmptyEntity reports Notify without an entity name. ErrEmptyEntity = errors.New("projection: notify: empty entity") )
Functions ¶
func Notify ¶
Notify sends a Change for the entity id of the Tenant in ctx to every Subscription. Call it from the Handler of a Projection version: it is sent inside the Cursor transaction, so subscribers only see it once the transaction commits, and never when the handler fails. In the shadow version it does nothing. Outside a handler it fails with ErrOutsideHandler, without an entity with ErrEmptyEntity.
A PgRuntime sends it with pg_notify on the channel <schema>.changes; an InMemoryRuntime delivers it in process.
Types ¶
type Change ¶
type Change struct {
// Tenant is the Tenant of the event whose handler sent the Change.
Tenant string
// Entity names the kind of read model entity, as passed to Notify.
Entity string
// ID identifies the entity.
ID uuid.UUID
// Gap reports that changes may have been lost (a full buffer or a
// reconnect); the other fields are empty. Refetch everything shown.
Gap bool
}
Change tells that a read model entity changed, so a live UI can refetch it.
type Config ¶
type Config struct {
// Name names the Projection. It must not contain '@'.
Name string
// EventTypes is the filter of every version. Leave it empty to take each
// version's filter from its Handler (a Router), so a new version can
// handle more types than the active one.
EventTypes []string
// Active is the version readers see. Only it sends change
// notifications and is the target of Await.
Active Version
// Shadow is a newer version building beside the active one, or nil.
Shadow *Version
}
Config configures a Projection.
type Projection ¶
type Projection struct {
// contains filtered or unexported fields
}
Projection runs the Consumers of a Projection's active version and, during a version bump, its shadow version.
func New ¶
New creates the Consumers of cfg's versions on rt. They always run Transactional; opts apply to each of them. New fails with consumer.ErrInvalidConfig for an empty or '@'-containing Name, a version below 1, a nil Handler or a Shadow that is not newer than Active, and with consumer.ErrDuplicate when rt already runs one of the versions.
func (*Projection) Await ¶
func (p *Projection) Await(ctx context.Context, pos eventstore.Cursor) consumer.Freshness
Await waits until the active version has caught up to pos, as consumer.Consumer.Await does. The shadow is never awaited.
func (*Projection) CaughtUp ¶
func (p *Projection) CaughtUp(ctx context.Context) (bool, error)
CaughtUp reports whether the shadow version, or the active one when there is no shadow, has processed every visible event it matches and is not Stopped. Use it to decide when the next release may switch to the shadow.
func (*Projection) Consumers ¶
func (p *Projection) Consumers() []*consumer.Consumer
Consumers returns the Consumers to run, the active version's first and the shadow's second. Put them into a consumer.Group.
func (*Projection) Reset ¶
func (p *Projection) Reset(ctx context.Context) error
Reset is for prototypes and development, where readers may see an empty read model. It runs the Clear of every version and rewinds their Cursors to the start of the log in one transaction, and clears their Stopped state; the versions then rebuild from the first event. It fails with consumer.ErrRunning while a version runs or drains, here or in another process, and with consumer.ErrInvalidConfig when a version has no Clear. In production, repair a read model with a version bump instead.
type Subscription ¶
type Subscription struct {
// contains filtered or unexported fields
}
Subscription receives the Changes of one Runtime.
func Subscribe ¶
Subscribe returns a Subscription to the Changes sent on rt from now on. It ends when ctx ends or on Close, whichever comes first; C is closed then. On a PgRuntime it listens through the runtime's Listener and fails with consumer.ErrInvalidConfig when there is none; changes sent before the LISTEN took effect are not delivered. A Subscription receives the Changes of every Tenant: filter by Change.Tenant before forwarding one where a Tenant can see it (ADR-0014).
func (*Subscription) C ¶
func (s *Subscription) C() <-chan Change
C returns the channel Changes are delivered on. It is closed by Close.
func (*Subscription) Close ¶
func (s *Subscription) Close()
Close ends the Subscription and closes C. Close is idempotent.
type Version ¶
type Version struct {
// N numbers the version, from 1. Its Consumer is named <name>@vN.
N int
// Handler writes the version's tables through the Cursor transaction in
// ctx (postgres.Conn, or postgres.Stage in memory).
Handler consumer.Handler
// Clear empties the version's tables through the transaction in ctx.
// Only Reset needs it.
Clear func(ctx context.Context) error
}
Version is one Projection version: its own tables, built by its own Consumer.