SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
Types
Domain types in pkg/types/<domain>/ live on three serialization boundaries — inbound HTTP, outbound HTTP, and SQL — on top of an in-memory domain representation. SigNoz's convention is core-type-first: every domain defines a single canonical type X, and specialized flavors (PostableX, GettableX, UpdatableX, StorableX) are introduced only when they actually differ from X. This guide spells out when each flavor is warranted and how they relate to each other.
Before reading, make sure you have read abstractions.md — the rules here build on its guidance that every new type must earn its place.
The core type is required
Every domain package in pkg/types/<domain>/ defines exactly one core type X: AuthDomain, Channel, Rule, Dashboard, Role, PlannedMaintenance. This is the canonical in-memory representation of the domain object. Domain methods, validation invariants, and business logic hang off X — not off the flavor types.
Two rules shape how the core type behaves:
Conversions can be either
New<Output>From<Input>or a receiver-style(x *X) ToY()method. Either form is fine; pick whichever reads best at the call site:// Constructor form func NewGettableAuthDomainFromAuthDomain(d *AuthDomain, info *AuthNProviderInfo) *GettableAuthDomain // Receiver form func (maintenance *PlannedMaintenanceWithRules) ToPlannedMaintenance() *PlannedMaintenanceXcan double as the storage row when the DB shape would be identical.Channelembedsbun.BaseModeldirectly, and there is noStorableChannel. This is the preferred shape when it works.
Domain packages under pkg/types/ must not import from other pkg/ packages. Keep the core type's methods lightweight and push orchestration out to the module layer.
Add a flavor only when it differs
For each of the four flavors, create it only if its shape diverges from X. If a flavor would have the same fields and tags as X, reuse X directly, or declare a type alias. Every flavor must earn its place per abstractions.md rule 6 ("Wrappers must add semantics, not just rename").
| Flavor | Create it when it differs in… |
|---|---|
PostableX |
JSON shape differs from X — typically no Id, no audit fields, no server-computed fields. Often owns input validation via Validate() or a custom UnmarshalJSON. |
GettableX |
Response shape adds server-computed fields that are not persisted — e.g., GettableAuthDomain adds AuthNProviderInfo, which is resolved at read time. |
UpdatableX |
Only a strict subset of PostableX is replaceable on PUT. If the updatable shape equals PostableX, reuse PostableX. |
StorableX |
DB row shape differs from X — usually X carries nested typed config while StorableX carries a flat Data string JSON column, plus bun tags, audit mixins, and an OrgID. If X already has those, skip the flavor. |
The failure mode this rule exists to prevent: minting all four flavors on reflex for every new resource, even when two or three are structurally identical. Each unnecessary flavor is another type contributors must understand and another conversion that can drift.
Worked examples
Channel — core type only
type Channels = []*Channel
type GettableChannels = []*Channel
type Channel struct {
bun.BaseModel `bun:"table:notification_channel"`
types.Identifiable
types.TimeAuditable
Name string `json:"name" required:"true" bun:"name"`
Type string `json:"type" required:"true" bun:"type"`
Data string `json:"data" required:"true" bun:"data"`
OrgID string `json:"orgId" required:"true" bun:"org_id"`
}
Channel is both the domain type and the bun row. GettableChannels is a type alias because *Channel already serializes correctly as a response. There is no StorableChannel, PostableChannel, or UpdatableChannel — those would be identical to Channel and so do not exist. Prefer this shape when it works.
AuthDomain — all four flavors
type AuthDomain struct {
storableAuthDomain *StorableAuthDomain
storableAuthDomainConfig *StorableAuthDomainConfig
}
type StorableAuthDomain struct {
bun.BaseModel `bun:"table:auth_domain"`
types.Identifiable
Name string `bun:"name"`
Data string `bun:"data"` // StorableAuthDomainConfig serialized as JSON
OrgID valuer.UUID `bun:"org_id"`
types.TimeAuditable
}
type PostableAuthDomain struct {
Name string `json:"name" required:"true"`
Enabled bool `json:"enabled"`
Config AuthDomainConfig `json:"config" required:"true"`
RoleMapping *RoleMapping `json:"roleMapping"`
}
type UpdatableAuthDomain struct {
Enabled bool `json:"enabled"` // Name intentionally absent
Config AuthDomainConfig `json:"config" required:"true"`
RoleMapping *RoleMapping `json:"roleMapping"`
}
type GettableAuthDomain struct {
StorableAuthDomain
Enabled bool `json:"enabled"`
Config AuthDomainConfig `json:"config"`
RoleMapping *RoleMapping `json:"roleMapping"`
AuthNProviderInfo *AuthNProviderInfo `json:"authNProviderInfo"`
}
Each flavor exists for a concrete reason:
StorableAuthDomainstores the typed config as an opaqueData stringcolumn, so the schema does not need to migrate every time a config field is added.PostableAuthDomaincarries the config as a structured object (not a string) for the request;AuthDomainConfigis a kind/spec envelope.UpdatableAuthDomainexcludesNamebecause a domain's name cannot change after creation.GettableAuthDomainaddsAuthNProviderInfo, which is derived at read time and never persisted.
The core AuthDomain holds the two live halves — storableAuthDomain and storableAuthDomainConfig — and owns business methods such as Update(updatable) and Patch(patchable). Conversions use the New<Output>From<Input> form: NewAuthDomainFromPostableAuthDomain, NewAuthDomainFromStorableAuthDomain, NewGettableAuthDomainFromAuthDomain.
Sum types: the kind/spec envelope
When a domain type is a sum type — exactly one of several variants, selected by a discriminator — model it as an envelope with a kind and a spec:
type FooConfig struct {
Kind FooKind `json:"kind" required:"true"`
Spec any `json:"spec" required:"true"`
}
{ "kind": "bar", "spec": { "url": "...", "timeout": "30s" } }
Kind is a valuer.String enum implementing Enum(); Spec holds exactly one concrete variant type (BarSpec, BazSpec, …). RuleThresholdData and EvaluationEnvelope in pkg/types/ruletypes/ are the canonical in-tree examples; the dashboard panel/query/variable plugins in pkg/types/dashboardtypes/ are the same pattern behind generics. (QueryEnvelope in querybuildertypes uses type as the discriminator key for historical reasons; new envelopes use kind.)
The envelope goes at the point of variance, not the resource root
Put the envelope on the field that actually varies. The resource root is almost never a sum type — a Foo has a name and an enabled flag regardless of which kind it is configured with; only its configuration varies, so the envelope is the config field:
{ "name": "my-foo", "enabled": true, "config": { "kind": "bar", "spec": { "...": "..." } } }
Hoisting kind/spec to the root would turn the whole resource into a oneOf: every flavor (PostableFoo, UpdatableFoo, GettableFoo) then needs one variant schema per kind, each repeating the common fields; every new common field has to be added to all of them; and generated clients get unions of large objects instead of one small union that narrows on config.kind. A root-level kind also collides with the resource-model meaning of the word — root kind conventionally answers "what resource is this" (Dashboard), never "which flavor of config does it hold".
The existing domains already follow this placement:
- Rules — plain root; envelopes on the varying fields:
thresholds: {kind, spec}andevaluation: {kind, spec}. - Dashboards — metadata at the root plus one typed
spec; the unions sit deep inside, at each panel/query/variable plugin ({kind, spec}inperses_plugin_wrappers.go). - Saved views — root
{schemaVersion, spec}, wherespecis a versioning envelope holding one fixed type, not a union; the unions are inside it (spec.queries: [{type, spec}]). Same word, different job — a versioned body is not a discriminated union.
Why this tagging style
Of the union encodings in common use, the envelope is the adjacently tagged one — tag and payload side by side. Variant payloads stay collision-free, and each kind maps to a named wrapper schema that carries the discriminator, which is exactly what OpenAPI generators need. The alternatives lose on those points: internally tagged ({"kind": "bar", ...fields flattened}) mixes common and variant fields, admits cross-variant key collisions, and forces every variant schema to redeclare the discriminator; sibling optional fields ({"kind": "bar", "barConfig": {}, "bazConfig": {}}) is the anti-pattern the first rule below exists to prevent.
The rules that make the envelope work:
Never model variants as sibling fields. A struct with
Bar *BarSpec,Baz *BazSpecnext to a discriminator cannot be expressed as an OpenAPI discriminated union, forces nilability checks on every consumer, and silently admits contradictory payloads (kind=bar with a baz spec). The chosen variant is the payload.The envelope owns
UnmarshalJSON. Decodekindfirst, then switch on it to decode and validate the matching concrete type intoSpec. Unknown kinds and missing specs are rejected at the boundary:func (typ *FooConfig) UnmarshalJSON(data []byte) error { var raw map[string]json.RawMessage // ... unmarshal raw, decode raw["kind"] ... switch kind { case FooKindBar: spec := BarSpec{} if err := json.Unmarshal(raw["spec"], &spec); err != nil { return err } typ.Spec = spec // ... one case per kind, default rejects ... } typ.Kind = kind return nil }Consumers type-assert on
Spec(config.Spec.(BarSpec)) after switching onKind. If assertion sites multiply, add typed accessors on the envelope (seeEvaluationEnvelope.GetEvaluation()).OpenAPI needs one unexported variant struct per kind (
fooConfigBar{Kind; Spec BarSpec}), exposed viaJSONSchemaOneOf()and mapped viaPrepareJSONSchemawith thex-signoz-discriminatorextension. The schema mechanics are covered in handler.md.A legacy persisted shape gets a data migration or a
StorableX. When rows were written before the envelope existed, prefer an idempotentsqlmigrationthat rewrites them into the new shape, so the storable type simply nests the envelope. Only when the old shape must keep being written (external writers, rollback windows) keep it in a storable twin and convert at the type boundary.
Conventions that tie the flavors together
Conversions use either a
New<Output>From<Input>constructor — e.g.NewChannelFromReceiver,NewGettableAuthDomainFromAuthDomain— or a receiver-styleToY()method. Both forms coexist in the codebase; use whichever fits the call site.Validation belongs on the core type
X. Putting it onXmeans every write path — HTTP create, HTTP update, in-process migration, replay — runs the same checks.Validate()onPostableXis reserved for checks that are specific to the request shape and do not apply toX.UnmarshalJSONonPostableXis a separate tool that lives there because decoding only happens at the HTTP boundary —PostableAuthDomain.UnmarshalJSONrejecting a malformed domain name at decode time is the canonical example.// Domain invariants: every write path re-runs these. func (entity *X) Validate() error { ... } // Request-shape-only: checks that do not apply once the value is persisted. func (postable *PostableX) Validate() error { ... }Type aliases, not wrappers, when two shapes are identical.
type GettableChannels = []*Channelis correct because it adds no semantics beyond the underlying type.Serialization tags follow handler.md:
required:"true"means the JSON key must be present,nullable:"true"is required on any slice or map that may serialize asnull, and types with a fixed value set must implementEnum() []any.
A note on UpdatableX and PatchableX
UpdatableX— the body for PUT (full replace) when the shape is a strict subset ofPostableX. If the updatable shape equalsPostableX, reusePostableX.PatchableX— the body for PATCH (partial update); only the fields a client is allowed to patch. For example,PatchableRolecarries a singleDescriptionfield even thoughRolehas many — clients may patch the description but not anything else.type PatchableRole struct { Description string `json:"description"` }
Both are optional. Do not introduce them if PostableX already covers the case.
What to avoid
- Do not mint a flavor that mirrors the core type. If
StorableXwould have the same fields asX, useXdirectly withbun.BaseModelembedded.Channelis the canonical example. - Do not bolt domain methods onto
StorableX. Storage types are data carriers. Domain methods live onX. - Do not invent new suffixes (
Creatable,Fetchable,Savable). The core type plusPostable/Gettable/Updatable/Patchable/Storablecovers every case that exists today. - Spelling —
Updatable, notUpdateable.Updateableis a common typo. Prefer the shorter form when introducing new types, and rename any stragglers you come across. - Spelling —
Storable, notStoreable.Storeableis a common typo. Prefer the shorter form when introducing new types, and rename any stragglers you come across.
What should I remember?
- Every domain package defines the core type
X. OnlyXis mandatory. - Add
PostableX/GettableX/UpdatableX/StorableXone at a time, only when the shape actually diverges fromX. - Model sum types as a
{kind, spec}envelope with a validatingUnmarshalJSON— never as sibling variant fields next to a discriminator. - The envelope goes on the field that varies, never at the resource root — common fields stay on the resource, outside the union.
- Domain logic lives on
X, not on the flavor types. - Conversions can be a
New<Output>From<Input>constructor or a receiver-styleToY()method — pick whichever reads best at the call site. - Use a type alias when two shapes are truly identical.
pkg/types/<domain>/must not import from otherpkg/packages.
Further reading
- abstractions.md — when to introduce a new type at all.
- handler.md — struct tag rules at the HTTP boundary.
- packages.md — where types live under
pkg/types/. - sql.md — star-schema requirements for
StorableX.