Hooks
A hook runs a prepared statement you already serve, unchanged, when a stream record arrives, when another hook runs that statement, or when a queued entry falls due.
HOOK(RUN <prepared statement> ON <trigger> [AS <alias>] [WHERE <condition>] [AT <due time>]
USING <values> [TO <sink> [, <sink> …]] [QUEUE <sink>]
[WITH (START = …, POLICY = …, EVERY = …, EXPIRE = …)]) A hook is a feature, declared in CREATE FEATURES like any other. It shares its clauses with LOGGER . Streams, sinks and hooks reach featuremeshd at RECOMPILE SERVING or at its next sync ( Recompile before serving ).
Three kinds
| Event hook | Hook on a statement | Scheduled hook | |
|---|---|---|---|
| Declared as | HOOK(… ON <stream record>) | HOOK(… ON <statement>), without AT | HOOK(… ON <statement> AT …) |
| Fired by | each record of a Kafka topic | each successful call of its statement by another hook, once that hook's batch is written | an entry of its queue falling due. Entries are queued by the hook runs of the statement it is ON |
| Calls | one per record | one per triggering call | one per due reference |
| Writes | the event index, latest values, the queues of the hooks on its statement | the same | latest values, the queues of the hooks on its statement |
REQUEST_TIME() | the record's Kafka timestamp, not a time field of its payload such as event_time | the trigger's own REQUEST_TIME(): down a chain from an event hook, the record's Kafka timestamp | the drain's time T, on the queue store's clock in whole seconds: the due time or later, by the drain period, a backlog or retries |
| State of its own, besides what it writes | none: its offsets are in Kafka | none | its queue, in a store |
REQUEST_TIME() is also the request_time of every value the call writes. A scheduled hook's value is as of its drain, not its due time, so a later drain reads more of the index. A bucket's own minute or hour is in its key. A materialized view is not a hook: it is a scheduled query.
An event hook, ON a stream's record, writing an event index:
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS
PERSIST
stream := SOURCE_STREAM('kafka://broker:9092' WITH (FORMAT = 'json')),
payments := EXTERNAL_COLUMNS(
payment_id BIGINT,
merchant_id BIGINT,
amount DOUBLE,
event_time TIMESTAMP(3)
FROM TABLE(stream[payments])
),
payment_id := INPUT(BIGINT),
merchant_id := INPUT(BIGINT),
amount := INPUT(DOUBLE),
event_time := INPUT(TIMESTAMP(3)),
pay_row := ROW(
event_time AS event_time,
payment_id AS payment_id,
amount AS amount
),
minute_ref := ROW(
merchant_id AS merchant_id,
DATE_TRUNC(event_time, 'minute') AS minute
),
minute_close := (DATE_TRUNC(event_time, 'minute') + INTERVAL '70 SECOND')::TIMESTAMP(0),
pay_ps := PREPARED_STATEMENT(
pay_row
USING (payment_id, merchant_id, amount, event_time)
CAPTURE (minute_ref, minute_close)
),
pay_index := SINK(
'redis://redis:6379'
KEY 'pay:{' || merchant_id::VARCHAR || '}'
INDEXED ON event_time UNIQUE ON payment_id
WITH (
FORMAT = 'msgpack',
MODE = 'append',
SHAPE = 'sorted_set',
RETENTION = INTERVAL '1 DAY'
)
),
on_payment := HOOK(
RUN pay_ps
ON payments AS p
WHERE p[amount] > 0
USING (p[payment_id], p[merchant_id], p[amount], p[event_time])
TO pay_index
WITH (
START = 'earliest'
)
)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_REF.AMOUNT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.EVENT_TIME | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.MERCHANT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.MINUTE_CLOSE | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.MINUTE_REF | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.ON_PAYMENT | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PAYMENTS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PAYMENT_ID | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PAY_INDEX | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PAY_PS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PAY_ROW | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.STREAM | CREATED | Feature created as not exists |
A scheduled hook ON the event hook's statement. Its reference MINUTE_REF is a row, (merchant_id, minute), so the queue holds one entry per merchant and minute. The statement it runs, MINUTE_PS, takes that row as its input, so each run is a lookup on one merchant:
CREATE OR REPLACE FEATURES IN FM.TUTORIALS.HOOK_REF AS
PERSIST
mm := INPUT(ROW<merchant_id BIGINT, minute TIMESTAMP(3)>),
n_doubled := mm[merchant_id] * 2,
minute_ps := PREPARED_STATEMENT(n_doubled USING mm),
per_minute := SINK(
'postgresql://fm@postgres:5432/fm'
TABLE 'per_minute' KEY (MERCHANT_ID, MINUTE)
WITH (
MODE = 'latest',
PASSWORD = SECRET('env', 'PG_PASSWORD')
)
),
minute_queue := SINK(
'postgresql://fm@postgres:5432/fm'
TABLE 'minute_queue'
WITH (
PASSWORD = SECRET('env', 'PG_PASSWORD')
)
),
rollup_minute := HOOK(
RUN minute_ps
ON pay_ps
AT minute_close
USING (minute_ref)
TO per_minute
QUEUE minute_queue
WITH (
POLICY = 'earliest',
EVERY = INTERVAL '10 SECOND',
EXPIRE = INTERVAL '23 HOUR'
)
)
;| feature_name VARCHAR | status VARCHAR | message VARCHAR |
|---|---|---|
| FM.TUTORIALS.HOOK_REF.MINUTE_PS | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.MINUTE_QUEUE | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.MM | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.N_DOUBLED | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.PER_MINUTE | CREATED | Feature created as not exists |
| FM.TUTORIALS.HOOK_REF.ROLLUP_MINUTE | CREATED | Feature created as not exists |
Clauses
| Clause | Takes | Notes |
|---|---|---|
RUN | a PREPARED_STATEMENT | The statement reads its sources like any serving call. Its output goes TO the sinks, and its loggers log the hook's calls |
ON | a stream's record, or a prepared statement | A record is EXTERNAL_COLUMNS(… FROM TABLE(STREAM[topic])) and needs AS. A statement's call row (its inputs, output and captures) is read by feature name |
AS | an alias | A record only: ON PAYMENTS AS p, then p[field] |
WHERE | a boolean over the trigger's row | NULL does not fire |
AT | a TIMESTAMP(0) over the trigger's row | Queues the run: the USING values are the reference, AT its due time. A statement trigger only: AT schedules a run after the writes of the statement the hook is ON, and a stream's record has none (UE/HOOK-AT-ON-STREAM). Run a statement on the stream, and schedule ON it |
USING | the call's inputs, by position | The statement's own USING, binders removed, each input replaced by a value: (a, b), c for two input tables. One input table of three inputs takes one group of three values |
TO | hot sinks: the stores serving reads, Redis, PostgreSQL and MySQL/MariaDB | May be empty when the statement's loggers or hooks are the point. A hot sink has one writer: a second hook or view writing it is refused (UE/SINK-SHARED), as is a logger's sink ( Sinks ) |
QUEUE | a bare sink: a table, or a constant Redis key prefix ( Queues ) | Where a scheduled hook keeps its queue. Required with AT, refused without |
USING, WHERE and AT read the trigger's row and nothing else: no source, no other feature, no REQUEST_TIME() or NOW(). A value several hooks need is a feature of the triggering statement, listed in its CAPTURE (…). A capture is computed in the same call, from the same reads, and is not returned to the caller ( CAPTURE ).
AT takes whole seconds, cast visibly: DATE_TRUNC(…, 'second')::TIMESTAMP(0). Another type is refused (UE/HOOK-AT-NOT-SECONDS). A cast to TIMESTAMP(0) rounds to the nearest second, half up: 10:00:59.5 gives 10:01:00. DATE_TRUNC truncates first, which is what a bucket boundary needs.
WITH
| Property | For | Takes | Default |
|---|---|---|---|
START | an event hook | Where its consumer starts on a partition that has no committed offset yet: 'earliest', 'latest', or an interval back from now (INTERVAL '1 HOUR'). It applies to the partitions the hook finds when it first subscribes. A partition added to the topic later is read from its beginning, whatever START says. Under 'latest', the index holds no record produced before the hook first got the partition | 'latest' |
POLICY | a scheduled hook | Which due time an entry keeps when it is queued again before it runs. 'earliest' keeps the earlier one, so a bucket's close does not move. 'latest' keeps the later one, a debounce: a burst pushes the run back, and it runs once after the burst. Under 'latest', a due time far in the future (an event stamped a year ahead) pins its entry there: guard the due time where it is computed | 'earliest' |
EVERY | a scheduled hook | How often its queue is drained, at least one second | the configuration's drain_every, 5 seconds |
EXPIRE | a scheduled hook | How long after its due time an entry may still run. An older entry is dropped, counted, and not run | required (UE/HOOK-AT-WITHOUT-EXPIRE) |
Changing EXPIRE, EVERY or POLICY with CREATE OR REPLACE keeps the queued entries. A change of the QUEUE, of the USING text or of the reference's types moves the queue, and drops its entries ( Queues and drains ).
Queues and drains
A scheduled hook's queue keeps one pending entry per reference, such as a merchant and a minute. Every call of the statement it is ON queues its reference, due at AT, so a minute's payments for one merchant fold into one entry.
- Queued again before it runs, an entry is folded by
POLICY. - Queued again after it ran, or while it runs, the reference gets a new entry, which runs again. Under
'earliest'it runs at the next drain, already past due. Under'latest'it runs at its new due time. - A late event queues its reference again with the same due time, already past, so it runs at the next drain if it is still within
EXPIRE. That run computes the whole reference again.
The queue lives in the store its QUEUE names and survives restarts. Any featuremeshd running the hook can drain it, one at a time, under a lease ( Leases ).
Every EVERY, the drainer runs the due entries in batches, until nothing is due. A batch's size is a setting of featuremeshd ( drain_batch_max ). The next drain starts one EVERY after the previous one ended. Without lag, an entry runs at its due time plus the wait for the next drain. Consumer lag, a backlog, a store failure or a lease handover add to that, without bound.
A drain reads its time T on the queue store's clock, in whole seconds, and takes the entries due at or before T. Each entry is checked against EXPIRE then:
| At the drain | The entry |
|---|---|
due ≤ T ≤ due + EXPIRE | runs |
T > due + EXPIRE | is dropped, unrun, and counted in entries_expired |
Everything before the drain counts against EXPIRE: the consumer's lag, the drain period, a backlog, a drain retried after a failure. Each attempt reads a new T, so the same limit covers an outage and a late event. How a drain fails, entry by entry, is in Failures in a drain .
A recompile that names another QUEUE, or changes the hook's USING text or its reference's types, moves the queue. The old entries are dropped and counted: entries_dropped in SHOW SERVING STATUS, DROPPED rows in SHOW SERVING WRITES, and five references sampled in featuremeshd's log. No migration keeps them, and a bucket not written yet stays missing until another event schedules that same reference ( Move a queue ).
Chains
A hook ON a statement fires after every hook run of that statement: an event hook's statement can schedule a minute rollup, whose statement schedules an hour rollup. Hooks on one statement run in no defined order. A cycle is refused (UE/HOOK-CYCLE). Serving calls fire no hook ( Limits ).
Create a hook and every hook ON its statement in one CREATE FEATURES. An event hook loaded before the scheduled hook on its statement indexes records without queueing their references, and those buckets are not scheduled until another event of the same bucket arrives.
Checked at registration
USING follows the statement's own grammar:
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.PAY_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p USING (p[payment_id], p[merchant_id]), p[amount], p[event_time]);A hook writes hot sinks only. Files, object stores and stdout:// are a logger's:
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.PAY_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p USING (p[payment_id], p[merchant_id], p[amount], p[event_time]) TO SINK('file:///tmp/fm_hook_ref'));A sink has one writer:
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAY_PS AT FM.TUTORIALS.HOOK_REF.MINUTE_CLOSE USING (FM.TUTORIALS.HOOK_REF.MINUTE_REF) TO FM.TUTORIALS.HOOK_REF.PER_MINUTE QUEUE SINK('postgresql://fm@postgres:5432/fm' TABLE 'other_queue' WITH (PASSWORD = SECRET('env', 'PG_PASSWORD'))) WITH (EXPIRE = INTERVAL '1 HOUR'));AT needs a statement trigger:
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAYMENTS AS p AT p[event_time] USING (p[merchant_id]) QUEUE FM.TUTORIALS.HOOK_REF.MINUTE_QUEUE WITH (EXPIRE = INTERVAL '1 HOUR'));EXPIRE has no default:
CREATE OR REPLACE FEATURE FM.TUTORIALS.HOOK_REF.BAD AS HOOK(RUN FM.TUTORIALS.HOOK_REF.MINUTE_PS ON FM.TUTORIALS.HOOK_REF.PAY_PS AT FM.TUTORIALS.HOOK_REF.MINUTE_CLOSE USING (FM.TUTORIALS.HOOK_REF.MINUTE_REF) QUEUE SINK('postgresql://fm@postgres:5432/fm' TABLE 'bad_queue'));REQUEST_SEED() is refused in a hook's statement (UE/HOOK-REQUEST-SEED): a retried record would draw another value.
Related
- Streams : the records an event hook reads.
- Sinks and reading back : what a hook writes, and how serving reads it.
- Delivery and failures : what a call sees, retries and tombstones.
- Configure featuremeshd : enabling hooks, consumer groups, replicas and leases.
- Limits .