pdbcompat

package
v1.42.1 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: BSD-3-Clause Imports: 63 Imported by: 0

Documentation

Overview

Package pdbcompat provides a PeeringDB-compatible REST API layer that translates Django-style query parameters to ent predicates and serializes ent entities to PeeringDB's exact JSON response format.

Index

Constants

View Source
const (
	// DefaultLimit is the default value used when the `limit=` query
	// parameter is absent. Set to 0 ("unlimited") to mirror upstream
	// PeeringDB's behaviour (2.83.0 `rest.py:516`): bare `/api/<type>` URLs
	// return ALL rows from the queryset, not a paginated page.
	//
	// Earlier revisions of this code defaulted to 250, treating that as
	// a defensive page-size cap. The cap turned out to be a real parity
	// bug — verified 2026-04-28 against upstream live data
	// (parity-results.txt: bare /api/org returned 33,556 rows upstream
	// vs 250 on the mirror). The response-memory budget
	// (PDBPLUS_RESPONSE_MEMORY_LIMIT, default 128 MiB) is the real DoS
	// safeguard — it gates the precount × TypicalRowBytes before
	// materialising any result set, returning 413 when the would-be
	// payload exceeds the budget. The 250 default added nothing on top
	// of that, only divergence.
	DefaultLimit = 0
)
View Source
const FlushEvery = 100

FlushEvery is the row count between periodic http.Flusher.Flush() calls. Provides chunked backpressure for large payloads without the per-row syscall overhead of flushing after every Write.

View Source
const LogoMediaHost = "peeringdb-media-prod.s3.amazonaws.com"

LogoMediaHost is the host of the upstream media bucket, which every stored logo URL names. The fetcher reads no other host, so a stored URL cannot make the mirror send requests to another address.

View Source
const ResponseTooLargeType = "https://peeringdb-plus.fly.dev/errors/response-too-large"

ResponseTooLargeType is the RFC 9457 problem-type URI for pre-flight budget-exceeded 413 responses. Package constant so the handler wiring and the parity tests reference the same literal — drift between the wire value and the documented value is a silent compatibility break.

Variables

View Source
var Allowlists = map[string]AllowlistEntry{
	"campus": {
		Direct: []string{
			"fac__country",
			"fac__name",
			"org__name",
		},
	},
	"carrier": {
		Direct: []string{
			"fac__country",
			"fac__name",
			"org__name",
		},
	},
	"carrierfac": {
		Direct: []string{
			"carrier__name",
			"fac__country",
			"fac__name",
		},
	},
	"fac": {
		Direct: []string{
			"campus__name",
			"org__name",
		},
		Via: map[string][]string{
			"ixlan": {
				"ix__fac_count",
			},
		},
	},
	"ix": {
		Direct: []string{
			"ixpfx__prefix",
			"org__name",
		},
	},
	"ixfac": {
		Direct: []string{
			"fac__city",
			"fac__country",
			"fac__name",
			"ix__name",
		},
	},
	"ixlan": {
		Direct: []string{
			"ix__id",
			"ix__name",
			"ixpfx__prefix",
		},
	},
	"ixpfx": {
		Direct: []string{
			"ixlan__name",
		},
		Via: map[string][]string{
			"ixlan": {
				"ix__id",
				"ix__name",
			},
		},
	},
	"net": {
		Direct: []string{
			"org__id",
			"org__name",
		},
	},
	"netfac": {
		Direct: []string{
			"fac__country",
			"fac__name",
			"net__asn",
			"net__name",
		},
	},
	"netixlan": {
		Direct: []string{
			"ixlan__name",
			"net__asn",
			"net__name",
		},
	},
	"org": {
		Direct: []string{
			"fac__country",
			"fac__name",
			"ix__name",
			"net__asn",
			"net__name",
		},
	},
	"poc": {
		Direct: []string{
			"net__asn",
			"net__name",
		},
	},
}

Allowlists maps a PeeringDB type name (e.g. "net") to its Path A allowlist — the set of <fk>__<field> and <fk>__<fk>__<field> keys that mirror upstream serializers.py get_relation_filters(...) lists.

