Documentation
¶
Overview ¶
Package gateway is an HTTP endpoint that lands data.
It is NOT the engine, and the separation is the design rather than tidiness. `engine-weight.sh` states the rule it follows: "the data drivers -- pgx on the fetcher's side, BigQuery, S3, MySQL -- live in the TASKS' pods, which are other images". The engine orchestrates and never touches customer data; this does nothing else, on every request. So it is a module of its own, the way sdk/metrics/otelmeter is, and the engine's binary never links it.
The two also differ in every property that decides a design:
engine gateway shape batch, scheduled online, per request unit a run an event the SLO did the run finish p99 of POST, nothing lost on a 200 failure retry the run the client is already gone scaling one scheduler N stateless replicas
What it reuses, and it is most of the work ¶
Every `to/` driver in the SDK already takes a BATCH -- `Write(ctx, []Envelope, WriteOptions)` -- which is exactly what a micro-batching sink wants. So the gateway drives them directly, with no Pipeline around them, and inherits destinations that are already tested and already refuse what they cannot do.
It also inherits `ingestion_id`: the frozen UUID v5 over provider|entity|source_key|record_ts. A client that retries a POST produces the same id, so a sink with dedup absorbs the retry -- and a row landed here is the same row a batch fetcher would land for the same record.
Index ¶
- Constants
- Variables
- func BatchKeyOf(ctx context.Context) string
- func CheckTable(s Sink) error
- func CheckWrite(s Sink) error
- func DSNFrom(s Sink) (string, error)
- func DedupFor(write string) sdk.Dedup
- func IngestionMetricsEnabled() bool
- func Located(target, what string) (string, error)
- func Main(hooks *Hooks, opts ...Option)
- func Pattern(target string) string
- func Text(v any) string
- func WithBatchKey(ctx context.Context, key string) context.Context
- type Admitter
- type Auth
- type Buffer
- type Build
- type BulkClaimer
- type Config
- type Duration
- type Envelope
- type Flush
- type Hook
- type Hooks
- type Identity
- type JobAsker
- type JobNamer
- type Listen
- type LocateFunc
- type Manifest
- type ManifestDestination
- type ManifestField
- type ManifestStream
- type Measurer
- type Metastore
- type MetastoreConfig
- type MetastoreFunc
- type Metastores
- type Metering
- type Metrics
- type Naming
- type Option
- type Oversize
- type Reconciler
- type Reconciliation
- type Retry
- type Server
- type Shutdown
- type Sink
- type SinkFunc
- type Sinker
- type Sinks
- func (s *Sinks) Locate(sk Sink) (target string, known bool, err error)
- func (s *Sinks) MustRegister(name string, fn SinkFunc)
- func (s *Sinks) MustRegisterLocator(name string, fn LocateFunc)
- func (s *Sinks) Names() []string
- func (s *Sinks) Register(name string, fn SinkFunc) error
- func (s *Sinks) RegisterLocator(name string, fn LocateFunc) error
- type Size
- type StoreFunc
- type Stores
- type Stream
- type Target
Constants ¶
const ( CommunicationInternal = "internal" CommunicationExternal = "external" )
BREVIS_COMMUNICATION says which side of the network the gateway serves. Internal makes `listen.auth` optional -- declared, it is still enforced -- because a gateway only the cluster reaches is one internal teams integrate with without anybody handing out keys. External, the default, is the rule above. Like BREVIS_ENV it comes from the deployment and never from the file.
const ( ColumnOversize = "_oversize" ColumnOversizeArchive = "_oversize_archive" ColumnOversizeBytes = "_oversize_bytes" )
The fields an archived event carries into the stream, so the reduced record can be traced back to the whole one.
Stamped rather than left implicit. The alternative -- agreeing out of band that the id is also the object's name -- works until somebody changes the prefix, and then nothing says where to look.
const ( ColumnDeadLetterJobID = "_dead_letter_job_id" ColumnDeadLetterJobLocation = "_dead_letter_job_location" ColumnDeadLetterJobState = "_dead_letter_job_state" // ColumnDeadLetterBatch is the batch a buried row belonged to: the key the // send wrote under, which is also what a BigQuery load job was named after. // `gateway deadletter resend` sends under it again, so a job that landed is // adopted rather than written twice (#86). ColumnDeadLetterBatch = "_dead_letter_batch" // ColumnDeadLetterStream is the stream it came in on: a dead letter can // be shared, and the row is all whoever finds it has. ColumnDeadLetterStream = "_dead_letter_stream" )
The load job a buried row may already have been written by.
A sink that gives up waiting can be wrong about the outcome: a BigQuery load job keeps running, and can land. Issue #85 buried 88 rows that were already in the table. The job travels on the record so that whoever replays it -- by hand, or the console's resend -- can ask the warehouse first. The location is what BigQuery needs to find a regional job by name; the state is what was known when the row was buried.
const ( MetastoreMemory = "memory" MetastoreRedis = "redis" MetastoreMemcached = "memcached" )
The metastore backends.
const ( FormatJSON = "json" FormatArray = "array" FormatNDJSON = "ndjson" DurabilityMemory = "memory" // SinkAutoTable routes each event to the table its own payload names, // creating the table when it is absent. It writes nothing itself: `into` // names the destination that does. SinkAutoTable = "auto_table" SinkPubSub = "pubsub" SinkFiles = "files" SinkPostgres = "postgres" SinkBigQuery = "bigquery" SinkMySQL = "mysql" SinkRedshift = "redshift" )
const ( // WriteAppend adds rows and never looks at what is there. In Postgres that // is COPY FROM STDIN, which is its fast path: no per-row round trip, no // index lookup per row. // // Two deliveries of the same event land twice. That is correct for a log // and wrong for a table anybody counts, which is why it is named rather // than defaulted. WriteAppend = "append" // WriteMerge stages the batch into a temporary table and inserts it onto // the target with ON CONFLICT (ingestion_id) DO NOTHING, all inside one // transaction: BEGIN, CREATE TEMP … ON COMMIT DROP, COPY, INSERT, COMMIT. // A crash between any two of those leaves the table as it was. // // The FIRST delivery of an event wins. A redelivery is ignored, not // applied -- so a correction that arrives under the same ingestion_id does // not overwrite what is there. That is the right behaviour for an event, // which happened once and does not change, and the wrong one for a row // that carries a mutable state. // // It needs a UNIQUE index on ingestion_id, and the driver refuses without // one rather than silently appending -- which is the failure this mode // exists to prevent. WriteMerge = "merge" // WriteUpsert would be the other half: ON CONFLICT (ingestion_id) DO // UPDATE, where the LAST delivery wins. It is named here so the config can // refuse the word instead of accepting it and behaving like merge. // // Not implemented: it is a Dedup mode the SDK does not have, and adding // one means every writer -- BigQuery, MySQL, Redshift, Files, Pub/Sub -- // answers for it explicitly, or it becomes a silent append in whichever // one was missed. WriteUpsert = "upsert" )
How a row is written. The words are the ones a data engineer already uses, and each maps to what the driver actually does rather than to an intention.
const ( // Four deliveries at once. A batch is one round trip and mostly waiting, so // this is not a CPU number; it is how many outstanding calls a sink is // asked to carry, and four keeps a small pod from looking like a burst to // whatever is on the other side. // BigQueryFlushFloor is the shortest flush window a BigQuery sink may use. // // BigQuery allows 1,500 load jobs per table per DAY. The default window is // one second, which is 86,400 -- 57x the quota, exhausted in about // twenty-five minutes. It is not a problem for Pub/Sub, and the number came // from a Pub/Sub config, which is exactly how it would arrive here. // // Sixty seconds is 1,440 a day: inside the quota with room for a retry, and // it is Google's own framing of the limit. The real answer is the Storage // Write API, which is not written yet; until it is, the config refuses a // window it cannot honour rather than letting the first deploy find out. BigQueryFlushFloor = 60 * time.Second // BigQueryDailyLoadJobs is the quota BigQueryFlushFloor exists to protect: // load jobs per TABLE per day. Named rather than repeated, now that the // refusal and the boot budget both count against it. BigQueryDailyLoadJobs = 1500 )
Defaults, and each one is a number with a reason.
const ( MetricReceived = "brevis_gateway_events_received_total" MetricRejected = "brevis_gateway_events_rejected_total" MetricDropped = "brevis_gateway_events_dropped_total" MetricBatches = "brevis_gateway_batches_total" MetricBuried = "brevis_gateway_dead_letter_records_total" MetricSaturated = "brevis_gateway_saturated_total" MetricRefused = "brevis_gateway_requests_refused_total" MetricOversized = "brevis_gateway_oversized_total" MetricDelivery = "brevis_gateway_delivery_seconds" MetricBatchSize = "brevis_gateway_batch_records" MetricBuffer = "brevis_gateway_buffer_records" MetricQueue = "brevis_gateway_queue_batches" MetricFlushes = "brevis_gateway_flushes_total" // MetricReconciled is batches that landed AFTER the send window closed: // the load job finished, the gateway had stopped waiting, and reconcile // found it done (#85). A subset of batches_total{outcome="delivered"}, // which counts them too -- a counter of its own and not an outcome, so a // dashboard summing delivered does not change. How often it moves is how // often the window is shorter than the destination's queue. MetricReconciled = "brevis_gateway_reconciled_total" // MetricWindows is what became of each flush WINDOW when the claim is on. // // Its own series and not a label on MetricFlushes, because a yield is not // a flush: that counter's sum means "batches handed to the pool", and // folding a non-delivery into it would end that. // // Published only by a stream with `flush.claim`, so it is not noise on // every deployment that never turned this on. MetricWindows = "brevis_gateway_flush_windows_total" // MetricTableFlushes is flushes per TABLE, and it is the number the // BigQuery quota is actually about: 1,500 load jobs per table per day. // // MetricFlushes counts batches handed to the pool, and with a routing key // one batch is one table -- but it cannot say which, so a stream at 94 // tables reports one number against a limit that is per table. An // operator alerting before the quota bites needs the table. // // Behind the switch with the volume pair, and for the same reason: the // label is the producer's. The unconditional half of this question is the // boot line, which says what `flush.every` costs per table per day before // an event arrives -- one line and no cardinality. MetricTableFlushes = "brevis_gateway_table_flushes_total" // The three series behind the switch. // // They carry `table`, which is a label the PRODUCER chooses: with // auto_table one route becomes N tables, and every other metric in this // file is per stream precisely so nothing here grows with what a client // sends. `naming.pattern` and `max_new_per_hour` bound it, but bounded is // not the same as small, and a metrics bill is not something to opt // somebody into. // // So they are OFF unless BREVIS_INGESTION_METRICS says otherwise. The same // number is on every row in `brevis_received_bytes`, where it costs // storage instead of cardinality and answers history rather than now. MetricIngestedBytes = "brevis_gateway_ingested_bytes_total" MetricIngestedEvents = "brevis_gateway_ingested_events_total" )
The series the gateway reports, prefixed so they sit beside the engine's brevis_ and the SDK's brevis_sdk_ without colliding.
The units are in the names, because a number called `delivery_time` tells nobody whether it is seconds or milliseconds.
const ( ReasonHook = "hook_error" ReasonSourceKey = "no_source_key" ReasonRecordTS = "no_record_ts" ReasonIdentity = "identity" ReasonOversize = "oversize" ReasonAdmit = "sink_refused" )
Why a reason is a CLOSED enum and never the error text.
The rule is the SDK's, written where it costs the most: "a label whose value is a record id, a URL with a cursor, or a timestamp is how a metrics backend becomes the most expensive part of an installation." An error string is worse than all three -- it carries a table name, a column, sometimes a row -- and one malformed client would mint a new series per request.
The text belongs in the dead letter, on the record, where whoever has the events can read it. These say only which KIND of thing happened.
const ( ReasonBodyTooLarge = "body_too_large" ReasonMalformed = "malformed" ReasonEmpty = "empty" ReasonSaturated = "saturated" )
Why a request was turned away before any event existed.
A SECOND enum and not more values on the one above, because the two count different things and cannot share a denominator. `Reason*` is per EVENT and is attributed after `decode` has returned; these are per REQUEST, and three of the four happen to a body that never decoded at all. There is nothing to divide by.
`saturated` is here as well as in its own counter. The counter is a published series with somebody's alert written against it, so folding it in would move that alert in silence; carrying it twice costs one series and lets a single query answer "is anything being turned away".
const ( WonWindow = "won" YieldedWindow = "yielded" CeilingWindow = "ceiling" UnreachableWindow = "unreachable" )
What became of a flush window, when the claim is on.
WonWindow and YieldedWindow are the feature working: one replica flushes, the others keep filling. The other two are wins WITHOUT coordination, and they are why this series exists:
CeilingWindow max_age closed, so the batch left whatever anybody held.
Correct, and it says the ceiling is doing the work rather
than the target.
UnreachableWindow the backend could not be asked, so the claim failed
open. Coordination is OFF and the load jobs are multiplying
by replica count again -- silently, because every flush
still looks exactly like a flush. This is the one worth an
alert, and a feature whose failure mode is silent shipped
without a way to see it is the shape of issue #33.
const ( TriggerTime = "time" TriggerRecords = "records" TriggerSize = "size" )
What made a batch leave the buffer.
Its OWN counter rather than a label on MetricBatches, which already carries `sink` and `outcome`: a third dimension there would multiply the series for a question that belongs to the buffer and not to the delivery.
The one worth an alert is `size` on a stream that writes to BigQuery. That destination allows 1,500 load jobs per table per day, which is why the flush window has a 60-second floor -- and a size trigger walks past that floor, because the floor governs the timer alone. Nothing refuses it at load, since the arrival rate is not knowable there; this makes it visible instead.
const ( OutcomeDelivered = "delivered" OutcomeRetried = "retried" OutcomeBuried = "buried" )
Outcomes of one batch's delivery.
const AuthBearer = "bearer"
const ClaimTimeout = 500 * time.Millisecond
ClaimTimeout bounds the call the timer path makes to the metastore.
Short, because this runs while the pipe's lock is held: a backend that hangs would stop every request for this stream, which is a far worse outcome than the duplicate load job the claim exists to avoid.
Exported because a backend whose client takes no context cannot honour it as a context and has to honour it as a socket deadline instead. Memcached is that backend: `gomemcache.Add` has no ctx parameter, so before this number reached the driver the 500ms was decoration -- measured at a 2s backend, a Claim with a 500ms context returned in 2s, with the pipe's mutex held for all of it. One number, in one place, whichever way a driver has to obey it.
const ContentType = "text/plain; version=0.0.4; charset=utf-8"
ContentType is what a scraper expects. Version 0.0.4 is the text format Prometheus has served and parsed since 2014; OpenMetrics is a superset and scrapers accept this.
const DefaultMetastoreTTL = 60 * time.Second
DefaultMetastoreTTL is how long a cache entry lives when the file names no other. See MetastoreConfig.TTL for why it is a minute, and why `ttl: 0` -- which is a different thing from saying nothing -- means never.
const EnvIngestionMetrics = "BREVIS_INGESTION_METRICS"
EnvIngestionMetrics turns the per-table volume series on.
OFF by default, and that default is the point. Every other instrument in this file is labelled by things the OPERATOR wrote in a YAML file -- stream, sink, format, reason -- so the series count is known before the process starts. `table` is chosen by the PRODUCER: with auto_table one route becomes as many tables as they name, and `naming` bounds that rather than making it small.
Nobody should discover a metrics bill because they upgraded. The same number is on every row as `brevis_received_bytes` whether or not this is set, so the volume question is answerable either way -- this buys `now`, the column buys `since when` and `by whom`.
const EnvLocal = "local"
EnvLocal is the value that leaves the endpoint open, and it is spelled the same as the engine's so an operator learns one word.
Variables ¶
var ErrNoIdentity = errors.New("no identity")
ErrNoIdentity is a locate function's way of saying "this destination exists, and nothing in the configuration names it". The manifest lists it with no target and the reason, rather than failing or inventing a name.
Functions ¶
func BatchKeyOf ¶
BatchKeyOf returns the key ctx carries, or "" when it carries none.
func CheckWrite ¶
CheckWrite settles how rows land. One function for every table-shaped sink, because the question is the same everywhere and the answer has to be too: a `merge` that meant something different in MySQL than in Postgres would be one word with two meanings in the same file.
In all four it is the idempotent insert, and the FIRST delivery wins:
postgres INSERT … ON CONFLICT (ingestion_id) DO NOTHING mysql INSERT IGNORE bigquery MERGE … WHEN NOT MATCHED THEN INSERT redshift MERGE … WHEN NOT MATCHED THEN INSERT
func DSNFrom ¶
DSNFrom reads the connection string out of the environment variable the config named. The config carries the NAME; a DSN carries a password and the file is in git.
func DedupFor ¶
DedupFor turns the config's word into the SDK's mode.
CheckWrite already refused anything that is not one of the two words, so the default here is reached only by a driver that forgot to call it -- and DedupNone is the safe half of that mistake: it appends where it should have merged, which a UNIQUE index turns into a loud failure rather than a silent duplicate.
func IngestionMetricsEnabled ¶
func IngestionMetricsEnabled() bool
IngestionMetricsEnabled reads the switch. Anything strconv.ParseBool calls true is true -- `1`, `t`, `TRUE` -- and everything else, including an unset variable and a value nobody can parse, is false.
A bad value reads as OFF rather than failing the process: this is observability, and a typo here must not be the reason an ingestion endpoint does not start.
func Located ¶
Located turns a writer's answer into a locate function's: a writer that cannot name its destination says "" -- here that is an error naming what is missing, because a manifest with a hole in it would publish nothing and say nothing.
func Main ¶
Main runs a gateway from the config named on the command line.
It exists so a consumer's main is the registration and nothing else: the listener, the signals and the drain are the same every time, and a binary that has to re-derive them is a binary where one of them is forgotten.
The options are where the registration goes:
func main() {
sinks := gateway.NewSinks()
sinks.MustRegister(postgres.Sink, postgres.New)
sinks.MustRegister(files.Sink, files.New)
gateway.Main(nil, gateway.WithSinks(sinks))
}
That binary carries pgx and nothing else -- 10 MB against the 49 of one that registers all six. The import list is the selection, which is how database/sql has always worked.
func Pattern ¶
Pattern makes a table target the pattern of every table under its parent: bigquery://p/d/t becomes bigquery://p/d/*. A routing sink writes tables it learns from the events, so what it can publish is where they land.
func Text ¶
Text renders a JSON value as the text an attribute, an ordering key or a source key needs.
Exported because a sink driver lives in its own package now and a Pub/Sub attribute built with fmt.Sprint would not be the same string this gateway uses everywhere else.
It is NOT the SDK's asText, and the difference is deliberate: that one is frozen because IngestionID computes a UUID over its output, so changing it would rewrite every id ever written. This one is free to get stricter.
The case it exists for: JSON has one number type, so an id arrives as a float64 and fmt.Sprint renders 26130000 as 2.613e+07. An attribute carrying that filters nothing, and a source_key carrying it produces an ingestion_id for a record that does not exist.
Types ¶
type Admitter ¶
Admitter is a sink that can refuse ONE event before it is buffered.
Optional, and satisfied by structural typing: a sink that does not implement it admits everything, which is what every sink did before this existed.
It is the cure for the poison batch. A destination that can refuse an individual event -- `auto_table` refuses a table name outside its rules -- would otherwise refuse it at WRITE time, which fails the whole batch: one malformed event from one client buries the events of every other client in the same flush window, and none of them is told.
Here the refusal lands where per-event refusals already land: the event is rejected with its reason in the response, counted under its own label, and every well-formed event in the same request still lands.
type Auth ¶
type Auth struct {
// Type is `bearer` today. Empty means none, which is only allowed locally.
Type string `yaml:"type"`
// KeysFrom names the ENVIRONMENT VARIABLE holding the accepted keys, comma
// separated. The keys themselves are never in the file, which is the rule
// `secrets:` follows in a workflow and for the same reason: the file is in
// git.
KeysFrom string `yaml:"keys_from"`
}
Auth is who may write.
It mirrors what the engine does rather than inventing a second rule: BREVIS_ENV=local leaves the endpoint open, because asking for a token on every `docker compose up` only teaches a team to turn authentication off -- and outside local the process REFUSES TO START without one.
An ingestion endpoint is a write endpoint on somebody's topic or table. An unauthenticated one on a routable address is not a gateway with a gap, it is an open relay.
type Buffer ¶
type Buffer struct {
// Durability is what a 200 means. Today only "memory" exists and it says
// so: a tier that silently behaved like another would be the worst
// possible default for this field.
Durability string `yaml:"durability"`
Flush Flush `yaml:"flush"`
// Workers is how many batches this stream delivers at once.
//
// It exists because a delivery is I/O: one worker means a stream is as fast
// as one round trip to Pub/Sub or one COPY, no matter how many cores the
// pod has. It is bounded because the opposite -- a goroutine per batch --
// is a sink outage turning into unbounded memory and a thundering herd on
// the way back up.
//
// Zero takes the default, like every other number in this file. There is
// no way to ask for none, because a stream with no worker accepts events
// and delivers nothing.
Workers int `yaml:"workers"`
// Queue is how many full batches may wait for a worker.
//
// This is the shock absorber: a sink that pauses for a second does not
// reach the caller at all, it fills queue slots. When they are gone, the
// gateway says so -- see MaxRecords.
//
// Zero takes the default. A queue of none is expressible only as 1, which
// is near enough: with one worker busy, the second batch waits either way.
Queue int `yaml:"queue"`
// MaxRecords is the ceiling on events held in memory for this stream.
// Past it the gateway answers 503 instead of accepting.
//
// A 503 is the honest answer and an accepted event that is never delivered
// is not. It is also SAFE to retry here in a way it is not for most
// services: the ingestion_id is a frozen function of the event, so the same
// POST sent again is the same record, and a `merge` sink absorbs it.
MaxRecords int `yaml:"max_records"`
// MaxBytes is the same ceiling in BYTES, and it is the one that actually
// stops an OOM.
//
// A count cannot see this. `max_records: 40000` is 80 MB of 2 KB events
// and 80 GB of 2 MB ones, and until this field existed the config had no
// way to say which this stream holds -- so a producer who started sending
// the whole document instead of its id could take the pod down, and
// nothing in the file could have expressed the limit.
//
// It bounds the BUFFER and not one batch: `flush.size` shapes what leaves,
// this bounds what is held. Batches already queued for a worker, or in
// one, count until the sink is done with them, so a sink that is down
// cannot make `queue` x `flush.records` events pile up past this.
//
// Zero takes the default: 64 MiB, or more when `listen.max_body` or
// `flush.size` need it (4x the body, 2x the size) so one request and one
// batch always fit. It is never off: a ceiling that is off turns a slow
// sink into an OOM that loses every event already answered 202.
MaxBytes Size `yaml:"max_bytes"`
}
Buffer is the gap between accepting and delivering, and how honest a 200 is.
type Build ¶
type Build struct {
// Ctx bounds construction, which for a cloud driver means resolving
// credentials. It is the startup context, not a request's.
Ctx context.Context
// Sink is the YAML block, whole. The driver reads the fields that are its
// own and REFUSES the ones it needs and did not get -- which is why the
// per-driver checks live in the driver rather than in config.go.
Sink Sink
// Stores is the object-store backends this binary carries, keyed by
// scheme. Nil when none were registered, which is the ordinary case for a
// gateway that writes to local paths.
Stores *Stores
// Sinks is the registry this sink came from, so a driver that ROUTES can
// build the one it routes into -- through the same registry, which is what
// makes a binary that did not compile in BigQuery unable to route into it.
Sinks *Sinks
// Stream and Gateway name where this sink sits, so a driver can stamp them
// onto what it writes. A table fed by several routes still says which one
// wrote each line.
Stream string
Gateway string
// Meta is the shared state a routing driver keeps about tables: a cache
// of what exists, the debounce that keeps N replicas from all running the
// same DDL, and the counter behind max_new_per_hour.
//
// Never nil -- `memory` is the default and always available.
Meta Metastore
// Target is the table a routing driver wants created, when it wants one.
// Nil is the ordinary case: a sink named in the YAML writes to a table
// somebody already made.
Target *Target
}
Build is what a sink's constructor is handed.
A struct and not three arguments, because a driver added later will want something these do not carry, and growing a struct does not break the five drivers that came before it.
type BulkClaimer ¶
type BulkClaimer interface {
ClaimMany(ctx context.Context, keys []string, ttl time.Duration) ([]bool, error)
}
BulkClaimer is a metastore that can claim several keys in ONE round trip.
Optional, like Admitter and Measurer, and satisfied by structural typing: a store without it is asked one key at a time, which is what every store did before the trigger had keys.
It is not a convenience. The claim runs under `p.mu`, so its duration is admission's tail for every request that arrives during it -- and the loop below is the difference between 29.8ms and 2.589s on a Redis at 25ms RTT.
type Config ¶
type Config struct {
Name string `yaml:"name"`
Listen Listen `yaml:"listen"`
Metrics Metering `yaml:"metrics"`
Shutdown Shutdown `yaml:"shutdown"`
Streams []Stream `yaml:"streams"`
// contains filtered or unexported fields
}
Config is the whole gateway, and the file is the contract.
func Load ¶
Load reads and checks a config. Every refusal names the field and what is accepted: a gateway that starts on a file it half understood is one that drops events for a reason nobody can see.
func (*Config) DrainBudget ¶
DrainBudget is how long the drain may take.
Declared wins. Otherwise it is the longest flush window, floored at thirty seconds.
The window is the right quantity because it bounds what the buffer can be HOLDING when the signal arrives -- a 300-second stream can have 300 seconds of accepted events in memory, and the old fixed thirty was chosen when every window was one second.
One window and not two: the drain does not wait for anything. It takes the pending batch immediately and the workers deliver in parallel, so draining is strictly faster than the accumulating was. Giving it as long as the fill took is already generous, and doubling it only lengthens how long a pod that is genuinely stuck takes to die -- which is a rollout everybody waits on.
It is still a heuristic. What actually bounds the drain is the queue depth and the cost of one delivery, and neither is knowable here: a load job takes seconds, a file takes none. An installation that has measured its own should declare `shutdown.drain` and stop relying on this.
func (*Config) GracePeriod ¶
GracePeriod is what terminationGracePeriodSeconds has to be at least.
The gateway cannot read its own manifest, and Kubernetes' default is thirty seconds -- which equals the old fixed drain budget exactly, so there was no margin at all and a SIGKILL arrived while the drain was still inside its own deadline. It can at least state the number it needs, at boot, in the log whoever deploys it is already reading.
func (*Config) IdleTimeout ¶
IdleTimeout is how long a connection may sit unused, and it HAS A DEFAULT. [#44]
Go falls back to ReadTimeout when IdleTimeout is zero, and both were zero on both of this binary's listeners -- so it was not that idle connections lived a long time, they had no timeout at all. A connection opened on the first request of the day was still eligible at midnight, and the only thing that ever ended one was the client or a restart: a file descriptor per abandoned client, for the life of the process.
That is a DEFECT rather than a policy, which is why this one gets a default and why there is no way to turn it off. Somebody who wants effectively none sets a very long one, and it is then a number in their file rather than an absence nobody chose.
Ninety seconds is the reporter's own proposal, and it sits above the 30-to-60 most HTTP clients keep an idle connection for -- so it ends the ones nobody came back to without fighting the ones somebody will reuse.
func (*Config) MaxConnAge ¶
MaxConnAge is how long a client may keep one connection, and it is OFF unless the file says otherwise. [#44]
Unlike the idle timeout this is policy: it trades one in-cluster handshake per connection per age for load that spreads across replicas, and whether that trade is worth making depends on a deployment this binary cannot see. A default would be this process deciding it.
type Duration ¶
Duration is a time.Duration that also accepts a bare `0`.
YAML reads an unquoted number as an int and `time.Duration` wants a string, so `ttl: 0` -- the value the docs name for "never" -- was refused:
yaml: unmarshal errors: line 140: cannot unmarshal !!int `0` into time.Duration
Which is a Go type name in front of somebody who wrote a config file, about the one value this field's documentation told them to write. Found by a consumer copying it out of the changelog.
Zero is the ONE number where the unit adds nothing: zero seconds and zero hours are the same instant. Every other bare number is refused, and that is the other half of this type -- `ttl: 60` would be sixty NANOSECONDS under Go's own conversion, which nobody has ever meant. It says so rather than doing it.
type Envelope ¶
Envelope is what a sink receives, re-exported so an implementation of Sinker does not have to import the SDK to name the type it is handed.
type Flush ¶
type Flush struct {
// Every is the age at which a partial batch goes anyway, so a slow stream
// is not a stream that never lands.
Every time.Duration `yaml:"every"`
// Records is the count that sends one immediately.
Records int `yaml:"records"`
// Claim makes the flush clock belong to the DEPLOYMENT rather than to each
// process.
//
// `flush.every` is a `time.AfterFunc` in every replica, so the load jobs a
// table receives are a function of replica count and not of traffic:
//
// jobs / day / table = replicas × 86400 / every
//
// On BigQuery, against 1,500 per table per day, two replicas at 60s is
// 192% of a quota that cannot be raised -- before an HPA does anything.
// The gateway scales out for HTTP concurrency while the sink wants
// concentration, which is backwards from intuition and is why no static
// `every` fixes it: a value sized for maxReplicas makes a deployment at
// minReplicas pay the worst case's latency all day.
//
// With this on, a replica takes a set-if-absent claim for the stream and
// the window before flushing on the timer. One flush per window, whatever
// the replica count -- and it self-adjusts, because a replica only waits
// when another is actually competing.
//
// OFF by default, deliberately. It turns `every` from a promise into a
// target, and doing that silently to every deployment that happens to have
// a shared metastore is how `0.11.0` shipped a breaking change described
// as a free addition. It also requires `max_age`: a claim with no ceiling
// is latency with nothing bounding it.
//
// With `metastore: memory` it coordinates nothing, because every replica
// wins its own claim -- the same thing the DDL debounce does there. Issue
// #36.
Claim bool `yaml:"claim"`
// MaxAge is the age at which a partial batch goes REGARDLESS, and it is
// the promise `every` is not.
//
// `every` is a target: it is the age at which the gateway TRIES to flush.
// From the flush claim on (issue #36) a replica can lose that window to
// another and keep filling, so the target can be deferred. `max_age`
// cannot: no event waits longer than this, whatever the contention,
// whatever the backend, even with the metastore unreachable.
//
// The gap between the two is how much contention the deployment tolerates.
// `every` buys job economy -- on BigQuery the budget is 1,500 load jobs per
// table per day and a per-process clock spends `replicas ×` that -- and
// `max_age` bounds what that economy costs in latency.
//
// Zero leaves it off, which is what every existing config has. It must be
// at least `every`: a ceiling under the target would mean the target never
// applies, and the config says so rather than behaving that way.
MaxAge Duration `yaml:"max_age"`
// Size is the BYTE count that sends one immediately. Whichever of the
// three is crossed first wins; zero leaves this one off.
//
// It is measured on what arrived, not on what the batch weighs in memory
// -- a map[string]any is several times its JSON -- and a hook that
// inflates an event is not counted. An approximation, and the right one:
// it costs nothing to take, it moves with the payload, and the thing it
// guards against is a producer whose records grew tenfold.
//
// On BigQuery this is a CEILING and not a target. That destination allows
// 1,500 load jobs per table per day, which is why `every` has a 60-second
// floor -- and a size that fires every few seconds walks straight past
// that floor, because the floor only governs the timer. Nothing refuses it
// here, because the arrival rate is not knowable at load; instead every
// flush is counted by what triggered it, so `trigger="size"` climbing on a
// BigQuery stream is visible on a dashboard.
Size Size `yaml:"size"`
}
type Hook ¶
Hook is what runs on every event, and it is a plain Go function.
Returning nil DROPS the event, and that is a feature rather than an accident: filtering at the edge is most of what these do. It is counted, because an event dropped silently is indistinguishable from one lost.
An error sends that one event to the dead letter path and never fails the batch beside it. So does a panic: it is recovered per event, for the same reason -- one malformed record must not take down a process serving every other stream.
type Hooks ¶
type Hooks struct {
// contains filtered or unexported fields
}
Hooks is what this binary knows how to run.
Compiled in, and named by the YAML rather than pointed at. Measured before choosing: a Go function is 93 ns/op against Starlark's 959 and yaegi's 1,281, for nothing added to the binary -- and `plugin.Open` is not an option at all, because under CGO_ENABLED=0, which is the build every artifact here ships with, it returns "plugin: not implemented".
What it costs is worth saying where somebody will read it: adding a hook is a rebuild and a deploy, not a config change. That is the right trade while the hooks are written by the same people who ship the binary, and the wrong one the day a customer has to change one without a release.
func (*Hooks) MustRegister ¶
MustRegister is Register for a main that has nowhere to return an error.
type Identity ¶
type Identity struct {
Provider string `yaml:"provider"`
Entity string `yaml:"entity"`
SourceKey string `yaml:"source_key"`
RecordTS string `yaml:"record_ts"`
}
Identity is what becomes the ingestion_id, which is what makes a retried POST land once.
The four are the frozen formula's four, in its order. Provider and Entity are constants of the stream; SourceKey and RecordTS name FIELDS of the event, because they are the record's own identity and only it has them.
type JobAsker ¶
type JobAsker interface {
AskJob(ctx context.Context, job *sdk.LoadJobError, row map[string]any) (Reconciliation, error)
}
JobAsker asks what one buried row's load job became, for a resend (#86).
A Reconciler is asked about the failure a send just had. A resend has only the dead-letter row: the job on it and the row itself. A sink that can answer from the job alone needs nothing more than Reconcile -- AskJob falls back to it -- and a sink that writes many tables, like auto_table, reads which one off the row and asks that table's sink.
type JobNamer ¶
JobNamer is a sink whose failed write can name, per event, the load job that may still be writing it. See ColumnDeadLetterJobID.
Per event and not per batch, because one batch can be many jobs: auto_table writes each table with its own.
type Listen ¶
type Listen struct {
Addr string `yaml:"addr"`
// Auth is who may write. Outside BREVIS_ENV=local it is required, unless
// BREVIS_COMMUNICATION=internal.
Auth Auth `yaml:"auth"`
// MaxBody caps one request. Zero takes the default; a body past it is
// refused with 413 before a byte is parsed, because the alternative is a
// client deciding this process's memory.
MaxBody Size `yaml:"max_body"`
// IdleTimeout closes a connection that sits unused. Zero takes the
// default, and there is NO WAY TO TURN IT OFF -- see Config.IdleTimeout
// for why that is a correction rather than a missing knob. [#44]
IdleTimeout time.Duration `yaml:"idle_timeout"`
// MaxConnAge is how long a client may keep ONE connection before the
// next response asks it to redial. Zero is off, which is the default:
// this one is policy. See Config.MaxConnAge and listen.go. [#44]
MaxConnAge time.Duration `yaml:"max_conn_age"`
// contains filtered or unexported fields
}
type LocateFunc ¶
LocateFunc names a sink's destination from its configuration ALONE.
It is the constructor's twin for `gateway describe`, and the difference is the point: a constructor may resolve credentials or open a store, and describe runs in a deploy pipeline with no route to any warehouse. So a locate function only builds the SDK writer its constructor would build -- a struct, no client -- and asks it for its target. The SDK's Locate() stays the one place a target is built; the gateway never spells one itself.
The registry is passed so a routing driver can locate what it routes into through the same registry, which is what keeps a binary without a driver unable to describe it.
type Manifest ¶
type Manifest struct {
Kind string `json:"kind"`
Version int `json:"version"`
Gateway string `json:"gateway"`
GeneratedAt string `json:"generated_at"`
Streams []ManifestStream `json:"streams"`
}
Manifest is what `gateway describe` prints and `brevis gateway publish` stores: where each stream of this gateway lands, by name, never by address, and -- from version 2 -- how each stream is configured.
type ManifestDestination ¶
type ManifestDestination struct {
// Role is `sink`, `dead_letter`, or `archive` (where an oversized event's
// body is parked).
Role string `json:"role"`
// Kind is the sink's type as the config spells it.
Kind string `json:"kind"`
// Target is nil when the destination cannot be named: no locator in this
// binary, or nothing in the config that identifies it. Note says which.
Target *string `json:"target"`
Note string `json:"note,omitempty"`
// Routes marks a pattern: tables this sink learns from the events land
// under it.
Routes bool `json:"routes,omitempty"`
}
ManifestDestination is one sink of a stream.
type ManifestField ¶
type ManifestField struct {
Path string `json:"path"`
// Value is a string, a number, a bool or a list of them. Durations and
// sizes are written the way the file writes them -- `1m`, `256MiB` --
// and not as the integers Go holds them in.
Value any `json:"value"`
// Default marks a value the file did not write and the gateway filled
// in. Never set when there is no file to compare with.
Default bool `json:"default,omitempty"`
}
ManifestField is one setting of a stream, by the path the file spells it with: `buffer.flush.every`, `sink.into.write`.
type ManifestStream ¶
type ManifestStream struct {
Name string `json:"name,omitempty"`
Path string `json:"path"`
// Fields is the stream as it RUNS, defaults filled in, in the order the
// config declares them. See describeFields.
Fields []ManifestField `json:"fields,omitempty"`
// Notes are the file's comments, by the path of the setting they sit on.
// The comments are where a config says WHY, and a parser drops them.
Notes map[string]string `json:"notes,omitempty"`
Destinations []ManifestDestination `json:"destinations"`
}
ManifestStream is one stream: its destinations, and its configuration.
type Measurer ¶
Measurer is a sink that wants to know how many bytes each event arrived as.
Optional, like Admitter, and for the same reason: most sinks must not get this. A stream that lands in a topic or in a table somebody declared would have a field appear in its payload that nothing asked for -- a new key for every subscriber, or a column the table does not have and the load refuses. Only a sink that OWNS its table's shape can carry it, which today is `auto_table`.
The pipe calls this after the hook and after the oversize path, so the number is final, and it OVERWRITES whatever is on the event: the field name is the gateway's own, and a producer who sends it must not be able to forge their own volume.
The count is what ARRIVED on the wire, envelope included. It is not what the event weighs in memory, not what the destination stores, and not what a hook may have turned it into -- see Flush.Size, which is measured the same way and for the same reason.
It returns what this event's volume is ATTRIBUTED to: the table, for auto_table. The pipe owns the metrics and the sink owns the routing, so the name has to travel back rather than the metrics travelling in. Empty means "do not attribute", and the volume metrics are skipped for that event.
type Metastore ¶
type Metastore interface {
// Get returns what was stored, and whether anything was.
Get(ctx context.Context, key string) (string, bool, error)
// Put stores a value for ttl. A ttl of ZERO means the entry does not
// expire, and every backend has to mean it -- see MetastoreConfig.TTL.
//
// Only Put takes a zero that way. Claim and Incr are always given a
// positive window by their callers and must never be handed zero: a claim
// that does not expire is a lock, which this design refuses by name, and a
// counter that does not expire is a rolling window that never rolls.
Put(ctx context.Context, key, value string, ttl time.Duration) error
// Claim stores a marker only if the key is absent, and reports whether
// this caller is the one who stored it. Set-if-absent with an expiry: if
// the holder dies, the key expires and somebody else tries.
Claim(ctx context.Context, key string, ttl time.Duration) (bool, error)
// Incr adds one to a counter that expires, and returns the new value. The
// expiry is set when the counter is created and not extended, which is
// what makes a fixed window rather than one that never ends.
Incr(ctx context.Context, key string, ttl time.Duration) (int64, error)
// Describe names the backend, for a log and for an error.
Describe() string
}
Metastore is the shared state a gateway keeps ABOUT tables, not in them.
Four primitives, and the set is small on purpose: it is the intersection of what memory, Redis and memcached can all do atomically. Anything richer -- a rolling-window counter, a lock with a lease -- would work on one of them and be emulated badly on the others.
It is a CACHE and a COORDINATOR, never a source of truth:
- Get and Put hold what is known about a table, and may be wrong. The destination settles whether a table exists; N replicas racing to create one is the normal case and `AlreadyExists` is success.
- Claim is what makes several replicas behave like one. Ten of them detecting the same new field would be ten ALTERs against BigQuery's five metadata operations per table per ten seconds -- a quota gone and a retry storm. One Claim per field per window makes it one.
- Incr is the rolling-window counter behind `naming.max_new_per_hour`, which without it bounds a PROCESS and not a deployment.
Claim is a DEBOUNCE and not a lock, deliberately. A lock needs a lease, a lease needs a timeout, and a timeout too short splits the brain while too long stalls every replica behind one dead process. Losing a Claim costs a retry and nothing else, which is what Delta Lake and Iceberg do with optimistic commits and what Kafka Connect gets free from partition ordering.
An implementation must be safe for CONCURRENT use, including several calls to the same method. It always had to be safe across methods -- the router reads the cache from a worker while the timer claims a window -- and the per-key claim adds the rest: with no bulk primitive the fallback claims up to `claimFanout` keys at once, because doing it one at a time holds the buffer's lock for the sum of them.
func NewMemoryMetastore ¶
func NewMemoryMetastore() Metastore
NewMemoryMetastore is the default backend: this process, and nothing shared.
It is the DESIGN and not a limitation for a single replica. What it cannot do is coordinate: with N replicas each has its own, so Claim never debounces anything and `max_new_per_hour` bounds a process. The docs say so, and `redis` exists for exactly that.
type MetastoreConfig ¶
type MetastoreConfig struct {
// Type is the backend: `memory`, `redis` or `memcached`.
//
// `memory` is the default and needs nothing, which is the design rather
// than a limitation: a gateway that cannot start without Redis is a
// gateway with a new hard dependency for a cache. With ONE replica it is
// also the right answer.
//
// With several it gives each its own, so the debounce debounces nothing
// and `max_new_per_hour` bounds a process. That is the only reason the
// other two exist, and it is worth saying plainly: a shared backend does
// not make the gateway correct, it makes N replicas cheaper. The
// destination settles whether a table exists either way.
//
// Whether THIS binary carries one is a separate question, answered by the
// registry at startup, by name -- a slim build genuinely links neither.
Type string `yaml:"type"`
// TTL is how long the cache may be wrong, and `0` means never.
//
// A POINTER, because the three states are three -- the same reason
// `metrics.addr` is one. Absent takes the default; `ttl: 0` means the
// entry does not expire; a value is the value. A plain Duration collapses
// the first two, and "I did not mention ttl" and "I want this kept
// forever" must not be the same sentence.
//
// What the timer was defending against: a table dropped by hand outside
// the gateway makes every entry a lie. But the CLOCK is not what recovers
// from that -- `router.Write` is. A write that the destination refuses
// calls `invalidate`, which drops the entry immediately and lets the
// pipe's own retry come back against a cold cache. A dropped table costs
// one failed attempt, not a minute.
//
// So expiry is not the safety net it reads as, and it has a price: a miss
// charges `naming.max_new_per_hour` for a table that has existed for
// weeks, because `sinkFor` charges on BELIEF and not on creation. With a
// shared backend and a short TTL, a pod restarting a minute after a
// table's last event gets no benefit from the shared store at all -- which
// is the case the shared store exists for.
//
// Keeping the default at a minute anyway: an installation that has not
// thought about this should get the conservative behaviour, and the
// installation that has can say so in one field. Issue #35 is the
// argument, made by a consumer with 52 tables and a limit of 20.
// The type is `Duration` and not `time.Duration`, and that is the other
// half of the three states. `ttl: 0` is the value this comment names, and
// a plain time.Duration REFUSES it -- YAML reads a bare zero as an int --
// so the documented answer did not start the gateway. See Duration.
//
// It is the only duration in this file with that type, because it is the
// only one whose documented value is a bare number: `60s`, `500ms` and
// `2h` all carry their unit naturally, and there a bare number is a
// mistake worth refusing rather than a spelling worth accepting.
TTL *Duration `yaml:"ttl"`
// AddrFrom names the ENVIRONMENT VARIABLE holding a shared backend's
// address, never the address: it carries a password often enough, and this
// file is in git. Unused by `memory`, and REQUIRED by the other two --
// a shared backend with no address is a config that would quietly fall
// back to being alone.
AddrFrom string `yaml:"addr_from"`
}
Metastore is the cache of what is known about each table.
A CACHE and not a source of truth: the destination settles whether a table exists, and N replicas racing to create one is the normal case rather than the edge -- `AlreadyExists` is success. This only reduces the race.
func (MetastoreConfig) CacheTTL ¶
func (m MetastoreConfig) CacheTTL() time.Duration
CacheTTL is how long an entry lives. Zero means it does not expire.
Derived from the pointer and not from a field that `check` fills in, so a Config built in code -- a test, a consumer embedding the gateway -- gets the same answer as one that came through Load. A resolved field would have made "check did not run" and "the operator asked for never" the same zero, which is the exact confusion the pointer exists to prevent.
type MetastoreFunc ¶
MetastoreFunc opens a backend. `addr` is whatever the deployment put in the environment variable the config named -- never the config file, because an address carries a password often enough.
type Metastores ¶
type Metastores struct {
// contains filtered or unexported fields
}
Metastores is the backends this binary carries.
A registry for the same reason the sinks have one: a gateway that writes to a local table should not carry a Redis client, and a binary that did not compile one in should say so by name at startup rather than on the first table.
func NewMetastores ¶
func NewMetastores() *Metastores
func (*Metastores) MustRegister ¶
func (m *Metastores) MustRegister(name string, fn MetastoreFunc)
MustRegister is Register for a main with nowhere to return an error.
func (*Metastores) Open ¶
func (m *Metastores) Open(ctx context.Context, cfg MetastoreConfig) (Metastore, error)
Open builds the backend a config asked for.
`memory` is always available and needs no registration: it is the default, and a gateway that cannot start without Redis is a gateway with a new hard dependency for a cache.
func (*Metastores) Register ¶
func (m *Metastores) Register(name string, fn MetastoreFunc) error
Register adds one. A duplicate is refused rather than overwritten.
type Metering ¶
type Metering struct {
// Addr is its OWN address, and that is the whole design of this field.
//
// The ingest port is public by construction -- it is where clients POST --
// so `/metrics` on it would publish every stream name, path and
// destination to whoever finds the path. On a second address it is never
// in the Ingress at all.
//
// A POINTER, because the three states are three: absent takes the default,
// `addr: ""` serves nothing, and a value is the value. A plain string
// would collapse the first two, and "I turned metrics off" and "I did not
// mention metrics" must not be the same sentence.
Addr *string `yaml:"addr"`
// contains filtered or unexported fields
}
Metering is where the Prometheus exposition is served.
type Metrics ¶
type Metrics struct {
// contains filtered or unexported fields
}
Metrics is what the gateway counts.
Hand-written, with no dependency at all, and that is a measurement rather than a preference: the OpenTelemetry SDK costs 40 packages here and prometheus/client_golang 43, to report ten instruments whose exposition format is `name{label="value"} 42` and has not changed in a decade. The slim build exists to not pay for what it does not use, and metrics are in BOTH builds.
The engine made the same call one level up for the same reason, and its comment names the two things this gets wrong if written carelessly. Both have a test here:
- a histogram's buckets are RUNNING TOTALS in this format, not per-bucket counts. Backwards, it produces a chart that looks plausible and is wrong.
- a label value is quoted, so a quote, a backslash or a newline inside one ends the series early and corrupts every line after it.
func NewMetrics ¶
func NewMetrics() *Metrics
NewMetrics builds the instruments. A nil *Metrics records nothing and serves an empty scrape, which is what "metrics are off" has to look like: a valid scrape of a process with no metrics, not a 404 that reads as broken.
func (*Metrics) MetricsHandler ¶
MetricsHandler serves the exposition.
It is NEVER on the ingest mux, and the rule matters more here than it does in the engine: the gateway's port is public by design -- it is where clients POST -- so a /metrics on it would publish every stream name, path and destination to whoever finds the path.
type Naming ¶
type Naming struct {
// Pattern is the regular expression a name must match WHOLE. Empty takes
// defaultTableName, which is deliberately narrow.
Pattern string `yaml:"pattern"`
// Allow is an optional list of prefixes. Empty allows any name the pattern
// accepts; non-empty means a name must also start with one of these.
Allow []string `yaml:"allow"`
// MaxNewPerHour caps how many tables this stream may CREATE in an hour.
// A runaway producer stops at this number rather than at BigQuery's
// per-project quota, which is shared with everything else in the project.
//
// Zero takes the default. It bounds creations, never writes: a table that
// already exists is never rate limited.
MaxNewPerHour int `yaml:"max_new_per_hour"`
}
Naming is the boundary a producer writes inside.
Every field here is a refusal, and that is the point: `auto_table` turns a string in a payload into DDL, so the string is the whole of the attack surface. A gateway that creates whatever it is asked to create is a production dataset anybody in the cluster can fill.
type Option ¶
type Option func(*options)
Option adjusts a Server at construction.
func WithMetastores ¶
func WithMetastores(m *Metastores) Option
WithMetastores says which metastore backends this binary carries.
`memory` is always available and needs no registration: a gateway that cannot start without Redis is a gateway with a new hard dependency for a cache. Registering redis or memcached is what makes several replicas behave like one -- see gateway.Metastore.
func WithSink ¶
WithSink replaces one stream's destination.
It exists for the reason the SDK's drivers carry a Client field: "a publish that fails halfway is the case this driver is built around, and it cannot be produced on demand against a real topic". A sink that refuses, refuses twice then works, or is simply unreachable is exactly what the retry and the dead letter are for, and none of it can be arranged against a real one.
It is also the seam for a destination this does not ship: Sinker is exported, and a consumer with one of their own needs no fork.
func WithSinks ¶
WithSinks says which destinations this binary carries.
Without it a gateway registers none and refuses every stream by name, which is the honest default for a library: the sinks are Go, compiled in, and only the main that built the binary knows which ones it linked. cmd/gateway registers all six; cmd/gateway-slim registers two.
func WithStores ¶
WithStores says which object-store backends this binary carries, by scheme.
Separate from WithSinks because a scheme is not a destination: `files` is one sink that writes to a directory, to gs:// and to s3://, and a build that only ever writes locally should not carry the AWS SDK to do it.
type Oversize ¶
type Oversize struct {
// LargerThan is the per-EVENT ceiling, measured on the encoded payload
// after the hook has run. Distinct from listen.max_body, which caps a
// whole REQUEST and refuses with 413 before anything is parsed.
LargerThan Size `yaml:"larger_than"`
// Archive is where the whole event goes. It is an ordinary sink, so this
// is a directory on a laptop and a bucket in production with no second
// idea of what a path is.
Archive Sink `yaml:"archive"`
// Hook names a second hook, which receives the oversized event and
// returns the reduced one. It is Go, compiled in, like every other hook:
// which fields are heavy is domain knowledge and a YAML file cannot hold
// it.
//
// Without one the event is ARCHIVED AND DROPPED from the stream -- not
// lost, because the archive has it whole, and counted, because an event
// that silently stops arriving is the worst outcome here.
Hook string `yaml:"hook"`
}
Oversize is the claim-check path: an event too large is written somewhere whole, and what continues into the stream is a reduced version that points back at it.
It is a named pattern -- Enterprise Integration Patterns calls it Claim Check -- and the reason it beats a flat refusal is that a 413 loses the event. An oversized payload is usually the most interesting one somebody has: it is the request with the whole document attached, and refusing it throws away the case worth debugging.
type Reconciler ¶
type Reconciler interface {
Reconcile(ctx context.Context, cause error) (Reconciliation, error)
}
Reconciler is a sink that can say, after giving up on a write, whether it landed after all.
Optional, like Admitter. It exists because giving up is not the same as failing: a BigQuery load job keeps running after the gateway stops waiting for it, and it can succeed. Issue #85 buried 88 events that were already in the table. A sink whose write cannot outlive the call -- a topic publish, a SQL statement -- has nothing to reconcile and does not implement this.
cause is what Write returned, or an earlier attempt's error when that one named a job and the last did not. Landed is true only when the sink KNOWS the batch is in the destination; anything less, including an error asking, and the batch goes to the dead letter as before.
type Reconciliation ¶
type Reconciliation struct {
Landed bool
// Cause is what to bury the batch with when it did not land: the cause it
// was asked about, refined by what the sink found out -- a job that ended
// with an error, a table that did land. The dead-letter row is stamped
// from it, so it says what is true now rather than when the wait ended.
Cause error
}
Reconciliation is what a Reconciler learned.
func AskJob ¶
func AskJob(ctx context.Context, s Sinker, job *sdk.LoadJobError, row map[string]any) (Reconciliation, error)
AskJob asks a sink what a buried row's job became: through JobAsker when the sink is one, through Reconcile otherwise. A sink that is neither cannot say, and that is an error rather than a guess.
type Retry ¶
type Retry struct {
// Attempts counts the FIRST try. 1 means no retry at all.
Attempts int `yaml:"attempts"`
// Backoff is the wait before the second attempt; it doubles from there,
// with jitter. Bounded by MaxBackoff.
Backoff time.Duration `yaml:"backoff"`
MaxBackoff time.Duration `yaml:"max_backoff"`
}
Retry is the sink's second, third and fourth chance.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the gateway listening.
func New ¶
New wires a config to the hooks this binary carries.
Everything that can fail does so HERE and not on a request: an unknown hook, an unknown sink, a bad path. A gateway that starts on a file it half understood drops events for a reason nobody can see.
func (*Server) Close ¶
Close drains every stream. What is in a buffer at shutdown is delivered, not dropped: `memory` already loses on a crash, and losing on a clean stop as well would make the tier useless rather than merely limited.
func (*Server) Handler ¶
Handler is the gateway's routes, behind the guard.
The guard wraps the MUX and not each stream: a path that is not a stream must answer 401 as well, or an unauthenticated caller learns which paths exist by reading the status codes.
type Shutdown ¶
type Shutdown struct {
// Drain is the budget for emptying every stream's buffer.
//
// Zero derives it from the flush windows -- see DrainBudget -- because the
// two are the same quantity seen from opposite ends: a 300-second window
// can be holding 300 seconds of events when the signal arrives, and a
// fixed thirty was a number chosen when every window was one second.
Drain time.Duration `yaml:"drain"`
}
Shutdown is how long a clean stop may take.
It matters more than it looks, because the gateway answers 202 before anything is written: what is in a buffer at SIGTERM is delivered by the drain, and a drain that runs out of time loses events a producer was told had been accepted.
type Sink ¶
type Sink struct {
Type string `yaml:"type"`
// Project and Topic are Pub/Sub's. Named here rather than in a nested block
// per type because one sink is declared per stream, and a block that holds
// one thing is a level of nesting that buys nothing.
Project string `yaml:"project"`
Topic string `yaml:"topic"`
// Attributes names FIELDS of the event that become message attributes.
//
// The driver takes a function, and a YAML file cannot carry one. What it
// can carry is which of the client's own fields travel beside the payload
// -- which keeps the rule the driver was built on: the topic's contract
// belongs to whoever owns the topic, and nothing is invented here.
Attributes []string `yaml:"attributes"`
// Dataset is BigQuery's. Project is shared with Pub/Sub above -- both are
// the GCP project, and giving them one name keeps a file from saying the
// same thing twice.
Dataset string `yaml:"dataset"`
// StagingBucket is where BigQuery stages a batch larger than the inline
// limit. Empty lets the driver default it to <project>-brevis-staging.
StagingBucket string `yaml:"staging_bucket"`
// Staging is Redshift's S3 prefix, and it is REQUIRED for that sink:
// there is no inline path into Redshift. It is a columnar database and a
// row-by-row INSERT pays the cost of a block, so the only workable load is
// COPY from S3.
Staging string `yaml:"staging"`
// IAMRole is the role the Redshift cluster assumes to read that prefix.
//
// A role and not an access key, which the driver will not accept at all: a
// key in a COPY's URL ends up in the cluster's query log, and plenty of
// people read that.
IAMRole string `yaml:"iam_role"`
// Path is where `files` writes: a directory, gs:// or s3://.
Path string `yaml:"path"`
// DSNFrom names the ENVIRONMENT VARIABLE holding the connection string,
// never the string. A DSN carries a password and this file is in git --
// the same split `secrets:` makes in a workflow.
DSNFrom string `yaml:"dsn_from"`
// Table is schema-qualified: `landing.clicks`.
Table string `yaml:"table"`
// Write is `append` or `merge`. Required for a table, because the right
// answer depends on what the table is FOR and only its owner knows.
Write string `yaml:"write"`
// OrderingKey names the field whose value orders the messages. Empty is no
// ordering, which is the default and what every other destination gives.
OrderingKey string `yaml:"ordering_key"`
// TableFrom exists only so the word can be REFUSED by name.
//
// v1 let the stream choose which field named the table. v2 does not: the
// envelope names it in `table_name`, always, and a setting that could point
// somewhere else would make the one fixed contract negotiable per stream.
//
// Keeping the field means a file carrying it gets a sentence saying what
// replaced it. Deleting it would make `table_from` an unknown key, and
// KnownFields would refuse the file with "field table_from not found" --
// true, and no help at all to somebody upgrading.
TableFrom string `yaml:"table_from"`
// Naming bounds what a producer may ask for. Without it, a table name is a
// namespace nobody reviewed and a typo is a new table rather than an error.
Naming Naming `yaml:"naming"`
// Shape decides what the RECORD contributes to the row: `document` puts it
// whole in one JSON column, `columns` gives each field a column of its
// own.
//
// One contract for the producer either way -- the envelope never changes.
// What changes is what the operator's table looks like, which is their
// decision and not the producer's.
Shape string `yaml:"shape"`
// Metastore caches what is known about a table, so a per-event write does
// not become a per-event lookup -- and, from issue #36, coordinates the
// flush clock across replicas.
//
// It belongs to the STREAM even though it is written here, and it is
// opened for every stream whatever the sink. It used to be VALIDATED only
// under `auto_table`, so a direct `bigquery` stream naming redis with no
// `addr_from` started happily and coordinated with nobody. `Stream.check`
// validates it now, once, for the stream's own sink -- a dead letter and
// an oversize archive are Sinks too and neither has one.
Metastore MetastoreConfig `yaml:"metastore"`
// Into is the real destination, one per table. A nested sink, because
// `auto_table` routes and does not write: the four columns it lands are
// the same in Postgres (JSONB), MySQL (JSON), BigQuery (JSON) and Redshift
// (SUPER), so which of them receives the rows is a separate choice from
// the routing.
Into *Sink `yaml:"into"`
}
Sink is the destination.
type Sinker ¶
type Sinker interface {
Write(ctx context.Context, batch []sdk.Envelope) (int64, error)
Describe() string
}
Sinker is one destination, and it is the SDK's own Writer narrowed to what this needs.
Narrowed rather than reused whole so a test can supply one without a cloud account, and so the gateway never grows a second idea of what a destination is: every implementation shipped here IS an sdk driver.
type Sinks ¶
type Sinks struct {
// contains filtered or unexported fields
}
Sinks is what this binary knows how to write to.
It is the hook registry's twin, and for the twin reason. A `switch` naming every constructor -- which is what this was -- makes the linker keep every driver, so a gateway that only ever writes to Postgres still carried the AWS SDK, the Google stack and Arrow: 48.9 MB against 10.0 for the same gateway with only what it uses.
The import list is the selection. That is how database/sql has always worked, and it is already the rule one level down: sdk/store/s3 says "importing it costs you the AWS SDK" precisely so a fetcher reading GCS does not pay for it.
The published image registers all six. A binary of your own registers what it needs -- and anybody with a hook is compiling one already, so for them this costs nothing.
func (*Sinks) Locate ¶
Locate names the destination of one sink block. `known` is false when this binary carries no locator for the sink's type: the manifest then lists the sink with no target, as unidentified, rather than leaving it out.
func (*Sinks) MustRegister ¶
MustRegister is Register for a main with nowhere to return an error.
func (*Sinks) MustRegisterLocator ¶
func (s *Sinks) MustRegisterLocator(name string, fn LocateFunc)
MustRegisterLocator is RegisterLocator for a main.
func (*Sinks) Register ¶
Register adds one. A duplicate name is REFUSED rather than overwritten, the same as a hook: a silently replaced registration is a bug that shows up in production, when the wrong driver runs.
func (*Sinks) RegisterLocator ¶
func (s *Sinks) RegisterLocator(name string, fn LocateFunc) error
RegisterLocator adds one, refusing a duplicate as Register does.
type Size ¶
type Size int64
Size is a byte count written the way an operator writes one: 1MiB, 512KiB, 2GiB, or a plain number.
A plain int would have worked, and `max_body: 1048576` is a number nobody reads twice and everybody miscounts once.
type Stores ¶
type Stores struct {
// contains filtered or unexported fields
}
Stores is the object-store backends this binary carries, by URL scheme.
Separate from Sinks because a scheme is not a destination: `files` is one sink that writes to a directory, to gs:// and to s3://, and which of the three a deployment needs is not what its sink type says. Keeping them apart is what lets a slim build have `files` for its dead letter without the AWS SDK -- 10.0 MB against 13.5.
func (*Stores) MustRegister ¶
MustRegister is Register for a main with nowhere to return an error.
func (*Stores) Open ¶
Open returns the backend a path needs, or nil for a local path.
The refusal is the useful part: a path with a scheme this binary has no backend for fails HERE, at startup, naming the scheme and what is carried. Before the registry existed the same mistake failed on the first WRITE -- and for a dead letter that means "the dead letter refused them too, and they are lost".
type Stream ¶
type Stream struct {
Name string `yaml:"name"`
// Path is where it listens. It must start with "/" and must not collide
// with another stream's: two streams on one path is a silent winner.
Path string `yaml:"path"`
// Format says how to read the body. Declared, never sniffed: guessing is
// how a batch of a thousand becomes one row holding an array.
//
// json one object
// array a JSON array of objects
// ndjson one object per line
Format string `yaml:"format"`
Identity Identity `yaml:"identity"`
// Hook names a function registered in THIS binary, not a file. The hook is
// Go and compiled in -- see the registry for what that buys and what it
// costs. Empty means the event goes through untouched.
Hook string `yaml:"hook"`
// StampLoadedAt writes ingestion_loaded_at onto the payload: when the
// gateway received it, UTC, RFC3339.
//
// Opt-in, because it adds a field to every record and a topic's
// subscribers and a table's columns both notice. The same column name and
// the same format the SDK writes, so a row this gateway lands and a row a
// pipeline lands stay the same shape.
StampLoadedAt bool `yaml:"stamp_loaded_at"`
// Oversize is what happens to an event too big for the destination.
Oversize *Oversize `yaml:"oversize"`
Buffer Buffer `yaml:"buffer"`
Sink Sink `yaml:"sink"`
// Retry is how hard the sink is tried before a batch is given up on.
Retry Retry `yaml:"retry"`
// DeadLetter is where a batch goes when the sink will not take it.
//
// Without one, a sink that refuses is a log line and nothing else -- which
// is losing data quietly, and the one failure an ingestion service exists
// to not have. A stream that declares none is REFUSED rather than defaulted
// to silence: where the unacceptable goes is the operator's decision, and
// having to make it is the point.
DeadLetter Sink `yaml:"dead_letter"`
// contains filtered or unexported fields
}
Stream is one endpoint and where what arrives at it goes.
type Target ¶
type Target struct {
// Schema is the columns, with types. It is also what a later `evolve`
// compares against.
Schema sdk.Schema
// PartitionBy names the column a created table is partitioned on, by day.
// Empty creates an unpartitioned table, which for a landing table is a
// query bill that grows forever.
PartitionBy string
// ClusterBy names the columns a created table is clustered on.
ClusterBy []string
// DedupKey is the column a `merge` matches on. Empty means the SDK's
// `ingestion_id`, which is what a declared stream writes; a router that
// names its own identity column says so here.
DedupKey string
// Evolve says what a load may do to a table that EXISTS and no longer
// matches Schema. The zero value refuses any difference, which is what
// every driver has always done.
//
// sdk.EvolveAdditive adds a declared column the table lacks. It never
// drops and never narrows -- see core.Evolution for why there is no third
// mode.
Evolve sdk.Evolution
// Create lets the driver create the table when it is absent. Off by
// default everywhere else, because a loader that creates tables by
// accident turns a typo into a second table nobody is reading.
Create bool
}
Target is the shape a driver should create, when the caller knows it and the YAML does not.
It exists for `auto_table`, which turns a string in a payload into a table and therefore has to say what that table looks like. Everything here is the ROUTER's decision and never the producer's: a producer that could choose the schema could choose a partition column it controls.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
gateway
command
Command gateway is the published gateway: no hooks.
|
Command gateway is the published gateway: no hooks. |
|
gateway-slim
command
Command gateway-slim is the published gateway with two sinks instead of six.
|
Command gateway-slim is the published gateway with two sinks instead of six. |
|
A gateway with a hook: register what this binary knows, hand it the file.
|
A gateway with a hook: register what this binary knows, hand it the file. |
|
metastore
|
|
|
memcached
Package memcached is the memcached backend for a gateway's metastore.
|
Package memcached is the memcached backend for a gateway's metastore. |
|
redis
Package redis is the Redis backend for a gateway's metastore.
|
Package redis is the Redis backend for a gateway's metastore. |
|
sink
|
|
|
autotable
Package autotable routes each event to the table its own envelope names, and creates that table when it is absent.
|
Package autotable routes each event to the table its own envelope names, and creates that table when it is absent. |
|
bigquery
Package bigquery writes a gateway's batches into a BigQuery table.
|
Package bigquery writes a gateway's batches into a BigQuery table. |
|
files
Package files writes a gateway's batches as NDJSON objects.
|
Package files writes a gateway's batches as NDJSON objects. |
|
mysql
Package mysql writes a gateway's batches into a MySQL table.
|
Package mysql writes a gateway's batches into a MySQL table. |
|
postgres
Package postgres writes a gateway's batches into a Postgres table.
|
Package postgres writes a gateway's batches into a Postgres table. |
|
pubsub
Package pubsub publishes a gateway's batches to a Google Pub/Sub topic.
|
Package pubsub publishes a gateway's batches to a Google Pub/Sub topic. |
|
redshift
Package redshift writes a gateway's batches into a Redshift table, through S3.
|
Package redshift writes a gateway's batches into a Redshift table, through S3. |
|
store
|
|
|
gcs
Package gcs registers the Google Cloud Storage backend for a gateway's `files` sink.
|
Package gcs registers the Google Cloud Storage backend for a gateway's `files` sink. |
|
s3
Package s3 registers the S3 backend for a gateway's `files` sink and for Redshift's staging prefix.
|
Package s3 registers the S3 backend for a gateway's `files` sink and for Redshift's staging prefix. |