View Source
var Edges = map[string][]EdgeMetadata{
	"campus": {
		{Name: "facilities", TargetType: "fac", TraversalKey: "fac", Excluded: false, ParentFKColumn: "campus_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "organization", TargetType: "org", TraversalKey: "org", Excluded: false, ParentFKColumn: "org_id", TargetTable: "organizations", TargetIDColumn: "id", OwnFK: true},
	},
	"carrier": {
		{Name: "carrier_facilities", TargetType: "carrierfac", TraversalKey: "carrierfac", Excluded: false, ParentFKColumn: "carrier_id", TargetTable: "carrier_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "organization", TargetType: "org", TraversalKey: "org", Excluded: false, ParentFKColumn: "org_id", TargetTable: "organizations", TargetIDColumn: "id", OwnFK: true},
	},
	"carrierfac": {
		{Name: "carrier", TargetType: "carrier", TraversalKey: "carrier", Excluded: false, ParentFKColumn: "carrier_id", TargetTable: "carriers", TargetIDColumn: "id", OwnFK: true},
		{Name: "facility", TargetType: "fac", TraversalKey: "fac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: true},
	},
	"fac": {
		{Name: "campus", TargetType: "campus", TraversalKey: "campus", Excluded: false, ParentFKColumn: "campus_id", TargetTable: "campuses", TargetIDColumn: "id", OwnFK: true},
		{Name: "carrier_facilities", TargetType: "carrierfac", TraversalKey: "carrierfac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "carrier_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "ix_facilities", TargetType: "ixfac", TraversalKey: "ixfac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "ix_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "network_facilities", TargetType: "netfac", TraversalKey: "netfac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "network_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "organization", TargetType: "org", TraversalKey: "org", Excluded: false, ParentFKColumn: "org_id", TargetTable: "organizations", TargetIDColumn: "id", OwnFK: true},
	},
	"ix": {
		{Name: "ix_facilities", TargetType: "ixfac", TraversalKey: "ixfac", Excluded: false, ParentFKColumn: "ix_id", TargetTable: "ix_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "ix_lans", TargetType: "ixlan", TraversalKey: "ixlan", Excluded: false, ParentFKColumn: "ix_id", TargetTable: "ix_lans", TargetIDColumn: "id", OwnFK: false},
		{Name: "organization", TargetType: "org", TraversalKey: "org", Excluded: false, ParentFKColumn: "org_id", TargetTable: "organizations", TargetIDColumn: "id", OwnFK: true},
	},
	"ixfac": {
		{Name: "facility", TargetType: "fac", TraversalKey: "fac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: true},
		{Name: "internet_exchange", TargetType: "ix", TraversalKey: "ix", Excluded: false, ParentFKColumn: "ix_id", TargetTable: "internet_exchanges", TargetIDColumn: "id", OwnFK: true},
	},
	"ixlan": {
		{Name: "internet_exchange", TargetType: "ix", TraversalKey: "ix", Excluded: false, ParentFKColumn: "ix_id", TargetTable: "internet_exchanges", TargetIDColumn: "id", OwnFK: true},
		{Name: "ix_prefixes", TargetType: "ixpfx", TraversalKey: "ixpfx", Excluded: false, ParentFKColumn: "ixlan_id", TargetTable: "ix_prefixes", TargetIDColumn: "id", OwnFK: false},
		{Name: "network_ix_lans", TargetType: "netixlan", TraversalKey: "netixlan", Excluded: false, ParentFKColumn: "ixlan_id", TargetTable: "network_ix_lans", TargetIDColumn: "id", OwnFK: false},
	},
	"ixpfx": {
		{Name: "ix_lan", TargetType: "ixlan", TraversalKey: "ixlan", Excluded: false, ParentFKColumn: "ixlan_id", TargetTable: "ix_lans", TargetIDColumn: "id", OwnFK: true},
	},
	"net": {
		{Name: "network_facilities", TargetType: "netfac", TraversalKey: "netfac", Excluded: false, ParentFKColumn: "net_id", TargetTable: "network_facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "network_ix_lans", TargetType: "netixlan", TraversalKey: "netixlan", Excluded: false, ParentFKColumn: "net_id", TargetTable: "network_ix_lans", TargetIDColumn: "id", OwnFK: false},
		{Name: "organization", TargetType: "org", TraversalKey: "org", Excluded: false, ParentFKColumn: "org_id", TargetTable: "organizations", TargetIDColumn: "id", OwnFK: true},
		{Name: "pocs", TargetType: "poc", TraversalKey: "poc", Excluded: false, ParentFKColumn: "net_id", TargetTable: "pocs", TargetIDColumn: "id", OwnFK: false},
	},
	"netfac": {
		{Name: "facility", TargetType: "fac", TraversalKey: "fac", Excluded: false, ParentFKColumn: "fac_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: true},
		{Name: "network", TargetType: "net", TraversalKey: "net", Excluded: false, ParentFKColumn: "net_id", TargetTable: "networks", TargetIDColumn: "id", OwnFK: true},
	},
	"netixlan": {
		{Name: "ix_lan", TargetType: "ixlan", TraversalKey: "ixlan", Excluded: false, ParentFKColumn: "ixlan_id", TargetTable: "ix_lans", TargetIDColumn: "id", OwnFK: true},
		{Name: "ix_side", TargetType: "fac", TraversalKey: "ix_side", Excluded: false, ParentFKColumn: "ix_side_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: true},
		{Name: "network", TargetType: "net", TraversalKey: "net", Excluded: false, ParentFKColumn: "net_id", TargetTable: "networks", TargetIDColumn: "id", OwnFK: true},
	},
	"org": {
		{Name: "campuses", TargetType: "campus", TraversalKey: "campus", Excluded: false, ParentFKColumn: "org_id", TargetTable: "campuses", TargetIDColumn: "id", OwnFK: false},
		{Name: "carriers", TargetType: "carrier", TraversalKey: "carrier", Excluded: false, ParentFKColumn: "org_id", TargetTable: "carriers", TargetIDColumn: "id", OwnFK: false},
		{Name: "facilities", TargetType: "fac", TraversalKey: "fac", Excluded: false, ParentFKColumn: "org_id", TargetTable: "facilities", TargetIDColumn: "id", OwnFK: false},
		{Name: "internet_exchanges", TargetType: "ix", TraversalKey: "ix", Excluded: false, ParentFKColumn: "org_id", TargetTable: "internet_exchanges", TargetIDColumn: "id", OwnFK: false},
		{Name: "networks", TargetType: "net", TraversalKey: "net", Excluded: false, ParentFKColumn: "org_id", TargetTable: "networks", TargetIDColumn: "id", OwnFK: false},
	},
	"poc": {
		{Name: "network", TargetType: "net", TraversalKey: "net", Excluded: false, ParentFKColumn: "net_id", TargetTable: "networks", TargetIDColumn: "id", OwnFK: true},
	},
}

Edges maps a PeeringDB type name (e.g. "net") to a slice of EdgeMetadata describing its outgoing ent edges, plus the column edges declared in schema.ColumnEdges (ent/schema/pdb_allowlists.go). Consumed at request time by internal/pdbcompat.LookupEdge for Path B traversal.

The map is emitted at `go generate` time from gen.Graph — no runtime client.Schema walk, no sync.Once, no init-order coupling. Freshness is enforced by the existing go-generate drift-check CI gate (same precedent as the v1.15 schema hygiene drops).

TraversalKey is the <fk> token in filter params (equals TargetType for ent edges; a column edge carries its upstream FK name). Excluded edges (WithFilterExcludeFromTraversal annotation) are emitted with Excluded=true; LookupEdge hides them from its callers so consumers see them as missing.

ParentFKColumn, TargetTable, TargetIDColumn carry SQL-level metadata for the runtime subquery construction. An ent edge whose FK column or target table could not be resolved at codegen time is logged and skipped entirely (never emitted with blank metadata). A column edge that does not resolve stops codegen.

View Source
var FilterExcludes = map[string]map[string]bool{}

FilterExcludes holds the edges hidden from traversal: the edge-level counterpart of upstream 2.83.0 serializers.py:136-166 FILTER_EXCLUDE. Upstream's field-level entries (<fk>__<field>) have no counterpart. Outer key: entity Go name (e.g. "Network"). Inner key: edge name (e.g. "pocs"). Value is always true; the map is used as a set.

View Source
var Registry = map[string]TypeConfig{
	peeringdb.TypeOrg: {
		Name: peeringdb.TypeOrg,
		Fields: map[string]FieldType{
			"id":        FieldInt,
			"name":      FieldString,
			"aka":       FieldString,
			"name_long": FieldString,
			"website":   FieldString,
			"notes":     FieldString,
			"logo":      FieldString,
			"address1":  FieldString,
			"address2":  FieldString,
			"city":      FieldString,
			"state":     FieldString,
			"country":   FieldString,
			"zipcode":   FieldString,
			"suite":     FieldString,
			"floor":     FieldString,
			"latitude":  FieldFloat,
			"longitude": FieldFloat,
			"created":   FieldTime,
			"updated":   FieldTime,
			"status":    FieldString,
		},
		SearchFields: []string{"name", "aka", "name_long"},
		FoldedFields: map[string]bool{"name": true, "aka": true, "city": true},
	},
	peeringdb.TypeNet: {
		Name: peeringdb.TypeNet,
		Fields: map[string]FieldType{
			"id":                           FieldInt,
			"org_id":                       FieldInt,
			"name":                         FieldString,
			"aka":                          FieldString,
			"name_long":                    FieldString,
			"website":                      FieldString,
			"asn":                          FieldInt,
			"looking_glass":                FieldString,
			"route_server":                 FieldString,
			"irr_as_set":                   FieldString,
			"info_types":                   FieldMultiChoice,
			"info_prefixes4":               FieldInt,
			"info_prefixes6":               FieldInt,
			"info_traffic":                 FieldString,
			"info_ratio":                   FieldString,
			"info_scope":                   FieldString,
			"info_unicast":                 FieldBool,
			"info_multicast":               FieldBool,
			"info_ipv6":                    FieldBool,
			"info_never_via_route_servers": FieldBool,
			"notes":                        FieldString,
			"policy_url":                   FieldString,
			"policy_general":               FieldString,
			"policy_locations":             FieldString,
			"policy_ratio":                 FieldBool,
			"policy_contracts":             FieldString,
			"allow_ixp_update":             FieldBool,
			"status_dashboard":             FieldString,
			"rir_status":                   FieldString,
			"rir_status_updated":           FieldTime,
			"logo":                         FieldString,
			"ix_count":                     FieldInt,
			"fac_count":                    FieldInt,
			"netixlan_updated":             FieldTime,
			"netfac_updated":               FieldTime,
			"poc_updated":                  FieldTime,
			"created":                      FieldTime,
			"updated":                      FieldTime,
			"status":                       FieldString,
		},
		SearchFields: []string{"name", "aka", "name_long", "irr_as_set"},
		FoldedFields: map[string]bool{"name": true, "aka": true, "name_long": true},
		ForeignKeys:  map[string]string{"org": "org_id"},

		ExactCounts: map[string]bool{"fac_count": true},
	},
	peeringdb.TypeFac: {
		Name: peeringdb.TypeFac,
		Fields: map[string]FieldType{
			"id":                          FieldInt,
			"org_id":                      FieldInt,
			"org_name":                    FieldString,
			"campus_id":                   FieldInt,
			"name":                        FieldString,
			"aka":                         FieldString,
			"name_long":                   FieldString,
			"website":                     FieldString,
			"clli":                        FieldString,
			"rencode":                     FieldString,
			"npanxx":                      FieldString,
			"tech_email":                  FieldString,
			"tech_phone":                  FieldString,
			"sales_email":                 FieldString,
			"sales_phone":                 FieldString,
			"property":                    FieldString,
			"diverse_serving_substations": FieldBool,
			"notes":                       FieldString,
			"region_continent":            FieldString,
			"status_dashboard":            FieldString,
			"logo":                        FieldString,
			"net_count":                   FieldInt,
			"ix_count":                    FieldInt,
			"carrier_count":               FieldInt,
			"available_voltage_services":  FieldMultiChoice,
			"address1":                    FieldString,
			"address2":                    FieldString,
			"city":                        FieldString,
			"state":                       FieldString,
			"country":                     FieldString,
			"zipcode":                     FieldString,
			"suite":                       FieldString,
			"floor":                       FieldString,
			"latitude":                    FieldFloat,
			"longitude":                   FieldFloat,
			"created":                     FieldTime,
			"updated":                     FieldTime,
			"status":                      FieldString,
		},
		SearchFields: []string{"name", "aka", "name_long", "city", "country"},
		FoldedFields: map[string]bool{"name": true, "aka": true, "city": true},
		ForeignKeys:  map[string]string{"org": "org_id", "campus": "campus_id"},

		NonModelFields: map[string]bool{"org_name": true},

		ExactCounts: map[string]bool{"net_count": true},
	},
	peeringdb.TypeIX: {
		Name: peeringdb.TypeIX,
		Fields: map[string]FieldType{
			"id":                        FieldInt,
			"org_id":                    FieldInt,
			"name":                      FieldString,
			"aka":                       FieldString,
			"name_long":                 FieldString,
			"city":                      FieldString,
			"country":                   FieldString,
			"region_continent":          FieldString,
			"media":                     FieldString,
			"notes":                     FieldString,
			"proto_unicast":             FieldBool,
			"proto_multicast":           FieldBool,
			"proto_ipv6":                FieldBool,
			"website":                   FieldString,
			"url_stats":                 FieldString,
			"tech_email":                FieldString,
			"tech_phone":                FieldString,
			"policy_email":              FieldString,
			"policy_phone":              FieldString,
			"sales_email":               FieldString,
			"sales_phone":               FieldString,
			"net_count":                 FieldInt,
			"fac_count":                 FieldInt,
			"ixf_net_count":             FieldInt,
			"ixf_last_import":           FieldTime,
			"ixf_import_request":        FieldString,
			"ixf_import_request_status": FieldString,
			"service_level":             FieldString,
			"terms":                     FieldString,
			"status_dashboard":          FieldString,
			"logo":                      FieldString,
			"created":                   FieldTime,
			"updated":                   FieldTime,
			"status":                    FieldString,
		},
		SearchFields: []string{"name", "aka", "name_long", "city", "country"},
		FoldedFields: map[string]bool{"name": true, "aka": true, "name_long": true, "city": true},
		ForeignKeys:  map[string]string{"org": "org_id"},

		ExactCounts: map[string]bool{"net_count": true, "fac_count": true},
	},
	peeringdb.TypePoc: {
		Name: peeringdb.TypePoc,
		Fields: map[string]FieldType{
			"id":      FieldInt,
			"net_id":  FieldInt,
			"role":    FieldString,
			"visible": FieldString,
			"name":    FieldString,
			"phone":   FieldString,
			"email":   FieldString,
			"url":     FieldString,
			"created": FieldTime,
			"updated": FieldTime,
			"status":  FieldString,
		},
		SearchFields: []string{"name", "email"},
		ForeignKeys:  map[string]string{"network": "net_id"},
	},
	peeringdb.TypeIXLan: {
		Name: peeringdb.TypeIXLan,
		Fields: map[string]FieldType{
			"id":                              FieldInt,
			"ix_id":                           FieldInt,
			"name":                            FieldString,
			"descr":                           FieldString,
			"mtu":                             FieldInt,
			"dot1q_support":                   FieldBool,
			"rs_asn":                          FieldInt,
			"arp_sponge":                      FieldString,
			"ixf_ixp_member_list_url_visible": FieldString,
			"ixf_ixp_import_enabled":          FieldBool,
			"created":                         FieldTime,
			"updated":                         FieldTime,
			"status":                          FieldString,
		},
		SearchFields: []string{"name", "descr"},
		ForeignKeys:  map[string]string{"ix": "ix_id"},
	},
	peeringdb.TypeIXPfx: {
		Name: peeringdb.TypeIXPfx,
		Fields: map[string]FieldType{
			"id":       FieldInt,
			"ixlan_id": FieldInt,
			"protocol": FieldString,
			"prefix":   FieldString,
			"in_dfz":   FieldBool,
			"created":  FieldTime,
			"updated":  FieldTime,
			"status":   FieldString,
		},
		SearchFields: []string{"prefix"},

		ForeignKeys: map[string]string{"ixlan": "ixlan_id"},
	},
	peeringdb.TypeNetIXLan: {
		Name: peeringdb.TypeNetIXLan,
		Fields: map[string]FieldType{
			"id":          FieldInt,
			"net_id":      FieldInt,
			"ix_id":       FieldInt,
			"ixlan_id":    FieldInt,
			"name":        FieldString,
			"notes":       FieldString,
			"speed":       FieldInt,
			"asn":         FieldInt,
			"ipaddr4":     FieldString,
			"ipaddr6":     FieldString,
			"is_rs_peer":  FieldBool,
			"bfd_support": FieldBool,
			"operational": FieldBool,
			"net_side_id": FieldInt,
			"ix_side_id":  FieldInt,
			"created":     FieldTime,
			"updated":     FieldTime,
			"status":      FieldString,
		},
		SearchFields: []string{"name"},

		ForeignKeys: map[string]string{
			"network": "net_id",
			"ixlan":   "ixlan_id",
			"ix_side": "ix_side_id",
		},

		UpstreamIgnored: map[string]bool{"net_side_id": true},

		NonModelFields: map[string]bool{"name": true, "ix_id": true},
	},
	peeringdb.TypeNetFac: {
		Name: peeringdb.TypeNetFac,
		Fields: map[string]FieldType{
			"id":        FieldInt,
			"net_id":    FieldInt,
			"fac_id":    FieldInt,
			"name":      FieldString,
			"city":      FieldString,
			"country":   FieldString,
			"local_asn": FieldInt,
			"created":   FieldTime,
			"updated":   FieldTime,
			"status":    FieldString,
		},
		SearchFields: []string{"name"},
		ForeignKeys:  map[string]string{"network": "net_id", "facility": "fac_id"},

		UpstreamIgnored: map[string]bool{"local_asn": true},

		NonModelFields: map[string]bool{
			"name":      true,
			"city":      true,
			"country":   true,
			"local_asn": true,
		},
	},
	peeringdb.TypeIXFac: {
		Name: peeringdb.TypeIXFac,
		Fields: map[string]FieldType{
			"id":      FieldInt,
			"ix_id":   FieldInt,
			"fac_id":  FieldInt,
			"name":    FieldString,
			"city":    FieldString,
			"country": FieldString,
			"created": FieldTime,
			"updated": FieldTime,
			"status":  FieldString,
		},
		SearchFields: []string{"name"},
		ForeignKeys:  map[string]string{"ix": "ix_id", "facility": "fac_id"},

		NonModelFields: map[string]bool{"name": true, "city": true, "country": true},
	},
	peeringdb.TypeCarrier: {
		Name: peeringdb.TypeCarrier,
		Fields: map[string]FieldType{
			"id":        FieldInt,
			"org_id":    FieldInt,
			"org_name":  FieldString,
			"name":      FieldString,
			"aka":       FieldString,
			"name_long": FieldString,
			"website":   FieldString,
			"notes":     FieldString,
			"fac_count": FieldInt,
			"logo":      FieldString,
			"created":   FieldTime,
			"updated":   FieldTime,
			"status":    FieldString,
		},
		SearchFields: []string{"name", "aka", "name_long"},
		FoldedFields: map[string]bool{"name": true, "aka": true},
		ForeignKeys:  map[string]string{"org": "org_id"},

		UpstreamIgnored: map[string]bool{"fac_count": true, "org_name": true},
		NonModelFields:  map[string]bool{"org_name": true},
	},
	peeringdb.TypeCarrierFac: {
		Name: peeringdb.TypeCarrierFac,
		Fields: map[string]FieldType{
			"id":         FieldInt,
			"carrier_id": FieldInt,
			"fac_id":     FieldInt,
			"name":       FieldString,
			"created":    FieldTime,
			"updated":    FieldTime,
			"status":     FieldString,
		},
		SearchFields: []string{"name"},
		ForeignKeys:  map[string]string{"carrier": "carrier_id", "facility": "fac_id"},

		UpstreamIgnored: map[string]bool{"name": true},
		NonModelFields:  map[string]bool{"name": true},
	},
	peeringdb.TypeCampus: {
		Name: peeringdb.TypeCampus,
		Fields: map[string]FieldType{
			"id":        FieldInt,
			"org_id":    FieldInt,
			"org_name":  FieldString,
			"name":      FieldString,
			"name_long": FieldString,
			"aka":       FieldString,
			"website":   FieldString,
			"notes":     FieldString,
			"country":   FieldString,
			"city":      FieldString,
			"zipcode":   FieldString,
			"state":     FieldString,
			"logo":      FieldString,
			"created":   FieldTime,
			"updated":   FieldTime,
			"status":    FieldString,
		},
		SearchFields: []string{"name"},
		FoldedFields: map[string]bool{"name": true},
		ForeignKeys:  map[string]string{"org": "org_id"},

		UpstreamIgnored: map[string]bool{
			"org_name": true,
			"city":     true,
			"country":  true,
			"state":    true,
			"zipcode":  true,
		},
		NonModelFields: map[string]bool{
			"org_name": true,
			"city":     true,
			"country":  true,
			"state":    true,
			"zipcode":  true,
		},
	},
}

Registry maps PeeringDB type name strings to their TypeConfig. List and Get functions are nil until serializers are wired up.

Every type declares "status" as an ordinary filter field. Upstream (2.83.0) turns ?status=X into status__iexact (rest.py:683) and applies it before the list status matrix (rest.py:695, :745-748), so the two filters AND together. wireEntity appends applyStatusMatrix last, so a caller filter can narrow the admitted statuses but never widen them.

Functions

func ParseDepthParam added in v1.37.0

func ParseDepthParam(params url.Values) (raw int, text string, present bool, err error)

ParseDepthParam returns the ?depth= value as upstream parses it (2.83.0 rest.py:520-523): the last value, Python int() rules (pyInt). raw is the value, saturated to the int range. text is its canonical decimal form, for messages that print the value. present is false when the key is absent, and the caller then applies its own default. An empty or non-integer value is errDepthNotNumber. The caller clamps raw to its depth range.

func ParseFilters

func ParseFilters(params url.Values, tc TypeConfig) ([]func(*sql.Selector), bool, error)

ParseFilters translates Django-style query parameters into ent sql.Selector predicates. Reserved parameters (limit, skip, etc.) are skipped. Unknown fields are silently ignored.

Calls ParseFiltersCtx with context.Background — unknown fields are discarded rather than surfaced. Production handlers MUST use ParseFiltersCtx with a ctx from WithUnknownFields to emit diagnostics.

Return values:

  • preds: the predicate slice to pass to ent as Where arguments
  • emptyResult: true when an __in filter was empty (?asn__in=); the caller MUST short-circuit the whole request and emit an empty data array without running SQL
  • err: set only for known fields with invalid values / operators

func ParseFiltersCtx added in v1.16.0

func ParseFiltersCtx(ctx context.Context, params url.Values, tc TypeConfig) ([]func(*sql.Selector), bool, error)

ParseFiltersCtx is the context-aware filter parser. Unknown filter fields (including over-cap traversal keys) are silently ignored for the HTTP response AND appended to the ctx-attached accumulator so operators can observe them via slog.DebugContext + OTel.

A key without relation segments filters a local column. A key that names a forward FK in upstream spelling (org, network_id, facility) filters the FK column (resolveLocalField). A key that upstream never filters (TypeConfig.UpstreamIgnored) is unknown, and so is a relation key whose field is a FK column (namesFKColumn). A relation key filters status only through a forward edge one hop away (relationStatusFilterable).

Traversal resolution order (1-hop and 2-hop, len(relSegs) <= 2):

  1. Path A: Allowlists[tc.Name].Direct or .Via exact match
  2. Path B: LookupEdge + TargetFields introspection

An upstream FK name as the first relation segment (network__asn, facility__name) resolves as the mirror traversal key of the same edge (traversalKeyFor).

Keys with len(relSegs) > 2 are silently rejected.

parseListFilters reads the keys in the upstream order: the fac and org distance key (parseDistanceSearch), the prepare_query keys, name_search (resolveNameSearch), then the other keys.

For each key (filterState.addKey), the filterable meta keys of the type (netixlan meta__<path> and the upstream meta_* column names, see lookupMetaFilter) resolve first, before the key is split for traversal. The presence keys of an upstream prepare_query (presenceKeys, for example net?not_ix= and fac?all_net=) resolve next, then the ix ipblock key (lookupIPBlockKey, a text prefix match on the ixpfx prefix), then the ixpfx whereis key (lookupWhereisKey, the prefixes that contain an address), then the ix capacity key (lookupCapacityFilter, the sum of the netixlan speeds), then the relation keys (relationSeeds, for example fac?net= and net?ix__name=), with their own path and status rules (buildPresencePredicate, buildRelationSeedPredicate). The bare netixlan ipaddr6 key resolves next and compares the canonical text of the address (ipaddr6Predicate).

The status matrix and the _fold-routing / empty-__in invariants are preserved: traversal predicates wrap around buildPredicate which still consults FoldedFields on the target TypeConfig, and the empty-__in emptyResult sentinel bubbles back up from subquery construction.

An empty result (an empty __in) is returned after every key is parsed, so an error of any key wins.

ParseFiltersCtx wraps parseListFilters and drops the sort key of a distance search: see parseListFilters for the pre-pass.

func ParsePaginationParams

func ParsePaginationParams(params url.Values) (limit, skip int, err error)

ParsePaginationParams returns limit and skip as upstream parses them (2.83.0 rest.py:511-518): the last value of each key, Python int() rules (pyInt), skip first. An empty or non-integer value is an error with the upstream text.

The values keep their sign, and the caller decides what a negative value does. serveList serves every row for a negative limit, as upstream slices only when limit > 0 (rest.py:757-760), and returns 400 for a negative skip (errNegativeSkip).

Without a limit key the limit is DefaultLimit (0 = every row), as upstream (rest.py:516). A positive limit has no upper cap (rest.py:757-758). The response memory budget bounds the response: when the count × TypicalRowBytes is over the budget, the handler returns 413 before it reads any row. A value too large for an int saturates: a huge limit serves every row and a huge skip serves no row.

func ParseSinceParam

func ParseSinceParam(params url.Values) (*time.Time, error)

ParseSinceParam parses ?since= as a Unix timestamp (see parseSince). It returns nil when the key is absent and when the value is 0 or less: upstream activates the since matrix only if since > 0 (2.83.0 rest.py:719), so ?since=0 gives the plain live-status list. A zero boundary here would flip the status matrix and serve every tombstone.

The time is in UTC. The SQLite driver binds a time.Time as text in the zone of the value, and the stored timestamps are UTC text, so the comparison is only correct when both sides are UTC. time.Unix returns the process zone, which is UTC in production but not on every host.

func StreamListResponse added in v1.16.0

func StreamListResponse(ctx context.Context, w http.ResponseWriter, meta any, rowsIter RowsIter) error

StreamListResponse writes a PeeringDB envelope {"meta":...,"data":[...]} token-by-token without materialising the full result slice.

Write sequence:

  1. Set the Content-Type (httperr.MetaJSONContentType) and X-Powered-By headers.
  2. Write `{"meta":` + json.Marshal(meta) + `,"data":[`.
  3. For each row yielded by rowsIter: emit a leading `,` (when not first), then json.Marshal(row) written directly to w.
  4. Every FlushEvery rows, flush via http.Flusher (if w implements it).
  5. Write `]}` and do a final flush.

Error handling:

  • json.Marshal(meta) failure returns the wrapped error BEFORE any bytes hit the wire, so callers can still emit a 500 error body.
  • Any failure after the prelude has been written returns a wrapped error; previously-written bytes stay on the wire (the response is already committed). The caller is expected to log and drop the connection.
  • Absence of http.Flusher on w is tolerated: flushes are silently skipped.

ctx is reserved for future per-row cancellation (honor ctx.Done() inside the loop for backpressure when a client disconnects); today the iterator is driven by ent.All() or a keyset-chunked query that already respects ctx at its own boundary, so threading ctx.Err() per row is redundant.

func TargetFields added in v1.16.0

func TargetFields(targetType string) map[string]FieldType

TargetFields returns the filterable field set on the target entity of an edge lookup. Parser uses this to validate the <field> portion of <fk>__<field> before translating to a predicate.

Consults Registry[targetType].Fields — the existing TypeConfig map. Nil-safe: returns nil for an unknown target.

func TypicalRowBytes added in v1.16.0

func TypicalRowBytes(entity string, depth int) int

TypicalRowBytes returns the conservative estimated serialized size per row for the named entity at the given depth. depth collapses to two buckets: 0 (the bare row) and >=1 (expanded), where the expanded estimate is the depth=2 figure. That is a safe over-estimate for ?depth=1, whose reverse-relation ID lists are smaller than the depth=2 full objects but larger than the bare row. Unknown entities return defaultRowSize to fail-closed against surprise types (e.g. a new type added to Registry before this map is updated).

func UnknownFieldsFromCtx added in v1.16.0

func UnknownFieldsFromCtx(ctx context.Context) []string

UnknownFieldsFromCtx returns the current accumulator (possibly nil when no accumulator was attached). Callers emit slog.DebugContext + OTel span attribute from the returned slice after ParseFiltersCtx returns.

func WithUnknownFields added in v1.16.0

func WithUnknownFields(ctx context.Context) context.Context

WithUnknownFields returns a new context carrying an empty unknown-fields accumulator. Handler creates this before calling ParseFiltersCtx; the parser appends to the accumulator as it encounters unknown keys.

Ctx threading (rather than a return slice) keeps ParseFilters' existing return signature stable and avoids churning every call site that passes params straight through to ent.

func WriteBudgetProblem added in v1.16.0

func WriteBudgetProblem(w http.ResponseWriter, instance string, info BudgetExceeded)

WriteBudgetProblem writes the RFC 9457 413 response described above. writeBudgetError calls it when the request Accept header names application/problem+json. Does not set Retry-After: the failure is request-shape (wrong filters / too-large page), not transient resource pressure; retrying the same request would produce the same 413. Operators who want to retrieve more rows must narrow their filters or page smaller.

`instance` is written through untouched to the `instance` field of the problem-detail body when non-empty; callers typically pass r.URL.Path.

func WriteResponse

func WriteResponse(w http.ResponseWriter, data any)

WriteResponse writes a successful PeeringDB-compatible JSON response with the standard envelope format. Data must be a slice.

Types

type AllowlistEntry added in v1.16.0

type AllowlistEntry struct {
	Direct []string
	Via    map[string][]string
}

AllowlistEntry is the per-entity allowlist shape emitted into internal/pdbcompat/allowlist_gen.go by cmd/pdb-compat-allowlist. Consumed at request time by ParseFilters to decide whether a <fk>__<field> key is a valid Path A traversal.

  • Direct: single-hop filter keys (e.g. "org__name"). Codegen populates this from WithPrepareQueryAllow fields that contain exactly one "__" separator AND whose first segment matches a schema edge name.
  • Via: 2-hop filter keys grouped by first hop. For "ixlan__ix__fac_count" the map entry is {"ixlan": {"ix__fac_count"}}. Codegen populates from fields that contain exactly two "__" separators.

Fields with zero or >2 "__" separators are either direct local fields (0 separators — live in TypeConfig.Fields instead) or too deep (>2 separators — exceed the 2-hop cap, so codegen drops them with a build-time warning).

type BudgetExceeded added in v1.16.0

type BudgetExceeded struct {
	MaxRows        int    `json:"max_rows"`
	BudgetBytes    int64  `json:"budget_bytes"`
	EstimatedBytes int64  `json:"-"`
	Count          int    `json:"-"`
	Entity         string `json:"-"`
	Depth          int    `json:"-"`
}

BudgetExceeded describes a request whose estimated response size exceeds the configured PDBPLUS_RESPONSE_MEMORY_LIMIT. Populated by CheckBudget; consumed by writeBudgetError (413 writer) and structured-log emission in the handler + OTel span attributes for the memory-budget counter.

Only MaxRows and BudgetBytes are serialized onto the wire; EstimatedBytes, Count, Entity, and Depth are internal diagnostics carried in the struct so callers can log / trace them without a second trip through TypicalRowBytes.

func CheckBudget added in v1.16.0

func CheckBudget(count int, entity string, depth int, budgetBytes int64) (BudgetExceeded, bool)

CheckBudget reports whether a request of `count` rows for `entity` at `depth` fits under `budgetBytes`. The BudgetExceeded diagnostics are populated on BOTH outcomes so the caller can reuse EstimatedBytes for in-flight pool admission without recomputing the count × row-size math (a second computation could silently drift from the 413 pricing); ok distinguishes fits (true) from over-budget (false).

budgetBytes <= 0 disables the check entirely — same semantic as PDBPLUS_SYNC_MEMORY_LIMIT=0. This is the documented local-dev escape hatch and the reason the unbounded limit=0 is safe to expose in prod (the budget is the DoS safety net).

The math: perRow = TypicalRowBytes(entity, depth); estimated = count × perRow; over budget iff estimated > budgetBytes. The estimate is conservative by construction — TypicalRowBytes is the measured mean doubled and rounded up, and count is a precise SELECT COUNT(*) against the already-filtered query, so false-positive 413s are rare and preferred over OOM.

Overflow: count is an int from SELECT COUNT(*); perRow tops out near 10 KiB in the lookup table. count × perRow comfortably fits int64 until count exceeds ~10^15, which is 10^8× the current PeeringDB fleet size. No overflow guard needed in practice.

type CountFunc added in v1.16.0

type CountFunc func(ctx context.Context, client *ent.Client, opts QueryOptions) (int, error)

CountFunc runs the predicate chain for a list query and returns the matching row count WITHOUT fetching row data. Used by the serveList pre-flight budget check to decide whether to 413 up-front before committing to an expensive .All(ctx) fetch.

The returned count reflects what WOULD be served after Offset/Limit are applied — not the raw total. This matches the budget math that multiplies count × typicalRowBytes.

type EdgeMetadata added in v1.16.0

type EdgeMetadata struct {
	Name           string
	TargetType     string
	TraversalKey   string
	Excluded       bool
	ParentFKColumn string
	TargetTable    string
	TargetIDColumn string
	OwnFK          bool
}

EdgeMetadata describes one edge for Path B traversal lookup: an ent edge, or a column edge declared in schema.ColumnEdges (ent/schema/pdb_allowlists.go) over a FK column that has no ent edge. Emitted into allowlist_gen.go Edges by cmd/pdb-compat-allowlist at `go generate` time. The codegen-emitted static map is used instead of a runtime client.Schema.Tables walk: it is deterministic, testable, has no init-order coupling, and matches the v1.15 codegen precedent; freshness is enforced by the existing go-generate drift-check CI gate.

Parser-facing fields:

  • Name: local ent edge name (e.g. "organization", "network_facilities"), or the traversal key of a column edge declared in schema.ColumnEdges.
  • TargetType: PeeringDB type string of the edge target (e.g. "org")
  • TraversalKey: the <fk> token used in filter params ("?org__name=foo" → TraversalKey "org"). Equals TargetType for ent edges; a column edge carries its upstream FK name (e.g. "ix_side"). A column edge always has OwnFK true.
  • Excluded: true when the edge has WithFilterExcludeFromTraversal. LookupEdge returns (zero, false) for excluded edges.

SQL-join-facing fields (consumed read-only by the traversal subquery construction):

  • ParentFKColumn: foreign-key column name for this edge sourced from gen.Relation.Column() at codegen time. For M2O edges (edge.From with Ref().Field()) the column lives on the parent table (networks.org_id); for O2M edges (edge.To) the column lives on the child table (pocs.net_id). The subquery shape depends on which side of the join owns the column — see OwnFK below.
  • OwnFK: true when ParentFKColumn lives on the PARENT table (M2O / O2O-from-inverse); false when it lives on the CHILD / target table (O2M / O2O-from-edge). Populated at codegen time from gen.Edge.Rel.Type (M2O → true; O2M → false). Used by buildSinglHop / buildTwoHop to decide whether to filter the parent's PK against a `SELECT child.<fk>` subquery (O2M) or the parent's FK column against a `SELECT target.<id>` subquery (M2O). Without this flag, O2M edges like net→pocs produce invalid SQL referencing a non-existent networks.net_id column.
  • TargetTable: SQL table name on the target side (e.g. "organizations").
  • TargetIDColumn: typically "id"; emitted explicitly so the codegen output is self-contained and doesn't rely on a convention.

func LookupEdge added in v1.16.0

func LookupEdge(entityType, fk string) (EdgeMetadata, bool)

LookupEdge returns the edge metadata for a single hop from entityType via the filter-param token fk (e.g. LookupEdge("net", "org") returns the Network→Organization edge).

Returns (zero, false) when:

  • entityType is not in Edges (unknown PeeringDB type)
  • no edge on entityType has TraversalKey == fk
  • the matching edge is Excluded

The traversal parser calls this after a param fails direct-field lookup and also fails Path A Allowlists lookup. When this returns false, the param is the unknown-filter-field case and goes through the silent-ignore + DEBUG log + OTel attr path.

The generated Edges map is populated at package init by Go's normal mechanism and is safe for concurrent readers with no runtime guard — the codegen path makes the map effectively immutable after init.

func ResolveEdges added in v1.16.0

func ResolveEdges(entityType string) []EdgeMetadata

ResolveEdges returns all non-excluded edges for entityType. Used in tests and by future diagnostic endpoints; not on the request-time hot path. Returns nil (not a zero-length slice) for an unknown entityType so callers can distinguish "no such entity" from "entity with no traversable edges".

type FieldType

type FieldType int

FieldType represents the data type of a filterable field.

const (
	// FieldString indicates a string-typed field.
	FieldString FieldType = iota
	// FieldInt indicates an integer-typed field.
	FieldInt
	// FieldBool indicates a boolean-typed field.
	FieldBool
	// FieldTime indicates a time.Time-typed field.
	FieldTime
	// FieldFloat indicates a float64-typed field.
	FieldFloat
	// FieldMultiChoice indicates a multi-value choice field, stored as a
	// JSON array of strings. The filters compare the string that
	// upstream stores (see multichoice_filter.go).
	FieldMultiChoice
)

func (FieldType) String added in v1.19.0

func (ft FieldType) String() string

String returns the human-readable name of the field type. It is used in client-facing 400 filter-error messages so callers see "bool" rather than the internal enum integer. Unknown values render as "unknown(<n>)" rather than panicking — filter errors must never crash the request path.

type FilterExcludeFromTraversalAnnotation added in v1.16.0

type FilterExcludeFromTraversalAnnotation = schemaannot.FilterExcludeFromTraversalAnnotation

FilterExcludeFromTraversalAnnotation aliases schemaannot.FilterExcludeFromTraversalAnnotation.

func WithFilterExcludeFromTraversal added in v1.16.0

func WithFilterExcludeFromTraversal() FilterExcludeFromTraversalAnnotation

WithFilterExcludeFromTraversal is the pdbcompat-package-level constructor for FILTER_EXCLUDE annotations. Re-exports schemaannot.WithFilterExcludeFromTraversal.

Initial expected call sites:

  • Any edge that materialises as a JSON field (none today — placeholder)
  • Relay id-alias edges generated by entgql (covered via codegen introspection rather than explicit annotation; the tool detects them by name).

type GetFunc

type GetFunc func(ctx context.Context, client *ent.Client, id int, depth int) (any, error)

GetFunc queries a single entity by ID and returns its serialized form.

type Handler

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

Handler serves PeeringDB-compatible API endpoints.

func NewHandler

func NewHandler(client *ent.Client, responseMemoryLimit int64) *Handler

NewHandler creates a Handler for PeeringDB-compatible API endpoints. responseMemoryLimit is the per-response byte budget consumed by the pre-flight CheckBudget gate. Pass 0 to disable the budget check (local dev / tests only; operators ship a non-zero PDBPLUS_RESPONSE_MEMORY_LIMIT in prod — default 128 MiB).

func (*Handler) Register

func (h *Handler) Register(mux *http.ServeMux)

Register sets up PeeringDB-compatible routes on the given mux. Routes follow PeeringDB's URL patterns: /api/{type}, /api/{type}/{id} (parseAPIPath). The index endpoint at /api/ lists all available types.

func (*Handler) SetLogoSource added in v1.40.0

func (h *Handler) SetLogoSource(client *http.Client, host string)

SetLogoSource makes the asset route read logo files with client from the https URLs of host (LogoMediaHost in production). Without a source, the route sends file_data null.

func (*Handler) SetSyncClock added in v1.38.0

func (h *Handler) SetSyncClock(c *SyncClock)

SetSyncClock sets the clock of meta.generated. Without a clock, no response carries meta.generated.

type ListDepthFunc added in v1.37.0

type ListDepthFunc func(ctx context.Context, client *ent.Client, opts QueryOptions, ids []int, depth int, sets []childSet) ([]func() any, error)

ListDepthFunc loads the rows with the given ids (one chunk) and the given sets of each row at list depth 1 or 2 (list_depth.go). It returns one render closure per loaded row, in the order of ids. It applies the list predicates again, so a row that stopped matching after ListIDs is left out. A closure builds the row map when it is called.

type ListFunc

type ListFunc func(ctx context.Context, client *ent.Client, opts QueryOptions) ([]any, error)

ListFunc queries entities and returns their serialized objects.

type ListIDsFunc added in v1.37.0

type ListIDsFunc func(ctx context.Context, client *ent.Client, opts QueryOptions) ([]int, error)

ListIDsFunc returns the ids that a list request serves, in list order: the same predicates, order, skip and limit as ListFunc. A list at depth > 0 of a type with reverse sets reads the ids first and then loads the rows in chunks (ListDepthFunc).

type MatchFunc added in v1.37.0

type MatchFunc func(ctx context.Context, client *ent.Client, id int, filters []func(*sql.Selector)) (bool, error)

MatchFunc reports whether the row with the given id matches filters. A detail request uses it to apply the list filters: upstream get_object filters get_queryset(), which runs the same filters as a list (2.83.0 rest.py:849-855, :477-703). It adds no status of its own. The inline StatusIn of the get<Type>WithDepth PK lookup stays the detail status set. A filter can pin a status, as upstream does (a relation seed, make_relation_filter).

type PrepareQueryAllowAnnotation added in v1.16.0

type PrepareQueryAllowAnnotation = schemaannot.PrepareQueryAllowAnnotation

PrepareQueryAllowAnnotation aliases schemaannot.PrepareQueryAllowAnnotation. See the schemaannot package for full docs.

func WithPrepareQueryAllow added in v1.16.0

func WithPrepareQueryAllow(fields ...string) PrepareQueryAllowAnnotation

WithPrepareQueryAllow is the pdbcompat-package-level constructor for Path A allowlist annotations. Re-exports schemaannot.WithPrepareQueryAllow so pdbcompat's existing API surface is unchanged. New ent/schema call sites should import the schemaannot sub-package directly to avoid the import cycle documented above.

type QueryOptions

type QueryOptions struct {
	Filters []func(*sql.Selector)
	Limit   int
	Skip    int
	Since   *time.Time

	// EmptyResult is set by ParseFilters when the request contains an
	// __in filter with zero values (e.g. ?asn__in=). Each list closure in
	// registry_funcs.go short-circuits on this flag and returns an empty
	// result set without issuing any SQL — matches Django ORM
	// Model.objects.filter(id__in=[]).
	EmptyResult bool

	// OrderBy is a primary sort key that a filter asks for: the distance
	// of a fac or org distance search. listOrder puts it before the id
	// tiebreak on a plain list. A ?since= list ignores it.
	OrderBy func(*sql.Selector)
}

QueryOptions holds parsed query parameters for list endpoints.

type RowSize added in v1.16.0

type RowSize struct {
	Depth0 int
	Depth2 int
}

RowSize holds the conservative estimated serialized size in bytes per entity type at depth=0 (list-shape) and depth=2 (expanded-shape). Values are doubled from measured means so the budget check prefers false-positive 413s over OOM. Recalibrated every major milestone; drift >20% triggers a refresh.

type RowsIter added in v1.16.0

type RowsIter = func() (row any, ok bool, err error)

RowsIter is a pull-style row iterator driving StreamListResponse.

Semantics:

  • (row, true, nil) — row is the next payload element; keep iterating.
  • (nil, false, nil) — clean EOF; end of stream.
  • (nil, false, err) — abort; err is returned to the caller wrapped with the failing row index.

A "zombie" iterator that returns ok=true forever is caller-unsafe; the upstream memory budget is responsible for ensuring bounded iteration length by capping the filtered row count pre-flight.

type SyncClock added in v1.38.0

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

SyncClock holds the completion time of the newest successful sync of the local database. The handler sends it as meta.generated on a list that upstream serves from its API cache file, where meta.generated is the modification time of the file (2.83.0 api_cache.py:135). The zero value holds no time. It is safe for concurrent use.

func (*SyncClock) Set added in v1.38.0

func (c *SyncClock) Set(t time.Time)

Set stores t. A zero t clears the clock.

func (*SyncClock) Time added in v1.38.0

func (c *SyncClock) Time() time.Time

Time returns the stored time, or the zero time when the clock is nil or holds no time.

type TypeConfig

type TypeConfig struct {
	Name         string
	Fields       map[string]FieldType
	SearchFields []string
	List         ListFunc
	Count        CountFunc
	Get          GetFunc
	Match        MatchFunc
	ListIDs      ListIDsFunc
	// ListDepth is nil for the 7 types without reverse sets (childSets):
	// their list rows are the same at every depth.
	ListDepth ListDepthFunc

	// FoldedFields lists the string fields on this type that have a sibling
	// <field>_fold column populated by the sync worker.
	// When non-nil, substring / prefix / iexact filters on these fields are
	// routed to the _fold column with unifold.Fold(value) on the RHS for
	// diacritic-insensitive matching. Nil is safe —
	// map reads on nil return the zero value (false).
	FoldedFields map[string]bool

	// ForeignKeys maps the upstream name of each forward foreign key of
	// the type (the Django field name, for example "org" or "network")
	// to the local FK column in Fields. Upstream filters a key that
	// names the FK (?org=1, ?network__in=1,2, ?facility_id=2) on the FK
	// column (2.83.0 rest.py:608-631, :670-677). A relation key that
	// starts with the upstream name (?network__asn=) walks the edge
	// that owns the column. Nil when the type has no forward FK.
	ForeignKeys map[string]string

	// UpstreamIgnored lists the Fields keys that upstream never filters
	// as a key without relation segments. Such a key is ignored for any
	// operator, as upstream ignores it. Two causes exist:
	//   - queryable_field_xl renames the key to a name that matches no
	//     field (2.83.0 serializers.py:428-438): carrier fac_count
	//     becomes facility_count, netixlan net_side_id becomes
	//     network_side.
	//   - The key is a serializer field or a model property, not a
	//     model field, and no prepare_query handles it (rest.py:525-528,
	//     :633, :670): for example campus city and carrier org_name.
	// The columns stay in Fields, so they stay valid traversal targets
	// where upstream filters them (carrierfac?carrier__fac_count=).
	UpstreamIgnored map[string]bool

	// NonModelFields lists the Fields keys that are not fields of the
	// upstream model: serializer fields and model properties. The
	// upstream filter loop filters only model fields and
	// queryable_relations (2.83.0 rest.py:525-528, :633, :670), so each
	// of these keys is a prepare_query key or in UpstreamIgnored. No
	// relation key filters one of these fields on the related row.
	// queryable_relations offers only model fields
	// (serializers.py:970-996), so upstream ignores a traversal key such
	// as fac?campus__city=, and so does the mirror. In a relation key of
	// a prepare_query, the Django filter raises FieldError, and the key
	// returns 400 (Invalid query), as upstream (rest.py:488-500).
	// UpstreamIgnored is not the same set: it also holds model fields
	// that queryable_field_xl renames (carrier fac_count).
	NonModelFields map[string]bool

	// ExactCounts lists the Fields keys that a prepare_query filters with
	// an exact lookup or a get_relation_filters operator (the count
	// seeds), with the first value of the key. The filter loop ignores
	// them (queryable_field_xl renames them). A value that int() does not
	// accept is a 400, as upstream (2.83.0 serializers.py:2119-2124,
	// :3743-3748, :4531-4543). Every other plain integer key matches the
	// decimal text of the value (buildModelFieldPredicate).
	ExactCounts map[string]bool
}

TypeConfig describes a PeeringDB object type for the compatibility layer.

Directories

Path Synopsis
Package parity holds regression tests that lock pdbcompat behavior to upstream PeeringDB.
Package parity holds regression tests that lock pdbcompat behavior to upstream PeeringDB.
Package schemaannot exposes ent schema annotation types consumed by ent/schema/*.go to describe pdbcompat's Path A allowlist and per-edge FILTER_EXCLUDE.
Package schemaannot exposes ent schema annotation types consumed by ent/schema/*.go to describe pdbcompat's Path A allowlist and per-edge FILTER_EXCLUDE.

Jump to

Keyboard shortcuts

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