udbclient

package
v0.5.21 Latest Latest
Warning

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

Go to latest
Published: Aug 23, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EncodingRecordSetV1 is the always-supported V1 row encoding (Select/RecordSet).
	EncodingRecordSetV1 = "record_set_v1"
	// EncodingRecordBatchV2 is the additive typed-column batch encoding (SelectV2),
	// used only when both server and client advertise it.
	EncodingRecordBatchV2 = "record_batch_v2"
)

Wire encoding identifiers.

View Source
const DefaultIRBackend = "postgres"

DefaultIRBackend is the backend whose neutral-IR compiler lowers the envelope when the caller does not pick one explicitly. The broker resolves the concrete instance per project.

View Source
const GeneratedProtocolVersion = "1.0.0"

GeneratedProtocolVersion mirrors the wire protocol this layer targets. It is the generated companion to the hand-written udbclient.ProtocolVersion and is kept identical; both are asserted equal at package init below.

View Source
const ProtocolVersion = "1.0.0"
View Source
const SDKVersion = "0.5.21"

SDKVersion is the UDB release this generated layer was rendered from. It is baked at generation time and is the version the bundled `udb` CLI launcher (cmd/udb) will resolve.

Variables

View Source
var AllRPCs = []RPCInfo{}/* 382 elements not displayed */

AllRPCs lists every RPC across every UDB service in this build.

View Source
var BackendRoles = mustStringMap(`{"postgres":"canonical","mysql":"canonical","sqlite":"canonical","sqlserver":"canonical","clickhouse":"canonical","redis":"canonical","memcached":"projection","qdrant":"projection","weaviate":"projection","pinecone":"projection","minio":"projection","s3":"projection","azureblob":"projection","gcs":"projection","mongodb":"canonical","elasticsearch":"projection","neo4j":"canonical","cassandra":"canonical"}`)
View Source
var Entities = map[string]EntityDescriptor{
	"udb.core.analytics.entity.v1.ExecutorPerformanceSummary":     {Table: "executor_performance_summaries", PrimaryKeys: []string{"summary_id"}, Fields: []string{"summary_id", "summary_date", "executor_identity", "workload_kind", "total_dispatches", "successful_results", "timeout_count", "error_count", "avg_execution_ms", "p99_execution_ms", "avg_confidence", "success_rate", "avg_capacity_utilisation", "recorded_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/analytics/entity/v1;analyticsv1.ExecutorPerformanceSummary"},
	"udb.core.analytics.entity.v1.PipelineMetricSnapshot":         {Table: "pipeline_metric_snapshots", PrimaryKeys: []string{"snapshot_id"}, Fields: []string{"snapshot_id", "snapshot_hour", "stage_name", "tenant_id", "total_requests", "successful", "failed", "p50_latency_ms", "p95_latency_ms", "p99_latency_ms", "avg_latency_ms", "error_rate", "throughput_rps", "recorded_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/analytics/entity/v1;analyticsv1.PipelineMetricSnapshot"},
	"udb.core.analytics.entity.v1.ReconciliationAnalyticsSummary": {Table: "reconciliation_analytics_summaries", PrimaryKeys: []string{"summary_id"}, Fields: []string{"summary_id", "summary_date", "total_reconciliations", "exact_matches", "partial_conflicts", "hard_conflicts", "low_confidence_flagged", "avg_reconciliation_ms", "resolution_rate", "avg_record_confidence", "recorded_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/analytics/entity/v1;analyticsv1.ReconciliationAnalyticsSummary"},
	"udb.core.apikey.entity.v1.ApiKey":                            {Table: "api_keys", PrimaryKeys: []string{"key_id"}, Fields: []string{"key_id", "key_prefix", "key_hash", "name", "description", "owner_type", "owner_id", "scopes_json", "status", "ip_allowlist_json", "rate_limit_per_minute", "rate_limit_per_day", "created_by", "revoked_by", "revoke_reason", "expires_at", "last_used_at", "created_at", "updated_at", "deleted_at", "deleted_by", "tenant_id", "project_id", "allowed_resources_json", "metadata_json"}, Relations: mustEntityRelations(`[{"name":"api_key_usages","kind":"has_many","local_fields":["key_id"],"target_message_type":"udb.core.apikey.entity.v1.ApiKeyUsage","target_table":"udb_authn.api_key_usages","target_fields":["key_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/apikey/entity/v1;apikeyv1.ApiKey"},
	"udb.core.apikey.entity.v1.ApiKeyUsage":                       {Table: "api_key_usages", PrimaryKeys: []string{"usage_id"}, Fields: []string{"usage_id", "key_id", "endpoint", "ip_address", "http_status", "latency_ms", "rate_limited", "requested_at", "tenant_id", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"key","kind":"belongs_to","local_fields":["key_id"],"target_message_type":"udb.core.apikey.entity.v1.ApiKey","target_table":"udb_authn.api_keys","target_fields":["key_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/apikey/entity/v1;apikeyv1.ApiKeyUsage"},
	"udb.core.asset.entity.v1.Asset":                              {Table: "assets", PrimaryKeys: []string{"asset_id"}, Fields: []string{"asset_id", "tenant_id", "project_id", "file_id", "name", "media_type", "status", "metadata", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/asset/entity/v1;assetv1.Asset"},
	"udb.core.asset.entity.v1.PipelineDefinition":                 {Table: "pipeline_definitions", PrimaryKeys: []string{"definition_id"}, Fields: []string{"definition_id", "tenant_id", "name", "description", "media_type", "steps", "version", "status", "audit_info", "trigger_topic", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "version", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/asset/entity/v1;assetv1.PipelineDefinition"},
	"udb.core.asset.entity.v1.PipelineInstance":                   {Table: "pipeline_instances", PrimaryKeys: []string{"instance_id"}, Fields: []string{"instance_id", "definition_id", "asset_id", "tenant_id", "status", "current_step", "context", "correlation_id", "started_at", "completed_at", "audit_info", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/asset/entity/v1;assetv1.PipelineInstance"},
	"udb.core.asset.entity.v1.PipelineStep":                       {Table: "pipeline_steps", PrimaryKeys: []string{"step_id"}, Fields: []string{"step_id", "instance_id", "step_name", "step_type", "status", "result", "error", "retry_count", "started_at", "completed_at", "audit_info", "tenant_id", "params", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/asset/entity/v1;assetv1.PipelineStep"},
	"udb.core.authn.entity.v1.CertificateBinding":                 {Table: "certificate_bindings", PrimaryKeys: []string{"binding_id"}, Fields: []string{"binding_id", "selector_kind", "selector_value", "user_id", "tenant_id", "grant_revision", "scope_subset_json", "status", "not_before", "not_after", "revoked_at", "revoke_reason", "updated_by", "reason", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.CertificateBinding"},
	"udb.core.authn.entity.v1.Device":                             {Table: "devices", PrimaryKeys: []string{"device_id"}, Fields: []string{"device_id", "user_id", "tenant_id", "project_id", "device_name", "device_type", "fingerprint_hash", "last_ip_masked", "last_user_agent_hash", "last_seen_at", "created_at", "revoked_at", "revoked_by", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.Device"},
	"udb.core.authn.entity.v1.MfaChallenge":                       {Table: "mfa_challenges", PrimaryKeys: []string{"challenge_id"}, Fields: []string{"challenge_id", "user_id", "tenant_id", "project_id", "factor_kind", "purpose", "device_fingerprint_hash", "ip_address_masked", "attempt_count", "expires_at", "consumed_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.MfaChallenge"},
	"udb.core.authn.entity.v1.MfaPolicy":                          {Table: "mfa_policies", PrimaryKeys: []string{"policy_id"}, Fields: []string{"policy_id", "tenant_id", "require_mfa", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.MfaPolicy"},
	"udb.core.authn.entity.v1.OTP":                                {Table: "otps", PrimaryKeys: []string{"otp_id"}, Fields: []string{"otp_id", "user_id", "otp_type", "code_hash", "delivery_channel", "delivery_address", "status", "attempt_count", "superseded_by_id", "expires_at", "used_at", "created_at", "correlation_id", "tenant_id", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"otps","kind":"has_many","local_fields":["otp_id"],"target_message_type":"udb.core.authn.entity.v1.OTP","target_table":"udb_authn.otps","target_fields":["superseded_by_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"superseded_by","kind":"belongs_to","local_fields":["superseded_by_id"],"target_message_type":"udb.core.authn.entity.v1.OTP","target_table":"udb_authn.otps","target_fields":["otp_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.OTP"},
	"udb.core.authn.entity.v1.RecoveryCode":                       {Table: "recovery_codes", PrimaryKeys: []string{"recovery_code_id"}, Fields: []string{"recovery_code_id", "user_id", "code_hash", "used_at", "created_at", "tenant_id", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.RecoveryCode"},
	"udb.core.authn.entity.v1.ServiceAccountGrant":                {Table: "service_account_grants", PrimaryKeys: []string{"grant_id"}, Fields: []string{"grant_id", "user_id", "service_identity", "tenant_id", "project_id", "approved_scopes_json", "status", "revision", "updated_by", "reason", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "revision", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.ServiceAccountGrant"},
	"udb.core.authn.entity.v1.Session":                            {Table: "sessions", PrimaryKeys: []string{"session_id"}, Fields: []string{"session_id", "user_id", "session_type", "session_token_lookup", "session_token_hash", "csrf_token_hash", "access_token_jti", "refresh_token_jti", "device_type", "device_name", "ip_address", "user_agent", "is_active", "expires_at", "last_active_at", "revoked_by", "revoke_reason", "created_at", "tenant_id", "project_id", "principal_id", "provider_id", "auth_method", "scopes_json", "metadata_json", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"revoked_by","kind":"belongs_to","local_fields":["revoked_by"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.Session"},
	"udb.core.authn.entity.v1.SigningKey":                         {Table: "signing_keys", PrimaryKeys: []string{"key_id"}, Fields: []string{"key_id", "tenant_id", "algorithm", "public_material", "encrypted_private_material", "kms_key_ref", "state", "not_before", "not_after", "created_at", "retired_at", "created_by", "retired_by", "rotation_reason", "updated_at"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.SigningKey"},
	"udb.core.authn.entity.v1.TokenFamily":                        {Table: "token_families", PrimaryKeys: []string{"family_id"}, Fields: []string{"family_id", "session_id", "user_id", "principal_id", "tenant_id", "project_id", "device_id", "current_refresh_jti_hash", "previous_refresh_jti_hash", "reuse_detected_at", "revoked_at", "revocation_reason", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.TokenFamily"},
	"udb.core.authn.entity.v1.TokenRevocation":                    {Table: "token_revocations", PrimaryKeys: []string{"jti_hash"}, Fields: []string{"jti_hash", "token_type", "tenant_id", "expires_at", "revoked_at", "revoked_by", "reason", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.TokenRevocation"},
	"udb.core.authn.entity.v1.User":                               {Table: "users", PrimaryKeys: []string{"user_id"}, Fields: []string{"user_id", "username", "email", "password_hash", "account_kind", "status", "tenant_id", "full_name", "totp_secret_enc", "mfa_enabled", "failed_login_count", "locked_until", "email_verified_at", "last_login_at", "created_by", "created_at", "updated_at", "deleted_at", "deleted_by", "project_id", "external_provider_id", "external_subject", "locale", "timezone", "profile_attributes_json", "external_references_json", "phone", "phone_verified_at"}, Relations: mustEntityRelations(`[{"name":"certificate_bindings","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.CertificateBinding","target_table":"udb_authn.certificate_bindings","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"created_by","kind":"belongs_to","local_fields":["created_by"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"notification_logs","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.notification.entity.v1.NotificationLog","target_table":"udb_notification.notification_logs","target_fields":["recipient_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"otps","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.OTP","target_table":"udb_authn.otps","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"recovery_codes","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.RecoveryCode","target_table":"udb_authn.recovery_codes","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"role_permissions","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authz.entity.v1.RolePermission","target_table":"udb_authz.role_permissions","target_fields":["granted_by"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"service_account_grants","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.ServiceAccountGrant","target_table":"udb_authn.service_account_grants","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"sessions","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.Session","target_table":"udb_authn.sessions","target_fields":["revoked_by"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"sessions","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.Session","target_table":"udb_authn.sessions","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"user_roles","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authz.entity.v1.UserRole","target_table":"udb_authz.user_roles","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"users","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["created_by"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"webauthn_credentials","kind":"has_many","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.WebAuthnCredential","target_table":"udb_authn.webauthn_credentials","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.User"},
	"udb.core.authn.entity.v1.WebAuthnCredential":                 {Table: "webauthn_credentials", PrimaryKeys: []string{"credential_id"}, Fields: []string{"credential_id", "user_id", "passkey_json", "label", "tenant_id", "project_id", "created_at", "updated_at", "last_used_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.WebAuthnCredential"},
	"udb.core.authn.entity.v1.WebAuthnPolicy":                     {Table: "webauthn_policies", PrimaryKeys: []string{"policy_id"}, Fields: []string{"policy_id", "tenant_id", "required_user_verification", "required_resident_key", "allowed_attestation_conveyance", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authn/entity/v1;authnv1.WebAuthnPolicy"},
	"udb.core.authz.entity.v1.AccessDecisionAudit":                {Table: "access_decision_audits", PrimaryKeys: []string{"decision_audit_id"}, Fields: []string{"decision_audit_id", "user_id", "domain", "object", "action", "effect", "decision_source", "matched_rule", "reason", "ip_address", "correlation_id", "decided_at", "tenant_id", "decision_id", "policy_version", "relationship_version", "purpose", "scopes", "matched_policy_ids", "project_id", "actor_kind", "resource_type", "trace_id", "span_id", "user_agent_hash", "decision_input", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.AccessDecisionAudit"},
	"udb.core.authz.entity.v1.AuthzRevision":                      {Table: "authz_revisions", PrimaryKeys: []string{"revision_id"}, Fields: []string{"revision_id", "tenant_id", "project_id", "policy_revision", "relationship_revision", "content_hash", "changed_by", "changed_at", "change_type", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.AuthzRevision"},
	"udb.core.authz.entity.v1.PolicyApproval":                     {Table: "policy_approvals", PrimaryKeys: []string{"approval_id"}, Fields: []string{"approval_id", "draft_id", "tenant_id", "actor", "role", "decision", "reason", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"draft","kind":"belongs_to","local_fields":["draft_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyDraft","target_table":"udb_authz.policy_drafts","target_fields":["draft_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyApproval"},
	"udb.core.authz.entity.v1.PolicyCanary":                       {Table: "policy_canaries", PrimaryKeys: []string{"canary_id"}, Fields: []string{"canary_id", "policy_set_id", "policy_version_id", "scope_kind", "scope_values", "state", "started_at", "success_window_secs", "metric_threshold", "created_by", "tenant_id", "project_id", "min_samples", "rollback_version_id", "outcome_reason", "revision", "created_at", "updated_at"}, Relations: mustEntityRelations(`[{"name":"policy_set","kind":"belongs_to","local_fields":["policy_set_id"],"target_message_type":"udb.core.authz.entity.v1.PolicySet","target_table":"udb_authz.policy_sets","target_fields":["policy_set_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"policy_version","kind":"belongs_to","local_fields":["policy_version_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyVersion","target_table":"udb_authz.policy_versions","target_fields":["policy_version_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "revision", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyCanary"},
	"udb.core.authz.entity.v1.PolicyDraft":                        {Table: "policy_drafts", PrimaryKeys: []string{"draft_id"}, Fields: []string{"draft_id", "tenant_id", "project_id", "title", "description", "proposed_policies_json", "proposed_tuples_json", "base_version_id", "status", "author", "high_risk", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"policy_approvals","kind":"has_many","local_fields":["draft_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyApproval","target_table":"udb_authz.policy_approvals","target_fields":["draft_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyDraft"},
	"udb.core.authz.entity.v1.PolicyRule":                         {Table: "policy_rules", PrimaryKeys: []string{"policy_id"}, Fields: []string{"policy_id", "subject", "domain", "object", "action", "effect", "condition", "description", "is_active", "created_by", "created_at", "updated_at", "deleted_at", "tenant_id", "deleted_by", "project_id", "resource_type", "attributes_json"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyRule"},
	"udb.core.authz.entity.v1.PolicySet":                          {Table: "policy_sets", PrimaryKeys: []string{"policy_set_id"}, Fields: []string{"policy_set_id", "tenant_id", "project_id", "name", "active_version_id", "rollback_version_id", "description", "created_by", "created_at", "updated_at", "deleted_at"}, Relations: mustEntityRelations(`[{"name":"policy_canaries","kind":"has_many","local_fields":["policy_set_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyCanary","target_table":"udb_authz.policy_canaries","target_fields":["policy_set_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"policy_versions","kind":"has_many","local_fields":["policy_set_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyVersion","target_table":"udb_authz.policy_versions","target_fields":["policy_set_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicySet"},
	"udb.core.authz.entity.v1.PolicySimulation":                   {Table: "policy_simulations", PrimaryKeys: []string{"simulation_id"}, Fields: []string{"simulation_id", "policy_version_id", "principal_json", "resource_json", "action", "purpose", "active_decision_json", "draft_decision_json", "diff_json", "tenant_id", "project_id", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicySimulation"},
	"udb.core.authz.entity.v1.PolicyTuple":                        {Table: "policy_tuples", PrimaryKeys: []string{"policy_tuple_id"}, Fields: []string{"policy_tuple_id", "tuple_kind", "subject", "domain", "object", "action", "effect", "condition", "tenant_id", "project_id", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyTuple"},
	"udb.core.authz.entity.v1.PolicyVersion":                      {Table: "policy_versions", PrimaryKeys: []string{"policy_version_id"}, Fields: []string{"policy_version_id", "policy_set_id", "version_number", "state", "snapshot_hash", "created_by", "created_at", "activated_by", "activated_at", "rollback_of", "change_reason", "revision", "content_hash", "tenant_id", "project_id", "payload_json", "high_risk", "submitted_by", "source_draft_id", "updated_at"}, Relations: mustEntityRelations(`[{"name":"policy_canaries","kind":"has_many","local_fields":["policy_version_id"],"target_message_type":"udb.core.authz.entity.v1.PolicyCanary","target_table":"udb_authz.policy_canaries","target_fields":["policy_version_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"policy_set","kind":"belongs_to","local_fields":["policy_set_id"],"target_message_type":"udb.core.authz.entity.v1.PolicySet","target_table":"udb_authz.policy_sets","target_fields":["policy_set_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "revision", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.PolicyVersion"},
	"udb.core.authz.entity.v1.Role":                               {Table: "roles", PrimaryKeys: []string{"role_id"}, Fields: []string{"role_id", "name", "description", "is_system", "is_active", "created_by", "created_at", "updated_at", "deleted_at", "tenant_id", "deleted_by", "role_code", "domain", "project_id", "scope_type", "access_surface", "metadata_json"}, Relations: mustEntityRelations(`[{"name":"role_permissions","kind":"has_many","local_fields":["role_id"],"target_message_type":"udb.core.authz.entity.v1.RolePermission","target_table":"udb_authz.role_permissions","target_fields":["role_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"user_roles","kind":"has_many","local_fields":["role_id"],"target_message_type":"udb.core.authz.entity.v1.UserRole","target_table":"udb_authz.user_roles","target_fields":["role_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.Role"},
	"udb.core.authz.entity.v1.RolePermission":                     {Table: "role_permissions", PrimaryKeys: []string{"role_permission_id"}, Fields: []string{"role_permission_id", "role_id", "permission_code", "granted_by", "granted_at", "tenant_id", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"granted_by","kind":"belongs_to","local_fields":["granted_by"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"role","kind":"belongs_to","local_fields":["role_id"],"target_message_type":"udb.core.authz.entity.v1.Role","target_table":"udb_authz.roles","target_fields":["role_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.RolePermission"},
	"udb.core.authz.entity.v1.UserRole":                           {Table: "user_roles", PrimaryKeys: []string{"user_role_id"}, Fields: []string{"user_role_id", "user_id", "role_id", "domain", "assigned_by", "assigned_at", "expires_at", "created_at", "updated_at", "created_by", "tenant_id"}, Relations: mustEntityRelations(`[{"name":"role","kind":"belongs_to","local_fields":["role_id"],"target_message_type":"udb.core.authz.entity.v1.Role","target_table":"udb_authz.roles","target_fields":["role_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"user","kind":"belongs_to","local_fields":["user_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/authz/entity/v1;authzv1.UserRole"},
	"udb.core.backup.entity.v1.BackupPolicy":                      {Table: "backup_policies", PrimaryKeys: []string{"policy_id"}, Fields: []string{"policy_id", "tenant_id", "policy_name", "schedule_cron", "retention_days", "max_retained_backups", "enabled", "object_backend", "object_bucket", "created_at", "updated_at", "metadata_json", "project_id", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/backup/entity/v1;backupv1.BackupPolicy"},
	"udb.core.backup.entity.v1.BackupRun":                         {Table: "backup_runs", PrimaryKeys: []string{"backup_id"}, Fields: []string{"backup_id", "tenant_id", "kind", "status", "object_prefix", "manifest_checksum", "table_count", "total_rows", "excluded_count", "source_tenant_id", "target_tenant_id", "error_message", "created_at", "completed_at", "metadata_json", "project_id", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/backup/entity/v1;backupv1.BackupRun"},
	"udb.core.config.entity.v1.Flag":                              {Table: "flags", PrimaryKeys: []string{"flag_id"}, Fields: []string{"flag_id", "tenant_id", "project_id", "environment", "flag_key", "value_type", "value_json", "enabled", "rollout_percentage", "rollout_context_key", "revision", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "revision", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/config/entity/v1;configv1.Flag"},
	"udb.core.control.entity.v1.ControlPlaneNodeState":            {Table: "control_plane_node_states", PrimaryKeys: []string{"node_state_id"}, Fields: []string{"node_state_id", "node_id", "resource_type", "subscribed_names", "accepted_version", "last_good_version", "last_response_nonce", "nack_error_detail", "nonce_counter", "created_at", "updated_at", "served_snapshots", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/control/entity/v1;controlv1.ControlPlaneNodeState"},
	"udb.core.control.entity.v1.ControlPlaneResource":             {Table: "control_plane_resources", PrimaryKeys: []string{"resource_id"}, Fields: []string{"resource_id", "resource_type", "name", "tenant_id", "project_id", "version", "content_hash", "payload_json", "updated_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "version", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/control/entity/v1;controlv1.ControlPlaneResource"},
	"udb.core.embedding.entity.v1.EmbeddingDocument":              {Table: "embedding_documents", PrimaryKeys: []string{"document_id"}, Fields: []string{"document_id", "tenant_id", "project_id", "external_id", "title", "raw_text", "storage_object_ref", "content_type", "doc_version", "model_id", "target_collection", "status", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"model","kind":"belongs_to","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingModel","target_table":"udb_embedding.embedding_models","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/embedding/entity/v1;embeddingv1.EmbeddingDocument"},
	"udb.core.embedding.entity.v1.EmbeddingJob":                   {Table: "embedding_jobs", PrimaryKeys: []string{"job_id"}, Fields: []string{"job_id", "tenant_id", "project_id", "source_name", "document_id", "job_type", "mode", "status", "rows_enumerated", "chunks_emitted", "vectors_stored", "failed", "error", "metadata_json", "created_at", "started_at", "finished_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"embedding_work_items","kind":"has_many","local_fields":["job_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingWorkItem","target_table":"udb_embedding.embedding_work_items","target_fields":["job_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/embedding/entity/v1;embeddingv1.EmbeddingJob"},
	"udb.core.embedding.entity.v1.EmbeddingModel":                 {Table: "embedding_models", PrimaryKeys: []string{"model_id", "tenant_id"}, Fields: []string{"model_id", "tenant_id", "provider", "model_name", "version", "dimensions", "matryoshka_dims_json", "distance_metric", "normalize", "output_dtype", "rescore", "max_input_tokens", "tokenizer", "task_type", "asymmetric", "provider_endpoint_ref", "status", "retire_after", "replacement_model_id", "vector_backend", "vector_instance", "collection_alias", "active_collection", "chunking_strategy", "chunk_tokens", "chunk_overlap_tokens", "contextual_retrieval", "late_chunking", "tenant_state", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"embedding_documents","kind":"has_many","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingDocument","target_table":"udb_embedding.embedding_documents","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"},{"name":"embedding_models","kind":"has_many","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingModel","target_table":"udb_embedding.embedding_models","target_fields":["replacement_model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"},{"name":"embedding_sources","kind":"has_many","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingSource","target_table":"udb_embedding.embedding_sources","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"},{"name":"embedding_work_items","kind":"has_many","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingWorkItem","target_table":"udb_embedding.embedding_work_items","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"},{"name":"replacement_model","kind":"belongs_to","local_fields":["replacement_model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingModel","target_table":"udb_embedding.embedding_models","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"}]`), VersionField: "version", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/embedding/entity/v1;embeddingv1.EmbeddingModel"},
	"udb.core.embedding.entity.v1.EmbeddingSource":                {Table: "embedding_sources", PrimaryKeys: []string{"source_id"}, Fields: []string{"source_id", "tenant_id", "source_name", "source_message_type", "text_fields_json", "target_collection", "model_id", "tenant_column", "source_cdc_topic", "status", "created_at", "updated_at", "metadata_json", "created_by"}, Relations: mustEntityRelations(`[{"name":"model","kind":"belongs_to","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingModel","target_table":"udb_embedding.embedding_models","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/embedding/entity/v1;embeddingv1.EmbeddingSource"},
	"udb.core.embedding.entity.v1.EmbeddingWorkItem":              {Table: "embedding_work_items", PrimaryKeys: []string{"work_item_id"}, Fields: []string{"work_item_id", "tenant_id", "project_id", "job_id", "source_name", "parent_pk", "point_id", "document_id", "doc_version", "chunk_seq", "chunk_count", "chunk_hash", "chunk_text", "model_id", "target_collection", "status", "attempt_count", "max_attempts", "last_error", "retryable", "token_count", "next_attempt_at", "created_at", "last_emitted_at", "acked_at", "updated_at", "parent_text", "char_start", "char_end", "token_start", "token_end", "created_by"}, Relations: mustEntityRelations(`[{"name":"job","kind":"belongs_to","local_fields":["job_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingJob","target_table":"udb_embedding.embedding_jobs","target_fields":["job_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"model","kind":"belongs_to","local_fields":["model_id","tenant_id"],"target_message_type":"udb.core.embedding.entity.v1.EmbeddingModel","target_table":"udb_embedding.embedding_models","target_fields":["model_id","tenant_id"],"on_delete":"RESTRICT","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/embedding/entity/v1;embeddingv1.EmbeddingWorkItem"},
	"udb.core.idp.entity.v1.ExternalIdentity":                     {Table: "external_identities", PrimaryKeys: []string{"external_identity_id"}, Fields: []string{"external_identity_id", "tenant_id", "provider_id", "subject", "user_id", "email", "email_verified", "linked_at", "last_login_at", "deleted_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"provider","kind":"belongs_to","local_fields":["provider_id"],"target_message_type":"udb.core.idp.entity.v1.IdentityProvider","target_table":"udb_idp.identity_providers","target_fields":["provider_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/idp/entity/v1;idpv1.ExternalIdentity"},
	"udb.core.idp.entity.v1.IdentityProvider":                     {Table: "identity_providers", PrimaryKeys: []string{"provider_id"}, Fields: []string{"provider_id", "tenant_id", "kind", "display_name", "issuer", "entity_id", "jwks_url", "saml_metadata_url", "client_ids_json", "audiences_json", "claim_mapping_json", "group_mapping_json", "jit_policy_json", "account_linking_policy", "enabled", "client_secret", "saml_signing_key_pem", "saml_idp_certs_json", "saml_sso_url", "health", "last_jwks_refresh_at", "last_jwks_refresh_status", "created_by", "updated_by", "created_at", "updated_at", "deleted_at"}, Relations: mustEntityRelations(`[{"name":"external_identities","kind":"has_many","local_fields":["provider_id"],"target_message_type":"udb.core.idp.entity.v1.ExternalIdentity","target_table":"udb_idp.external_identities","target_fields":["provider_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"scim_directory_state","kind":"has_many","local_fields":["provider_id"],"target_message_type":"udb.core.idp.entity.v1.ScimDirectoryState","target_table":"udb_idp.scim_directory_state","target_fields":["provider_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/idp/entity/v1;idpv1.IdentityProvider"},
	"udb.core.idp.entity.v1.SamlReplayEntry":                      {Table: "saml_replay_entries", PrimaryKeys: []string{"saml_replay_entry_id"}, Fields: []string{"saml_replay_entry_id", "tenant_id", "provider_id", "assertion_id", "not_on_or_after", "consumed_at"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/idp/entity/v1;idpv1.SamlReplayEntry"},
	"udb.core.idp.entity.v1.ScimDirectoryState":                   {Table: "scim_directory_state", PrimaryKeys: []string{"scim_directory_state_id"}, Fields: []string{"scim_directory_state_id", "tenant_id", "provider_id", "cursor", "last_sync_at", "failure_count", "last_error", "deprovision_policy", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"provider","kind":"belongs_to","local_fields":["provider_id"],"target_message_type":"udb.core.idp.entity.v1.IdentityProvider","target_table":"udb_idp.identity_providers","target_fields":["provider_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/idp/entity/v1;idpv1.ScimDirectoryState"},
	"udb.core.lock.entity.v1.Lock":                                {Table: "locks", PrimaryKeys: []string{"lock_id"}, Fields: []string{"lock_id", "tenant_id", "lock_name", "owner_id", "fencing_token", "lease_ttl_seconds", "status", "acquired_at", "expires_at", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/lock/entity/v1;lockv1.Lock"},
	"udb.core.metering.entity.v1.QuotaRule":                       {Table: "quota_rules", PrimaryKeys: []string{"quota_id"}, Fields: []string{"quota_id", "tenant_id", "project_id", "metric", "limit_value", "window_seconds", "enabled", "revision", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "revision", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/metering/entity/v1;meteringv1.QuotaRule"},
	"udb.core.metering.entity.v1.UsageEvent":                      {Table: "usage_events", PrimaryKeys: []string{"usage_id"}, Fields: []string{"usage_id", "tenant_id", "principal_id", "method", "unit", "quantity", "occurred_at", "occurred_at_unix", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/metering/entity/v1;meteringv1.UsageEvent"},
	"udb.core.notification.entity.v1.Notification":                {Table: "notifications", PrimaryKeys: []string{"notification_id"}, Fields: []string{"notification_id", "recipient_id", "type", "channel", "subject", "message", "template_data", "priority", "status", "scheduled_at", "sent_at", "delivered_at", "read_at", "created_at", "retry_count", "error_message", "tenant_id", "deleted_at", "deleted_by", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/notification/entity/v1;notificationv1.Notification"},
	"udb.core.notification.entity.v1.NotificationDeliveryAttempt": {Table: "notification_delivery_attempts", PrimaryKeys: []string{"attempt_id"}, Fields: []string{"attempt_id", "notification_id", "tenant_id", "channel", "provider", "status", "attempt_count", "last_error", "provider_message_id", "created_at", "updated_at", "project_id", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/notification/entity/v1;notificationv1.NotificationDeliveryAttempt"},
	"udb.core.notification.entity.v1.NotificationLog":             {Table: "notification_logs", PrimaryKeys: []string{"log_id"}, Fields: []string{"log_id", "template_id", "event_type", "channel", "recipient_id", "recipient_address", "tenant_id", "project_id", "resource_type", "resource_id", "resource_name", "correlation_id", "status", "error_message", "provider_message_id", "retry_count", "sent_at", "delivered_at", "created_at", "rendered_subject", "rendered_body", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"recipient","kind":"belongs_to","local_fields":["recipient_id"],"target_message_type":"udb.core.authn.entity.v1.User","target_table":"udb_authn.users","target_fields":["user_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"template","kind":"belongs_to","local_fields":["template_id"],"target_message_type":"udb.core.notification.entity.v1.NotificationTemplate","target_table":"udb_notification.notification_templates","target_fields":["template_id"],"on_delete":"SET NULL","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/notification/entity/v1;notificationv1.NotificationLog"},
	"udb.core.notification.entity.v1.NotificationPreference":      {Table: "notification_preferences", PrimaryKeys: []string{"preference_id"}, Fields: []string{"preference_id", "user_id", "tenant_id", "channel", "event_type", "is_opted_out", "created_at", "updated_at", "created_by", "project_id"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/notification/entity/v1;notificationv1.NotificationPreference"},
	"udb.core.notification.entity.v1.NotificationTemplate":        {Table: "notification_templates", PrimaryKeys: []string{"template_id"}, Fields: []string{"template_id", "event_type", "channel", "subject_template", "body_template", "locale", "is_active", "created_at", "updated_at", "deleted_at", "created_by", "deleted_by", "tenant_id", "project_id"}, Relations: mustEntityRelations(`[{"name":"notification_logs","kind":"has_many","local_fields":["template_id"],"target_message_type":"udb.core.notification.entity.v1.NotificationLog","target_table":"udb_notification.notification_logs","target_fields":["template_id"],"on_delete":"SET NULL","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/notification/entity/v1;notificationv1.NotificationTemplate"},
	"udb.core.scheduler.entity.v1.ScheduledJob":                   {Table: "scheduled_jobs", PrimaryKeys: []string{"job_id"}, Fields: []string{"job_id", "tenant_id", "project_id", "name", "schedule_type", "cron_expression", "payload", "target_topic", "status", "next_fire_at", "last_fired_at", "max_attempts", "attempt_count", "backoff_seconds", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/scheduler/entity/v1;schedulerv1.ScheduledJob"},
	"udb.core.search.entity.v1.SearchIndex":                       {Table: "search_indexes", PrimaryKeys: []string{"index_id"}, Fields: []string{"index_id", "tenant_id", "index_name", "source_message_type", "backend", "resource_name", "vector_dims", "tenant_column", "source_cdc_topic", "status", "created_at", "updated_at", "metadata_json", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/search/entity/v1;searchv1.SearchIndex"},
	"udb.core.storage.entity.v1.File":                             {Table: "files", PrimaryKeys: []string{"file_id"}, Fields: []string{"file_id", "tenant_id", "project_id", "filename", "content_type", "size_bytes", "backend", "bucket", "object_key", "url", "cdn_url", "file_type", "reference_id", "reference_type", "is_public", "status", "checksum", "expires_at", "uploaded_by", "audit_info", "deleted_at", "deleted_by", "scan_verdict", "scanned_at", "scanned_by", "scan_detail", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/storage/entity/v1;storagev1.File"},
	"udb.core.tenant.entity.v1.Tenant":                            {Table: "tenants", PrimaryKeys: []string{"tenant_id"}, Fields: []string{"tenant_id", "code", "name", "type", "status", "parent_tenant_id", "config", "branding", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"parent_tenant","kind":"belongs_to","local_fields":["parent_tenant_id"],"target_message_type":"udb.core.tenant.entity.v1.Tenant","target_table":"udb_tenant.tenants","target_fields":["tenant_id"],"on_delete":"SET NULL","on_update":"NO ACTION"},{"name":"tenant_configs","kind":"has_many","local_fields":["tenant_id"],"target_message_type":"udb.core.tenant.entity.v1.TenantConfig","target_table":"udb_tenant.tenant_configs","target_fields":["tenant_id"],"on_delete":"CASCADE","on_update":"NO ACTION"},{"name":"tenants","kind":"has_many","local_fields":["tenant_id"],"target_message_type":"udb.core.tenant.entity.v1.Tenant","target_table":"udb_tenant.tenants","target_fields":["parent_tenant_id"],"on_delete":"SET NULL","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/tenant/entity/v1;tenantv1.Tenant"},
	"udb.core.tenant.entity.v1.TenantConfig":                      {Table: "tenant_configs", PrimaryKeys: []string{"config_id"}, Fields: []string{"id", "tenant_id", "config_key", "config_value", "type", "description", "audit_info", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[{"name":"tenant","kind":"belongs_to","local_fields":["tenant_id"],"target_message_type":"udb.core.tenant.entity.v1.Tenant","target_table":"udb_tenant.tenants","target_fields":["tenant_id"],"on_delete":"CASCADE","on_update":"NO ACTION"}]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/tenant/entity/v1;tenantv1.TenantConfig"},
	"udb.core.vault.entity.v1.VaultDbCredentialLease":             {Table: "vault_db_credential_leases", PrimaryKeys: []string{"lease_id"}, Fields: []string{"lease_id", "tenant_id", "role_name", "username", "parent_role", "backend", "issued_at", "expires_at", "revoked_at", "state", "metadata_json", "project_id", "idempotency_key", "request_hash", "credential_ciphertext", "target_instance", "last_error", "revoke_reason", "revocation_operation_id", "revocation_requested_at", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "project_id", GoType: "github.com/udb-project/udb/gen/go/udb/core/vault/entity/v1;vaultv1.VaultDbCredentialLease"},
	"udb.core.vault.entity.v1.VaultSecret":                        {Table: "vault_secrets", PrimaryKeys: []string{"secret_id"}, Fields: []string{"secret_id", "tenant_id", "secret_path", "version", "ciphertext", "data_key_wrapped", "state", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "version", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/vault/entity/v1;vaultv1.VaultSecret"},
	"udb.core.vault.entity.v1.VaultTransitKey":                    {Table: "vault_transit_keys", PrimaryKeys: []string{"key_id"}, Fields: []string{"key_id", "tenant_id", "key_name", "version", "algorithm", "wrapped_key_material", "state", "metadata_json", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "version", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/vault/entity/v1;vaultv1.VaultTransitKey"},
	"udb.core.webhook.entity.v1.WebhookDelivery":                  {Table: "webhook_deliveries", PrimaryKeys: []string{"delivery_id"}, Fields: []string{"delivery_id", "tenant_id", "endpoint_id", "event_id", "topic", "status", "attempt_count", "response_status", "signature", "last_error", "payload_json", "delivered_at", "audit_info", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/webhook/entity/v1;webhookv1.WebhookDelivery"},
	"udb.core.webhook.entity.v1.WebhookEndpoint":                  {Table: "webhook_endpoints", PrimaryKeys: []string{"endpoint_id"}, Fields: []string{"endpoint_id", "tenant_id", "url", "topic_pattern", "signing_secret", "active", "description", "max_attempts", "metadata_json", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/webhook/entity/v1;webhookv1.WebhookEndpoint"},
	"udb.core.webrtc.entity.v1.Peer":                              {Table: "peers", PrimaryKeys: []string{"peer_id"}, Fields: []string{"peer_id", "room_id", "tenant_id", "display_name", "state", "metadata", "user_agent", "joined_at", "left_at", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/webrtc/entity/v1;webrtcv1.Peer"},
	"udb.core.webrtc.entity.v1.Room":                              {Table: "rooms", PrimaryKeys: []string{"room_id"}, Fields: []string{"room_id", "tenant_id", "name", "state", "max_participants", "participant_count", "config", "created_by", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/webrtc/entity/v1;webrtcv1.Room"},
	"udb.core.webrtc.entity.v1.Track":                             {Table: "tracks", PrimaryKeys: []string{"track_id"}, Fields: []string{"track_id", "room_id", "peer_id", "tenant_id", "kind", "label", "state", "settings", "metadata", "audit_info", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/webrtc/entity/v1;webrtcv1.Track"},
	"udb.core.workflow.entity.v1.WorkflowInstance":                {Table: "workflow_instances", PrimaryKeys: []string{"workflow_id"}, Fields: []string{"workflow_id", "tenant_id", "project_id", "workflow_type", "status", "current_step", "total_steps", "payload", "compensations", "correlation_id", "saga_id", "pending_signal", "last_error", "next_run_at", "last_transition_at", "audit_info", "deleted_at", "deleted_by", "created_at", "updated_at", "created_by"}, Relations: mustEntityRelations(`[]`), VersionField: "", TenantField: "tenant_id", ProjectField: "", GoType: "github.com/udb-project/udb/gen/go/udb/core/workflow/entity/v1;workflowv1.WorkflowInstance"},
}

Entities is the catalog-derived entity registry, generated from the annotated entity messages so (*Client).Entity can default conflict_fields / primary keys from the manifest instead of the caller always passing Key(...). The EntityDescriptor type is hand-written in entity.go (this block only emits the map). Primary-key entries arrive pre-quoted and comma-separated from the generator, so they drop straight inside the []string{...} literal.

View Source
var ErrAuthzDenied = errors.New("udb: authorization denied")

ErrAuthzDenied is the sentinel a denied Require unwraps to. Callers can match it with errors.Is(err, ErrAuthzDenied) without depending on the concrete *AuthzDeniedError type.

View Source
var ErrPolicyBundleSignature = errors.New("udb: policy bundle signature mismatch")

ErrPolicyBundleSignature is the sentinel a failed VerifyPolicyBundle unwraps to. Match it with errors.Is(err, ErrPolicyBundleSignature).

View Source
var ORMTiers = mustStringMap(`{"postgres":"relational","mysql":"relational","sqlite":"relational","sqlserver":"relational","clickhouse":"relational","redis":"kv","memcached":"kv","qdrant":"vector","weaviate":"vector","pinecone":"vector","minio":"blob","s3":"blob","azureblob":"blob","gcs":"blob","mongodb":"document","elasticsearch":"vector","neo4j":"graph","cassandra":"relational"}`)
View Source
var ServiceRPCCounts = map[string]int{
	"udb.core.analytics.services.v1.AnalyticsService":       7,
	"udb.core.apikey.services.v1.ApiKeyService":             9,
	"udb.core.asset.services.v1.AssetService":               8,
	"udb.core.authn.services.v1.AuthnService":               60,
	"udb.core.authz.services.v1.AuthzService":               41,
	"udb.core.backup.services.v1.BackupService":             8,
	"udb.core.cache.services.v1.CacheService":               7,
	"udb.core.config.services.v1.ConfigService":             5,
	"udb.core.control.services.v1.ControlPlaneService":      6,
	"udb.core.embedding.services.v1.EmbeddingService":       19,
	"udb.core.idp.services.v1.IdentityProviderService":      27,
	"udb.core.livequery.services.v1.LiveQueryService":       1,
	"udb.core.lock.services.v1.LockService":                 5,
	"udb.core.metering.services.v1.MeteringService":         6,
	"udb.core.notification.services.v1.NotificationService": 12,
	"udb.core.scheduler.services.v1.SchedulerService":       6,
	"udb.core.search.services.v1.SearchService":             5,
	"udb.core.storage.services.v1.StorageService":           10,
	"udb.core.tenant.services.v1.TenantService":             8,
	"udb.core.vault.services.v1.VaultService":               22,
	"udb.core.webhook.services.v1.WebhookService":           6,
	"udb.core.webrtc.services.v1.PeerService":               5,
	"udb.core.webrtc.services.v1.RoomService":               9,
	"udb.core.webrtc.services.v1.SignalingService":          1,
	"udb.core.webrtc.services.v1.TrackService":              4,
	"udb.core.webrtc.services.v1.TurnService":               1,
	"udb.core.workflow.services.v1.WorkflowService":         5,
	"udb.services.v1.DataBroker":                            79,
}

ServiceRPCCounts maps each service's full name to its RPC count.

Functions

func AfterWrite added in v0.4.0

func AfterWrite(rc *entityv1.RequestContext, r WriteReceipt, maxWaitMs uint64)

AfterWrite stamps a read fence derived from a write receipt onto a single, caller-supplied per-read RequestContext so the follow-up read observes its own write. It NEVER touches shared Udb/facade metadata — the fence rides only this one request (guardrail: no leaking a fence into unrelated reads). An empty receipt leaves rc untouched.

func CorrelationID added in v0.4.0

func CorrelationID(ctx context.Context) string

CorrelationID returns the request's correlation id, or "" when unset.

func HTTPMiddleware added in v0.4.0

func HTTPMiddleware(next http.Handler) http.Handler

HTTPMiddleware is a standard net/http middleware: it reads the canonical UDB headers off each inbound request, builds a Metadata, and stashes it on the request context before delegating to next. Downstream handlers read it with FromContext / MetadataFromContext.

Usage:

mux := http.NewServeMux()
srv := &http.Server{Handler: udbclient.HTTPMiddleware(mux)}

func IsCASConflict added in v0.4.19

func IsCASConflict(err error) bool

IsCASConflict reports whether err is a compare-and-swap precondition failure — the target row was absent or a field no longer matched the expected value. Check it after Upsert(WithExpected) or Delete(WithDeleteExpected) to decide whether to re-read and retry the optimistic operation. Detected by the FAILED_PRECONDITION code the broker returns for a CAS mismatch (it writes nothing on failure), so a retry loop is safe.

func RawDispatchRequest added in v0.4.0

func RawDispatchRequest(backend, operation, specJSON, resourceName string) *entityv1.GenericDispatchRequest

RawDispatchRequest is the ESCAPE HATCH: build a raw GenericDispatchRequest with caller-authored spec_json, bypassing the typed IR builder. The mediated builders above are preferred; this preserves the pre-existing raw capability for advanced/admin callers. Like the builders, it sets no tenant/project on the body.

func StreamServerInterceptor added in v0.4.0

func StreamServerInterceptor(
	srv any,
	ss grpc.ServerStream,
	_ *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error

StreamServerInterceptor is the streaming counterpart of UnaryServerInterceptor: it stashes the per-request Metadata on the stream's context so streaming handlers see the same identity.

func TenantID added in v0.4.0

func TenantID(ctx context.Context) string

TenantID returns the request's tenant id, or "" when unset.

func ToLogicalValue added in v0.4.0

func ToLogicalValue(value any) any

ToLogicalValue encodes a Go value into the externally-tagged `ir::value::LogicalValue` wire form. `time.Time` -> RFC3339 `Timestamp` (normalized to UTC), `[]byte` -> `Bytes` (array of byte values, matching the other SDKs rather than Go's default base64), integers -> `Int`, floats -> `Float`, slices/arrays -> `Array`, maps/structs -> `Json`, nil -> the unit `"Null"`.

func UnaryServerInterceptor added in v0.4.0

func UnaryServerInterceptor(
	ctx context.Context,
	req any,
	_ *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (any, error)

UnaryServerInterceptor is a grpc.UnaryServerInterceptor that reads the canonical UDB headers off the inbound gRPC metadata, builds a Metadata, and stashes it on the handler's context. Downstream handlers read it with FromContext / MetadataFromContext.

Usage:

grpc.NewServer(grpc.UnaryInterceptor(udbclient.UnaryServerInterceptor))

func UserID added in v0.4.0

func UserID(ctx context.Context) string

UserID returns the request's user id, or "" when unset.

func VerifyPolicyBundle added in v0.4.0

func VerifyPolicyBundle(signed *authzv1.SignedPolicyBundle, secret []byte) error

VerifyPolicyBundle recomputes the HMAC-SHA256 (lowercase hex) of signed.Bundle with secret and constant-time compares it to signed.Signature. It returns nil on a match and a *PolicyBundleSignatureError (which errors.Is matches ErrPolicyBundleSignature) on mismatch. A nil bundle or empty secret is a usage error returned as-is.

func WasDuplicate added in v0.4.0

func WasDuplicate(m *entityv1.MutationResponse) bool

WasDuplicate reports whether the broker collapsed this mutation onto a prior write via durable idempotency (a replay of the same idempotency key) instead of applying a fresh write. It mirrors MutationResponse.was_duplicate and lets a caller of the raw Upsert/Delete path distinguish an idempotency replay from a fresh mutation (Entity.Upsert also surfaces this on UpsertResult.WasDuplicate). A nil response yields false.

func WithMetadata added in v0.4.0

func WithMetadata(ctx context.Context, meta Metadata) context.Context

WithMetadata returns a copy of ctx carrying meta, retrievable with FromContext.

func WithNativeTx

func WithNativeTx(ctx context.Context, db *sql.DB, grant *authzv1.NativeAccessGrant, fn func(tx *sql.Tx) error) (err error)

WithNativeTx opens a transaction on the caller-provided *sql.DB (which should be connected using grant.Dsn), applies the grant's app.current_* session variables with SET LOCAL so RLS sees the same request context the broker enforced, runs fn, and commits — or rolls back on error. Uses only the Go standard library so the SDK pulls in no database driver of its own; the caller chooses the driver (pgx stdlib, lib/pq, …) when opening db.

Types

type AdminFacade added in v0.4.0

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

AdminFacade exposes the migration lifecycle helpers over the data-plane DataBroker client.

func (*AdminFacade) ApplyCurrent added in v0.4.0

func (a *AdminFacade) ApplyCurrent(ctx context.Context, projectID string) (*entityv1.MigrationStatusResponse, error)

ApplyCurrent runs the full plan -> approve -> apply chain for a project, reading the approval token from approveResp.GetApprovalToken() (the typed response body) rather than a grpc.Trailer/metadata callback. It returns the final apply status.

type AdoptedLogin added in v0.4.0

type AdoptedLogin struct {
	Token     Token
	Principal *authnv1.Principal
}

AdoptedLogin is the result of LoginAndAdoptTenant: the bearer token set as the authorization credential and the verified principal whose canonical tenant/ project were adopted.

type ApiKeyFacade added in v0.4.0

type ApiKeyFacade struct {
	Raw apikeyv1.ApiKeyServiceClient
	// contains filtered or unexported fields
}

ApiKeyFacade wraps ApiKeyServiceClient.

func (*ApiKeyFacade) Create added in v0.4.0

func (f *ApiKeyFacade) Create(ctx context.Context, name string, scopes []string) (*apikeyv1.CreateApiKeyResponse, error)

Create issues a new API key. The plaintext key is returned ONCE on CreateApiKeyResponse.PlainKey — persist it; the server does not store it. Scopes default to the caller Metadata scopes when none are supplied.

func (*ApiKeyFacade) Revoke added in v0.4.0

func (f *ApiKeyFacade) Revoke(ctx context.Context, keyID, reason string) (*apikeyv1.RevokeApiKeyResponse, error)

Revoke revokes an API key by id with an optional reason.

type AssetFacade added in v0.4.0

type AssetFacade struct {
	Raw assetv1.AssetServiceClient
	// contains filtered or unexported fields
}

AssetFacade wraps AssetServiceClient.

func (*AssetFacade) CompleteStep added in v0.4.0

func (f *AssetFacade) CompleteStep(ctx context.Context, stepID, status, resultJSON, errorMessage string) (*assetv1.CompleteStepResponse, error)

CompleteStep reports the outcome of a pipeline step. status is one of COMPLETED | SKIPPED | FAILED; resultJSON and errorMessage are optional. tenant defaults to the Metadata.

func (*AssetFacade) CreatePipelineDefinition added in v0.4.0

func (f *AssetFacade) CreatePipelineDefinition(ctx context.Context, name, description, mediaType, stepsJSON string, version int32) (*assetv1.CreatePipelineDefinitionResponse, error)

CreatePipelineDefinition registers a reusable processing pipeline. steps is a JSON array of step descriptors. tenant defaults to the caller Metadata.

func (*AssetFacade) DefinePipeline added in v0.4.0

func (f *AssetFacade) DefinePipeline(ctx context.Context, name, description, mediaType, stepsJSON string, version int32) (*assetv1.CreatePipelineDefinitionResponse, error)

DefinePipeline is a thin wrapper over CreatePipelineDefinition taking the step list as a JSON array (the producer-side define helper). tenant defaults to the Metadata.

func (*AssetFacade) GetAsset added in v0.4.0

func (f *AssetFacade) GetAsset(ctx context.Context, assetID string) (*assetv1.GetAssetResponse, error)

GetAsset fetches an asset by id. tenant defaults to the Metadata.

func (*AssetFacade) GetPipeline added in v0.4.0

func (f *AssetFacade) GetPipeline(ctx context.Context, instanceID string) (*assetv1.GetPipelineResponse, error)

GetPipeline fetches a running/completed pipeline instance by id. tenant defaults to the Metadata.

func (*AssetFacade) GetPipelineDefinition added in v0.4.0

func (f *AssetFacade) GetPipelineDefinition(ctx context.Context, definitionID string) (*assetv1.GetPipelineDefinitionResponse, error)

GetPipelineDefinition fetches a pipeline definition by id. tenant defaults to the Metadata.

func (*AssetFacade) ListAssets added in v0.4.0

func (f *AssetFacade) ListAssets(ctx context.Context, mediaType, status string, page, pageSize int32) (*assetv1.ListAssetsResponse, error)

ListAssets paginates assets for the tenant, optionally filtered by mediaType and status. page/pageSize of zero use the server defaults. tenant defaults to the Metadata.

func (*AssetFacade) RegisterAsset added in v0.4.0

func (f *AssetFacade) RegisterAsset(ctx context.Context, fileID, name, mediaType, metadataJSON string) (*assetv1.RegisterAssetResponse, error)

RegisterAsset records an asset backed by a stored fileID. metadataJSON is an optional JSON blob. tenant/project default to the caller Metadata.

func (*AssetFacade) RegisterFromStorageFile added in v0.4.0

func (f *AssetFacade) RegisterFromStorageFile(ctx context.Context, fileID, name, mediaType, metadataJSON string) (*assetv1.RegisterAssetResponse, error)

RegisterFromStorageFile registers an asset bound to a storage file id (the producer-side register helper over RegisterAsset). tenant/project default to the Metadata.

func (*AssetFacade) StartAndWait added in v0.4.0

func (f *AssetFacade) StartAndWait(ctx context.Context, definitionID, assetID, contextJSON, correlationID string, deadline time.Duration) (*StartAndWaitResult, error)

StartAndWait starts a pipeline (consuming the inline steps from the StartPipeline response — NOT a follow-up GetPipeline proof read) and then polls instance status to a terminal state (COMPLETED/FAILED) or until the deadline. Status polling uses only GetPipeline reads, bounded and cancellation-aware — never a fixed sleep loop.

func (*AssetFacade) StartPipeline added in v0.4.0

func (f *AssetFacade) StartPipeline(ctx context.Context, definitionID, assetID, contextJSON, correlationID string) (*assetv1.StartPipelineResponse, error)

StartPipeline launches a pipeline definition against an asset. contextJSON is an optional JSON context blob; correlationID defaults to the caller Metadata CorrelationID when empty. tenant defaults to the Metadata.

type AuthClient

type AuthClient struct {
	Authn authnv1.AuthnServiceClient
	Authz authzv1.AuthzServiceClient
	Meta  Metadata
	// contains filtered or unexported fields
}

AuthClient is a thin, hand-written convenience wrapper over the generated UDB AuthnService and AuthzService stubs. It mirrors Client: the same caller Metadata is attached to every outgoing call so the broker sees a consistent tenant/identity/scope context, and the raw generated requests stay reachable for anything the convenience helpers don't cover.

func NewAuthClient

func NewAuthClient(conn grpc.ClientConnInterface, meta Metadata) *AuthClient

NewAuthClient builds an AuthClient from an existing gRPC connection.

func (*AuthClient) AllowRole added in v0.4.0

func (c *AuthClient) AllowRole(ctx context.Context, role string, resource *authzv1.ResourceRef, action string) (*authzv1.CreatePolicyRuleResponse, error)

AllowRole grants role permission to perform action on resource. It emits exactly one CreatePolicyRule RPC with effect = ALLOW: role becomes the policy subject, the resource's object key (message_type/resource_name/table, in that precedence) becomes the object, and tenant/project/domain + created_by are filled from the caller Metadata.

func (*AuthClient) AttachAuthzCache added in v0.4.0

func (c *AuthClient) AttachAuthzCache(cache *AuthzCache)

AttachAuthzCache binds a decision cache so Can/Require/Explain reuse server TTLs. Pass nil to detach. The cache is created over this same AuthClient.

func (*AuthClient) Authenticate

func (c *AuthClient) Authenticate(ctx context.Context, req *authnv1.AuthnRequest) (*authnv1.AuthnResponse, error)

Authenticate forwards a fully-formed AuthnRequest. Use this when you need to set fields the typed helpers below don't expose (external providers, audience, issuer, credential_type, …).

func (*AuthClient) AuthenticateAPIKey

func (c *AuthClient) AuthenticateAPIKey(ctx context.Context, apiKey string) (*authnv1.AuthnResponse, error)

AuthenticateAPIKey validates an API/service key and returns the principal.

func (*AuthClient) AuthenticateBearer

func (c *AuthClient) AuthenticateBearer(ctx context.Context, token string) (*authnv1.AuthnResponse, error)

AuthenticateBearer validates a native JWT bearer token and returns the resolved principal. The caller Metadata seeds the tenant/project hints and requested scopes.

func (*AuthClient) AuthenticateSession

func (c *AuthClient) AuthenticateSession(ctx context.Context, sessionID string) (*authnv1.AuthnResponse, error)

AuthenticateSession validates a server-side session id and returns the principal bound to that session.

func (*AuthClient) Authorize

func (c *AuthClient) Authorize(ctx context.Context, req *authzv1.AuthzRequest) (*authzv1.Decision, error)

Authorize forwards a fully-formed AuthzRequest and returns the decision.

func (*AuthClient) BatchCan added in v0.4.0

func (c *AuthClient) BatchCan(ctx context.Context, checks []BatchCheck) ([]BatchResult, map[string]bool, error)

BatchCan evaluates many permission checks in a single BatchCheckPermissions RPC. It returns the results in the same order as the input checks plus a keyed map ("object:action" → allowed) matching the server's response shape. The subject is the caller's UserID (falling back to ServiceIdentity) and the domain is the caller's TenantID, taken from Metadata.

func (*AuthClient) BindRole added in v0.4.0

func (c *AuthClient) BindRole(ctx context.Context, subject, role string) (*authzv1.AssignRoleResponse, error)

BindRole binds subject (a user/principal id) to role. It emits exactly one AssignRole RPC: subject is sent as both user_id and principal_id, role as role_id, and domain/tenant/project + assigned_by are filled from the caller Metadata.

func (*AuthClient) Can

func (c *AuthClient) Can(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (bool, *authzv1.Decision, error)

Can is a convenience over Authorize: it builds an AuthzRequest from the caller Metadata plus the supplied resource/action/purpose and reports whether access is allowed. The full Decision is returned for matched-policy/deny-reason inspection.

func (*AuthClient) CheckAccess

CheckAccess forwards a Casbin-style (user, domain, object, action) request.

func (*AuthClient) ConformanceProof added in v0.4.0

func (c *AuthClient) ConformanceProof(ctx context.Context, kind ConformanceKind, req ConformanceProofRequest) (string, error)

ConformanceProof drives the issuing RPC for kind and extracts the gated proof. OTP -> SendOTP.dev_otp_code; PASSWORD_RESET -> ForgotPassword.dev_otp_code; PHONE -> SendPhoneVerification.dev_otp_code; TOTP -> the current 6-digit code computed from EnrollMFA.totp_secret. An empty echo (broker not in conformance mode) returns an error.

func (*AuthClient) Context

func (c *AuthClient) Context(ctx context.Context) context.Context

Context attaches the caller Metadata as gRPC headers, matching Client.Context — including the request-scoped audit merge, so an auth call made for a given inbound request carries that request's correlation id rather than the connection-level baseline.

func (*AuthClient) Explain added in v0.4.0

func (c *AuthClient) Explain(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (*authzv1.Decision, error)

Explain returns the full Decision for (resource, action, purpose) without ever turning a clean deny into an error. Only transport/server failures error.

func (*AuthClient) GetNativeAccess

GetNativeAccess forwards a fully-formed NativeAccessRequest and returns the response (decision + optional grant). The grant is present only when the decision allowed and the server has native access configured.

func (*AuthClient) GetPolicyBundle

func (c *AuthClient) GetPolicyBundle(ctx context.Context) (*authzv1.SignedPolicyBundle, error)

GetPolicyBundle fetches a signed policy bundle for the caller's tenant/project scope. SDKs can persist and verify it to drive a fully offline cache; the signature + expiry let a caller trust a cached bundle between fetches.

When a bundle secret has been configured on the client via SetPolicyBundleSecret, the fetched bundle's HMAC signature is verified before it is returned; a mismatch returns a *PolicyBundleSignatureError (which errors.Is matches ErrPolicyBundleSignature) and no bundle.

func (*AuthClient) LoginSession added in v0.4.0

func (c *AuthClient) LoginSession(store TokenStore) *TokenManager

LoginSession is the canonical naming-contract accessor for the login/refresh session lifecycle: it constructs a TokenManager bound to this AuthClient (single-flight refresh, pluggable TokenStore — a nil store defaults to an in-memory one). It issues NO RPC itself; call Login/LoginWithDevice on the returned manager to authenticate. Alias of NewTokenManager(c, store).

func (*AuthClient) NativeAccess

func (c *AuthClient) NativeAccess(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (*authzv1.NativeAccessGrant, error)

NativeAccess is a convenience over GetNativeAccess: it builds the request from the caller Metadata plus the supplied resource/action/purpose and returns the grant. It returns (nil, nil) when access is allowed but no native grant was minted (native access not configured server-side), and an error when the decision denied access.

func (*AuthClient) Passkeys added in v0.4.0

func (c *AuthClient) Passkeys() *PasskeyHelper

Passkeys returns the passkey ceremony helper.

func (*AuthClient) Require added in v0.4.0

func (c *AuthClient) Require(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) error

Require checks (resource, action, purpose) and returns nil when allowed or an *AuthzDeniedError (which errors.Is(err, ErrAuthzDenied)) when denied. A transport/server error is returned as-is. It routes through the AuthClient's cache when one has been attached via AttachAuthzCache, otherwise it calls the server directly.

func (*AuthClient) SetPolicyBundleSecret added in v0.4.0

func (c *AuthClient) SetPolicyBundleSecret(secret []byte)

SetPolicyBundleSecret configures the shared HMAC secret used to verify signed policy bundles. When set, GetPolicyBundle verifies every fetched bundle and returns an *PolicyBundleSignatureError on mismatch. Pass nil/empty to disable.

type AuthzCache

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

AuthzCache is a concurrency-safe decision cache over an AuthClient.

func NewAuthzCache

func NewAuthzCache(client *AuthClient) *AuthzCache

NewAuthzCache builds a cache over the given AuthClient.

func (*AuthzCache) Can

func (a *AuthzCache) Can(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (bool, *authzv1.Decision, error)

Can answers the authorization question from the local cache when a fresh decision is present, otherwise it calls the server and caches the result for Decision.cache_ttl_seconds. The full Decision is returned for inspection.

func (*AuthzCache) Explain added in v0.4.0

func (a *AuthzCache) Explain(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (*authzv1.Decision, error)

Explain on the cache returns the cached/fresh Decision without erroring on deny.

func (*AuthzCache) Invalidate

func (a *AuthzCache) Invalidate()

Invalidate drops all cached decisions (e.g. after a known policy change).

func (*AuthzCache) Require added in v0.4.0

func (a *AuthzCache) Require(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) error

Require on the cache routes the underlying Can through the TTL cache.

type AuthzDeniedError added in v0.4.0

type AuthzDeniedError struct {
	Resource *authzv1.ResourceRef
	Action   string
	Purpose  string
	Decision *authzv1.Decision
}

AuthzDeniedError is the typed error Require returns when access is denied. It carries the resource/action/purpose that was checked and the server Decision so callers can inspect the deny reason, matched policies, and required scopes.

func (*AuthzDeniedError) DeniedRequiredScopes added in v0.4.0

func (e *AuthzDeniedError) DeniedRequiredScopes() []string

DeniedRequiredScopes surfaces the scopes the decision said were missing, when the broker populated them, so a caller can prompt for step-up.

func (*AuthzDeniedError) Error added in v0.4.0

func (e *AuthzDeniedError) Error() string

func (*AuthzDeniedError) Is added in v0.4.0

func (e *AuthzDeniedError) Is(target error) bool

Is lets errors.Is(err, ErrAuthzDenied) succeed for any AuthzDeniedError.

type AuthzFacade added in v0.4.0

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

AuthzFacade exposes the authz ergonomics surface (Can/Require/BatchCan/Explain /NativeAccess) over a cached AuthClient.

func (*AuthzFacade) AllowRole added in v0.4.0

func (f *AuthzFacade) AllowRole(ctx context.Context, role string, resource *authzv1.ResourceRef, action string) (*authzv1.CreatePolicyRuleResponse, error)

AllowRole on the AuthzFacade forwards to the underlying AuthClient so the canonical `u.Authz.AllowRole(...)` surface exists (one CreatePolicyRule RPC).

func (*AuthzFacade) BatchCan added in v0.4.0

func (f *AuthzFacade) BatchCan(ctx context.Context, checks []BatchCheck) ([]BatchResult, map[string]bool, error)

BatchCan evaluates many (object, action) checks in one RPC.

func (*AuthzFacade) BindRole added in v0.4.0

func (f *AuthzFacade) BindRole(ctx context.Context, subject, role string) (*authzv1.AssignRoleResponse, error)

BindRole on the AuthzFacade forwards to the underlying AuthClient so the canonical `u.Authz.BindRole(...)` surface exists (one AssignRole RPC).

func (*AuthzFacade) Can added in v0.4.0

func (f *AuthzFacade) Can(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (bool, *authzv1.Decision, error)

Can answers allow/deny (cached) and returns the Decision for inspection.

func (*AuthzFacade) Explain added in v0.4.0

func (f *AuthzFacade) Explain(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (*authzv1.Decision, error)

Explain returns the full Decision without erroring on a clean deny (cached).

func (*AuthzFacade) Invalidate added in v0.4.0

func (f *AuthzFacade) Invalidate()

Invalidate drops cached decisions (e.g. after a known policy change).

func (*AuthzFacade) NativeAccess added in v0.4.0

func (f *AuthzFacade) NativeAccess(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) (*authzv1.NativeAccessGrant, error)

NativeAccess returns a short-lived native DB grant when allowed.

func (*AuthzFacade) Require added in v0.4.0

func (f *AuthzFacade) Require(ctx context.Context, resource *authzv1.ResourceRef, action, purpose string) error

Require returns nil on allow or an *AuthzDeniedError on deny (cached).

type BatchCheck added in v0.4.0

type BatchCheck struct {
	Object string
	Action string
}

BatchCheck is one (object, action) pair for BatchCan. Object is the Casbin object string (e.g. a table or resource name); Action is the verb.

type BatchResult added in v0.4.0

type BatchResult struct {
	BatchCheck
	Allowed bool
}

BatchResult pairs a BatchCheck with its allow/deny outcome.

type Client

type Client struct {
	Broker servicesv1.DataBrokerClient
	Meta   Metadata
}

func New

func New(conn grpc.ClientConnInterface, meta Metadata) *Client

func (*Client) Admin added in v0.4.0

func (c *Client) Admin() *AdminFacade

Admin returns the migration-lifecycle helper bound to this data-plane client.

func (*Client) Context

func (c *Client) Context(ctx context.Context) context.Context

func (*Client) Delete

func (*Client) Entity added in v0.4.0

func (c *Client) Entity(fqn string, key EntityKey) *Entity

Entity binds a message FQN + key over this Client.

func (*Client) Select

func (*Client) Update added in v0.4.23

Update issues the partial-update RPC (W7): SET named columns and/or apply atomic increments on the matched rows — no full-record resend.

func (*Client) Upsert

type Config added in v0.4.0

type Config struct {
	Target     string // broker gRPC target, e.g. "localhost:50051" (required)
	AuthTarget string // authn/authz/media control-plane target; defaults to Target
	// WebRTCTarget, when set, is the signalling/peer endpoint the WebRTC facade
	// dials on a dedicated connection; defaults to AuthTarget (the control-plane
	// listener that also serves Room/Peer/Track/Turn).
	WebRTCTarget string

	TenantID  string
	ProjectID string
	Purpose   string
	Scopes    []string

	// Credentials, when set, are sent as auth headers on every call:
	// Bearer (an access token) and/or APIKey.
	Credentials Credentials

	// TLS, when non-nil, dials with transport security. When nil the client
	// dials insecure (plaintext) — appropriate for localhost / a mesh sidecar.
	TLS *tls.Config

	// Retry overrides the default backoff policy. Zero value uses
	// DefaultRetryConfig().
	Retry RetryConfig

	// Deadline, when > 0, is applied as a per-call timeout when the caller's
	// context carries none.
	Deadline time.Duration

	// UserID / ServiceIdentity / CorrelationID seed the caller Metadata.
	UserID          string
	ServiceIdentity string
	CorrelationID   string
}

Config configures NewUdb. Only Target is required; everything else has a sane default. AuthTarget defaults to Target when empty (auth lives on the same broker endpoint in the default deployment). The media services (Storage/ Asset/WebRTC) share the auth/control-plane listener, so they follow AuthTarget.

type ConformanceKind added in v0.4.0

type ConformanceKind string

ConformanceKind selects which proof material ConformanceProof returns.

const (
	ConformanceOTP           ConformanceKind = "otp"
	ConformancePasswordReset ConformanceKind = "password_reset"
	ConformancePhone         ConformanceKind = "phone"
	ConformanceTOTP          ConformanceKind = "totp"
)

type ConformanceProofRequest added in v0.4.0

type ConformanceProofRequest struct {
	UserID     string // SendOTP / EnrollMFA target
	Identifier string // ForgotPassword identifier (email/username)
	Phone      string // SendPhoneVerification phone number
}

ConformanceProofRequest carries the per-kind inputs ConformanceProof needs to drive the issuing RPC.

type ConsistencyMode added in v0.4.0

type ConsistencyMode string

── Consistency-mode selection (chapter 08.1) ────────────────────────────────

ConsistencyMode is an ergonomic selector for the read/write consistency a single request wants, mirroring Python's Metadata consistency knob. Its string value is the PINNED wire token the broker parses (src/runtime/consistency.rs ConsistencyMode::parse) — from either the x-udb-consistency header or the typed RequestContext.consistency_mode enum (proto field 22) it maps 1:1 onto. Changing a token breaks every client, so these stay byte-for-byte pinned.

const (
	// ConsistencyDefault leaves the mode unset (broker default = strong).
	ConsistencyDefault ConsistencyMode = ""
	// ConsistencyStrong reads the primary / linearizable copy.
	ConsistencyStrong ConsistencyMode = "strong"
	// ConsistencyReadYourWrites guarantees a session observes its own writes.
	ConsistencyReadYourWrites ConsistencyMode = "read_your_writes"
	// ConsistencyBoundedStaleness allows a replica read within a lag bound.
	ConsistencyBoundedStaleness ConsistencyMode = "bounded_staleness"
	// ConsistencyReplicaBounded prefers a replica within a bound.
	ConsistencyReplicaBounded ConsistencyMode = "replica_bounded"
	// ConsistencyEventual allows any replica (fastest, weakest).
	ConsistencyEventual ConsistencyMode = "eventual"
	// ConsistencyProjectionOk permits serving from an async projection.
	ConsistencyProjectionOk ConsistencyMode = "projection_ok"
	// ConsistencyCacheOk permits serving from a cache.
	ConsistencyCacheOk ConsistencyMode = "cache_ok"
)

func (ConsistencyMode) Apply added in v0.4.0

Apply stamps this consistency mode onto a single, caller-supplied per-read RequestContext (the typed consistency_mode enum the broker honors). It NEVER touches shared Udb/facade metadata — the choice rides only this one request. An empty mode leaves rc untouched.

func (ConsistencyMode) Header added in v0.4.0

func (m ConsistencyMode) Header() (string, string)

Header returns the (key, value) metadata pair for the x-udb-consistency header form of this mode, for callers stamping consistency via request headers rather than the RequestContext body. An empty mode yields an empty value.

type Credentials added in v0.4.0

type Credentials struct {
	Bearer string // sent as "authorization: Bearer <token>"
	APIKey string // sent as "x-api-key: <key>"
}

Credentials carries the per-call auth material the facade attaches as headers.

type DeleteBuilder added in v0.4.0

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

DeleteBuilder is the typed neutral-IR delete builder. It emits `{"ir": {"op": "delete", ...}}` (a `LogicalDelete`). A Where(...) predicate is REQUIRED — the IR has no delete-everything path (mirrors the server-side contract).

func DeleteFrom added in v0.4.0

func DeleteFrom(messageType string) *DeleteBuilder

DeleteFrom starts a typed neutral-IR delete for messageType.

func (*DeleteBuilder) Execute added in v0.4.0

func (*DeleteBuilder) ExecuteOn added in v0.4.0

func (d *DeleteBuilder) ExecuteOn(ctx context.Context, dispatch IRDispatcher, backend string, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

func (*DeleteBuilder) Returning added in v0.4.0

func (d *DeleteBuilder) Returning(fields ...string) *DeleteBuilder

func (*DeleteBuilder) ToEnvelope added in v0.4.0

func (d *DeleteBuilder) ToEnvelope() (any, error)

func (*DeleteBuilder) ToRequest added in v0.4.0

func (d *DeleteBuilder) ToRequest(backend string) (*entityv1.GenericDispatchRequest, error)

func (*DeleteBuilder) ToSpecJSON added in v0.4.0

func (d *DeleteBuilder) ToSpecJSON() (string, error)

func (*DeleteBuilder) Where added in v0.4.0

func (d *DeleteBuilder) Where(field, op string, value any) *DeleteBuilder

func (*DeleteBuilder) WhereIn added in v0.4.0

func (d *DeleteBuilder) WhereIn(field string, values ...any) *DeleteBuilder

type DeleteOption added in v0.4.19

type DeleteOption func(*deleteOptions)

DeleteOption configures Delete.

func WithDeleteExpected added in v0.4.19

func WithDeleteExpected(expected map[string]any) DeleteOption

WithDeleteExpected makes the Delete a compare-and-swap (G-2): the row the filter targets is removed only if each field -> value still equals the CURRENT row (row-locked, in the same tenant/RLS transaction). If the row is absent or any assertion fails, the broker returns FAILED_PRECONDITION and deletes nothing. Requires the filter to pin every primary-key column by equality. Passing a nil/empty map is rejected with errEmptyCAS BEFORE any RPC — a guarded delete must never degrade into an unconditional one (for an unconditional delete, simply omit this option).

func WithDeleteIdempotencyKey added in v0.5.0

func WithDeleteIdempotencyKey(key string) DeleteOption

WithDeleteIdempotencyKey attaches a caller-supplied durable idempotency key to the Delete. The broker deduplicates replays of the SAME key so an ambiguous client/network retry cannot repeat the delete or its side effects. Delete is still never auto-retried by the SDK (it is a destructive RPC — see retryableForRPC); this only makes a caller-driven retry replay-safe. A key that is present but only whitespace is rejected; an unset key leaves the request's idempotency_key empty (unchanged).

type DownloadOption added in v0.4.0

type DownloadOption func(*DownloadOptions)

DownloadOption is a functional option mutating DownloadOptions.

func WithDownloadChunkSize added in v0.4.0

func WithDownloadChunkSize(n int32) DownloadOption

WithDownloadChunkSize sets the advisory streaming chunk size.

func WithMaxDownloadBytes added in v0.4.0

func WithMaxDownloadBytes(n int64) DownloadOption

WithMaxDownloadBytes caps the reassembled byte payload.

type DownloadOptions added in v0.4.0

type DownloadOptions struct {
	// ChunkSizeBytes is the advisory server-side chunk size for the streaming
	// fallback; zero lets the server choose. It does not bound reassembly.
	ChunkSizeBytes int32
	// MaxBytes caps the reassembled payload; the stream is aborted with a typed
	// error once the accumulated bytes would exceed it. Zero = unlimited.
	MaxBytes int64
}

DownloadOptions carries the non-positional DownloadFileBytes inputs.

type DownloadResult added in v0.4.0

type DownloadResult struct {
	Data        []byte
	ContentType string
	TotalSize   int64
	ETag        string
}

DownloadResult is the reassembled output of DownloadFileBytes: the full file bytes plus the content-type/total-size/etag metadata the first chunk carries.

type EagerIncludeUnsupportedBackendError added in v0.4.0

type EagerIncludeUnsupportedBackendError struct {
	Backend string
	Tier    string
}

func (EagerIncludeUnsupportedBackendError) Error added in v0.4.0

type EnterpriseConfig added in v0.4.0

type EnterpriseConfig struct {
	Target     string // data-plane target, e.g. "127.0.0.1:50051" (required)
	AuthTarget string // control-plane target, e.g. "127.0.0.1:50061"; defaults to Target
	Username   string // required
	Password   string // required
	// TenantCode is the human tenant code hint used pre-login (e.g. "acme").
	// The verified canonical tenant UUID replaces it after login.
	TenantCode string
	ProjectID  string
	Purpose    string
	Scopes     []string
	UserID     string
	TLS        *tls.Config
	Deadline   time.Duration
	Retry      RetryConfig
}

EnterpriseConfig drives ConnectEnterprise, the one-call production-path setup: dial data + auth targets, log in with username/password, verify the bearer, adopt the canonical tenant UUID, and carry that bearer on every subsequent call. Mirrors examples/ts_enterprise's flow in Go.

type EnterpriseLockService added in v0.5.0

type EnterpriseLockService struct {
	Raw lockv1.LockServiceClient
	// contains filtered or unexported fields
}

EnterpriseLockService is a typed LockService facade bound to the session-owned control-plane channel (NativeConn). Every call routes through NativeContext, so it carries the canonical adopted identity + the freshly-refreshed bearer and fails closed locally when the session is poisoned — the same guarantees the data/native contexts give. Reach the raw stub via .Raw for any RPC (GetLock/ ListLocks or future additions) the helpers omit.

func (*EnterpriseLockService) Acquire added in v0.5.0

Acquire acquires a distributed lock, defaulting the request tenant to the verified canonical tenant UUID when the caller left it empty (never overriding an explicit value). Returns the monotone fencing token to present on Renew/Release.

func (*EnterpriseLockService) Get added in v0.5.0

Get fetches a single lock by name within the caller's tenant (found=false on a miss, not an error). Defaults the request tenant to the canonical UUID when empty.

func (*EnterpriseLockService) List added in v0.5.0

List lists the caller tenant's locks (paginated). Defaults the request tenant to the canonical UUID when empty.

func (*EnterpriseLockService) Release added in v0.5.0

Release releases a lock the caller holds; the presented fencing token must not be stale. Defaults the request tenant to the canonical UUID when empty.

func (*EnterpriseLockService) Renew added in v0.5.0

Renew extends the lease of a lock the caller holds; the presented fencing token must not be stale. Defaults the request tenant to the canonical UUID when empty.

type EnterpriseSession added in v0.4.0

type EnterpriseSession struct {
	*Udb
	// CanonicalTenantID is the verified tenant UUID (use this in all filters).
	CanonicalTenantID string
	// CanonicalProjectID is the verified project from the principal.
	CanonicalProjectID string
	// Principal is the verified login principal (for inspection).
	Principal *authnv1.Principal
	// Tenant tracks the code -> canonical-UUID transition + the fail-fast guard.
	Tenant TenantState
	// contains filtered or unexported fields
}

EnterpriseSession bundles the authenticated Udb with the VERIFIED canonical tenant state and the bearer.

IMPORTANT: after login the broker connection's interceptor (set at dial time) does NOT pick up the post-login token, so raw u.Data / native calls would be Unauthenticated. Use DataContext / NativeContext (which append the bearer explicitly) for any call you make through the embedded *Udb, and use CanonicalTenantID — never the human code — in tenant-scoped records/filters.

func ConnectEnterprise added in v0.4.0

func ConnectEnterprise(ctx context.Context, cfg EnterpriseConfig) (*EnterpriseSession, error)

ConnectEnterprise runs the full enterprise flow in one call and returns a session whose canonical tenant is verified and whose bearer is ready to attach via DataContext / NativeContext.

func (*EnterpriseSession) Bearer added in v0.4.0

func (s *EnterpriseSession) Bearer() string

Bearer is the "Bearer <token>" credential, for callers that build their own metadata.

func (*EnterpriseSession) Close added in v0.4.15

func (s *EnterpriseSession) Close() error

Close stops the background bearer refresher and closes the underlying connections. Safe to call more than once.

func (*EnterpriseSession) DataContext added in v0.4.0

func (s *EnterpriseSession) DataContext(ctx context.Context) context.Context

DataContext returns a context for DataBroker calls (s.Data.Broker.*) carrying the verified metadata AND the bearer. Use it for every data-plane call so the post-login token is sent (the dial-time interceptor does not carry it).

func (*EnterpriseSession) LockService added in v0.5.0

func (s *EnterpriseSession) LockService() *EnterpriseLockService

LockService returns a typed distributed-lock facade on the session-owned authenticated control-plane channel. There is no caller-managed dial or close: the connection is owned by the session (NativeConn) and torn down by Close, and the adopted-identity metadata + bearer refresh are preserved on every call.

func (*EnterpriseSession) NativeConn added in v0.5.0

func (s *EnterpriseSession) NativeConn() grpc.ClientConnInterface

NativeConn returns the session-OWNED, authenticated control-plane channel: the same *grpc.ClientConn ConnectEnterprise dialed to AuthTarget (or Target when the two coincide). It is the supported escape hatch for constructing a generated native-service client the typed facades do not yet cover — no redial, no second TLS lifecycle — e.g.

lock := lockv1.NewLockServiceClient(sess.NativeConn())
lock.AcquireLock(sess.NativeContext(ctx), &lockv1.AcquireLockRequest{ /* … */ })

The connection is owned by the session: never Dial or Close it yourself — the session's Close tears it down. Its dial-time interceptors read the SAME GeneratedClient that tenant adoption (SetMeta) and the background bearer refresher (SetAuthorization) keep current, so a bare-context call still carries the canonical adopted identity and the live bearer. For the strongest guarantee — a single-flight-refreshed bearer AND local fail-closed when the session is poisoned — pair every call with NativeContext (as above), which is exactly what the typed LockService facade below does. The return type mirrors GeneratedClient.Conn(): a grpc.ClientConnInterface is all any generated NewXxxClient constructor needs.

func (*EnterpriseSession) NativeContext added in v0.4.0

func (s *EnterpriseSession) NativeContext(ctx context.Context) context.Context

NativeContext returns a context for native control-plane calls (ApiKey/Tenant/ Notification/…) carrying the verified metadata AND the bearer.

func (*EnterpriseSession) RefreshErr added in v0.4.15

func (s *EnterpriseSession) RefreshErr() error

RefreshErr returns the most recent background bearer-refresh error, or nil if the last refresh succeeded. Useful for health checks and logging.

func (*EnterpriseSession) ValidateTenant added in v0.4.0

func (s *EnterpriseSession) ValidateTenant(recordTenantID string) error

ValidateTenant fails fast (naming both values) if recordTenantID differs from the verified canonical tenant — call it before a tenant-scoped write.

type Entity added in v0.4.0

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

Entity binds a message FQN + primary key once so CRUD calls stay terse.

func (*Entity) Delete added in v0.4.0

func (e *Entity) Delete(ctx context.Context, where map[string]any, opts ...DeleteOption) (*entityv1.MutationResponse, error)

Delete issues exactly ONE Delete RPC for the bound FQN with a Struct filter built from where. Delete is a mutation/destructive RPC and is never auto-retried (see retryableForRPC). Pass WithDeleteExpected for compare-and-swap.

func (*Entity) Increment added in v0.4.23

func (e *Entity) Increment(ctx context.Context, where map[string]any, deltas map[string]float64, opts ...UpdateOption) (*entityv1.MutationResponse, error)

Increment applies atomic counter deltas (`column = column + delta`) on the matched rows in ONE statement — no read-modify-write lost-update window. Combine with Update by calling update via separate RPCs only when the two column sets are disjoint; a single call never names a column in both.

func (*Entity) Select added in v0.4.0

func (e *Entity) Select(ctx context.Context, where map[string]any) ([]map[string]any, error)

Select issues exactly ONE Select RPC for the bound FQN with a Struct filter built from where, and decodes the RecordSet rows into []map[string]any.

func (*Entity) SelectPage added in v0.4.19

func (e *Entity) SelectPage(ctx context.Context, where map[string]any, opts PageOptions) (*Page, error)

SelectPage issues a single keyset-paginated Select for the bound FQN. Pass an empty PageToken for the first page, then feed each returned NextPageToken back until it comes back empty (P-1). This replaces the hand-built structpb filter + manual RecordSet decode a consumer otherwise writes for every listing endpoint.

func (*Entity) Update added in v0.4.23

func (e *Entity) Update(ctx context.Context, where map[string]any, changes map[string]any, opts ...UpdateOption) (*entityv1.MutationResponse, error)

Update issues exactly ONE partial-update RPC: SET only the columns named in changes (a JSON null value writes SQL NULL; columns not named are untouched) on the rows matched by where. This replaces the Select -> merge -> full-record Upsert pattern — no merge helper, no NOT-NULL resend hazard, and combined with WithUpdateExpected it is an atomic guarded write.

func (*Entity) Upsert added in v0.4.0

func (e *Entity) Upsert(ctx context.Context, record any, opts ...UpsertOption) (*UpsertResult, error)

Upsert marshals record (a map[string]any or json.RawMessage) to record_json, builds the UpsertRequest with conflict_fields from the bound key, and issues exactly ONE Upsert RPC. No proof Get afterward unless ReturnRecord() is given.

func (*Entity) WithConsistency added in v0.4.0

func (e *Entity) WithConsistency(mode ConsistencyMode) *Entity

WithConsistency returns a shallow copy of the Entity whose reads/writes stamp the requested consistency mode on their per-call RequestContext (RequestContext.consistency_mode). The broker stays the enforcement point — this only expresses the caller's preference (strong / read-your-writes / bounded-staleness / eventual, etc.). Passing an empty mode clears it.

type EntityDescriptor added in v0.4.0

type EntityDescriptor struct {
	Table        string
	PrimaryKeys  []string
	Fields       []string
	Relations    []EntityRelationDescriptor
	VersionField string
	TenantField  string
	ProjectField string
	GoType       string
}

EntityDescriptor is a catalog-derived entity registry entry. It mirrors lane 07's canonical EntityDescriptor field-set; the generated @@UDB_ENTITY block in generated_client.go populates the Entities map with one per annotated entity message so (*Client).Entity can default conflict_fields/PK from the manifest instead of the caller passing Key(...).

type EntityKey added in v0.4.0

type EntityKey []string

EntityKey is the ordered set of primary-key field names that become an Upsert's conflict_fields.

func Key added in v0.4.0

func Key(fields ...string) EntityKey

Key builds an EntityKey from primary-key field names, e.g. Key("record_id").

type EntityRelationDescriptor added in v0.4.0

type EntityRelationDescriptor struct {
	Name              string   `json:"name"`
	Kind              string   `json:"kind"`
	LocalFields       []string `json:"local_fields"`
	TargetMessageType string   `json:"target_message_type"`
	TargetTable       string   `json:"target_table"`
	TargetFields      []string `json:"target_fields"`
	OnDelete          string   `json:"on_delete,omitempty"`
	OnUpdate          string   `json:"on_update,omitempty"`
}

type Error added in v0.4.0

type Error struct {
	Code      codes.Code
	Message   string
	RPC       string // full method path, e.g. /udb.services.v1.DataBroker/Select
	DetailBin []byte // raw udb.entity.v1.ErrorDetail bytes, or nil
	// contains filtered or unexported fields
}

Error is the typed error the generated layer maps gRPC failures to. It always carries the gRPC code/message; when the broker attached a serialized ErrorDetail trailer, DetailBin holds its raw bytes for the caller to decode.

func AsError added in v0.4.0

func AsError(err error) (*Error, bool)

AsError extracts a *Error from any error returned by this layer, if present.

func (*Error) Detail added in v0.4.0

func (e *Error) Detail() (*entityv1.ErrorDetail, bool)

Detail prost-decodes the raw DetailBin trailer into the generated ErrorDetail. It returns (nil, false) when no detail was attached or the bytes fail to decode; the raw bytes remain available on Error.DetailBin either way.

func (*Error) Error added in v0.4.0

func (e *Error) Error() string

func (*Error) FieldViolations added in v0.4.0

func (e *Error) FieldViolations() []FieldViolation

FieldViolations returns decoded validation field violations, or nil when no typed detail was attached, decoding failed, or the checked-in generated ErrorDetail class has not yet been refreshed with field_violations.

func (*Error) Kind added in v0.4.0

func (e *Error) Kind() entityv1.ErrorKind

Kind returns the broker's typed error classification (ERROR_KIND_UNSPECIFIED when no detail was attached).

func (*Error) Reason added in v0.4.19

func (e *Error) Reason() string

Reason returns the stable machine-readable reason a caller can branch on: the policy decision id for auth/policy denials, else the capability token, else "". Prefer this over matching the human-readable message, which may change.

func (*Error) RetryAfter added in v0.4.19

func (e *Error) RetryAfter() time.Duration

RetryAfter is the broker-suggested backoff before retrying, or 0 when none was provided (or no typed detail was attached). Pair with Retryable().

func (*Error) Retryable added in v0.4.0

func (e *Error) Retryable() bool

Retryable reports the broker's typed retry signal (false when no detail was attached). This is the authoritative retry/escalate hint — never parse the message string.

func (*Error) Unwrap added in v0.4.0

func (e *Error) Unwrap() error

type EventsFacade added in v0.4.0

type EventsFacade struct {
	Raw servicesv1.DataBrokerClient
	// contains filtered or unexported fields
}

EventsFacade exposes tenant-scoped CDC subscription + outbox publishing.

func (*EventsFacade) PublishAndWait added in v0.4.0

func (f *EventsFacade) PublishAndWait(ctx context.Context, sub *Subscription, topic string, payload map[string]any, matchFn func(*eventsv1.CDCEnvelope) bool) (*eventsv1.CDCEnvelope, error)

PublishAndWait enqueues an outbox event for topic then reads the subscription until matchFn matches the resulting envelope. It issues exactly one EnqueueOutboxEvent and then consumes server-pushed envelopes — never a sleep. The supplied subscription must already be Ready. Bounded by ctx.

func (*EventsFacade) Subscribe added in v0.4.0

func (f *EventsFacade) Subscribe(ctx context.Context, topic string) (*Subscription, error)

Subscribe opens the PublishCDC server-stream for topic, tenant-scoped from the facade metadata. The returned handle's Ready() resolves on the first server signal.

type FieldViolation added in v0.4.0

type FieldViolation struct {
	Field       string
	Description string
}

FieldViolation is the SDK-level view of one structured validation failure. It deliberately does not depend on regenerated ErrorFieldViolation classes, so this helper compiles before SDK regen and starts returning entries as soon as the generated ErrorDetail descriptor includes field_violations.

type GeneratedClient added in v0.4.0

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

GeneratedClient is the robustness layer. It holds a gRPC connection and the options applied to every wrapped call. Build it from an existing *grpc.ClientConn (so TLS / credentials / dial options are entirely yours), then either:

  • use the hand-written typed wrappers (udbclient.New(gc.Conn(), meta), …) which inherit nothing extra, OR
  • dial through DialOptions() so the retry/metadata/error interceptors apply to those typed wrappers automatically, OR
  • call gc.InvokeUnary / gc.NewServerStream / gc.NewClientStream for RPCs without a typed helper.

func NewGenerated added in v0.4.0

func NewGenerated(conn grpc.ClientConnInterface, opt Options) *GeneratedClient

NewGenerated wraps an existing connection. The connection's transport security (TLS/insecure) and credentials are whatever you configured when you dialed it; this layer never downgrades them.

func (*GeneratedClient) Conn added in v0.4.0

Conn exposes the underlying connection so the hand-written typed wrappers can be built on the same channel: udbclient.New(gc.Conn(), gc.Meta()).

func (*GeneratedClient) DialOptions added in v0.4.0

func (g *GeneratedClient) DialOptions() []grpc.DialOption

DialOptions returns the unary + stream interceptors that apply this client's metadata, deadline, retry for read-only unary calls, and error mapping to calls on the dialed connection (including typed udbclient.Client wrappers).

func (*GeneratedClient) InvokeUnary added in v0.4.0

func (g *GeneratedClient) InvokeUnary(ctx context.Context, fullMethod string, req, reply any, opts ...grpc.CallOption) error

InvokeUnary performs a unary RPC by full method path with metadata injection, per-call deadline, retry with backoff, and typed error mapping. req/reply are proto.Message values (the generated request/response types from ./gen). This is the engine the typed wrappers below delegate to.

func (*GeneratedClient) Meta added in v0.4.0

func (g *GeneratedClient) Meta() Metadata

Meta returns the configured caller Metadata.

func (*GeneratedClient) NewClientStream added in v0.4.0

func (g *GeneratedClient) NewClientStream(ctx context.Context, fullMethod string, desc *grpc.StreamDesc, opts ...grpc.CallOption) (grpc.ClientStream, error)

NewClientStream opens a client-streaming or bidi RPC. Never retried (the body is non-idempotent). Metadata and per-call deadline still apply.

func (*GeneratedClient) NewServerStream added in v0.4.0

func (g *GeneratedClient) NewServerStream(ctx context.Context, fullMethod string, desc *grpc.StreamDesc, req any, opts ...grpc.CallOption) (grpc.ClientStream, error)

NewServerStream opens a server-streaming RPC. Streaming RPCs are NOT retried here (the stream may have already produced data); retry is the caller's decision. Metadata and per-call deadline still apply.

func (*GeneratedClient) SetAPIKey added in v0.4.17

func (g *GeneratedClient) SetAPIKey(apiKey string)

SetAPIKey atomically swaps the `x-api-key` credential. Passing an empty string clears API-key metadata after it has been exchanged for a bearer.

func (*GeneratedClient) SetAuthorization added in v0.4.0

func (g *GeneratedClient) SetAuthorization(authorization string)

SetAuthorization atomically swaps the `authorization` header value (e.g. "Bearer <jwt>") used on every subsequent call.

func (*GeneratedClient) SetMeta added in v0.4.0

func (g *GeneratedClient) SetMeta(meta Metadata)

SetMeta atomically swaps the caller Metadata used on every subsequent call. A concurrent in-flight call observes either the old or the new metadata in full, never a mix.

type IRDispatcher added in v0.4.0

type IRDispatcher interface {
	GenericDispatch(ctx context.Context, in *entityv1.GenericDispatchRequest, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)
}

IRDispatcher is the minimal surface the IR builders dispatch through: the buf-generated DataBroker `GenericDispatch` unary forwarder. Both the raw generated `servicesv1.DataBrokerClient` and the hand-written `Client.Broker` satisfy it, so callers pass whichever DataBroker handle they already hold — no new client engine is introduced.

type MemoryTokenStore added in v0.4.0

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

MemoryTokenStore is a concurrency-safe in-process TokenStore.

func (*MemoryTokenStore) Load added in v0.4.0

func (m *MemoryTokenStore) Load(ctx context.Context) (Token, error)

func (*MemoryTokenStore) Save added in v0.4.0

func (m *MemoryTokenStore) Save(ctx context.Context, tok Token) error

type Metadata

type Metadata struct {
	TenantID             string
	UserID               string
	Purpose              string
	CorrelationID        string
	Scopes               []string
	ServiceIdentity      string
	ProjectID            string
	ClientCatalogVersion string
}

func FromContext added in v0.4.0

func FromContext(ctx context.Context) (Metadata, bool)

FromContext returns the per-request Metadata stashed by a UDB adapter and true, or the zero Metadata and false when none is present.

func MergeRequestScopedAudit added in v0.4.19

func MergeRequestScopedAudit(ctx context.Context, client Metadata) Metadata

MergeRequestScopedAudit resolves the three REQUEST-SCOPED audit values (purpose, correlation id, client catalog version) by preferring what the caller attached to this context with WithMetadata over the connection-level value, and returns the Metadata to emit as headers.

Identity — tenant, user, project, scopes, service identity — is deliberately NOT resolved here: it stays authoritative from the connected client and can never be overridden per request, so a caller cannot smuggle another principal's identity in through a context value.

Every header-building path (the DataBroker client, the auth client, and the generated dial interceptor that carries the native services) funnels through this one function. Keeping it single-sourced is what stops a facade from silently reverting to connection-level-only correlation, which is how per-request audit traceability was previously lost on native calls.

func MetadataFromContext added in v0.4.0

func MetadataFromContext(ctx context.Context) Metadata

MetadataFromContext returns the per-request Metadata, or the zero Metadata when none has been set. Convenience for callers that don't care about presence.

func (Metadata) ToRequestContextMeta added in v0.4.0

func (m Metadata) ToRequestContextMeta() RequestContextMeta

ToRequestContextMeta projects the caller Metadata into the unified context.

type MetadataAccessor added in v0.4.0

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

MetadataAccessor is the metadata surface mounted on the project facade via Udb.Metadata(), matching the cross-language udb.metadata.* shape (TS udb.metadata.afterWrite, Python udb.metadata). It groups the per-request RequestContext stamping helpers so callers reach them off the project object instead of the package-level functions.

func (*MetadataAccessor) AfterWrite added in v0.4.0

func (a *MetadataAccessor) AfterWrite(rc *entityv1.RequestContext, r WriteReceipt, maxWaitMs uint64)

AfterWrite stamps a read fence derived from a write receipt onto a single per-read RequestContext so the follow-up read observes its own write. It delegates to the package-level AfterWrite and never touches shared facade metadata — the fence rides only this one request.

func (*MetadataAccessor) Consistency added in v0.4.0

func (a *MetadataAccessor) Consistency(rc *entityv1.RequestContext, mode ConsistencyMode)

Consistency stamps a consistency mode onto a single per-read RequestContext (delegates to ConsistencyMode.Apply).

type Negotiator added in v0.4.0

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

Negotiator picks the best encoding shared by the client and a server's ProtocolSupport. A nil *ProtocolSupport (server advertised nothing, or an old stub with no field) safely negotiates V1.

func NewNegotiator added in v0.4.0

func NewNegotiator(support *ProtocolSupport) *Negotiator

NewNegotiator builds a Negotiator from server-advertised protocol support. Passing nil is valid and yields V1-only behavior.

func (*Negotiator) NegotiatedEncoding added in v0.4.0

func (n *Negotiator) NegotiatedEncoding() string

NegotiatedEncoding returns "record_batch_v2" only if the server advertises it AND this client supports it; otherwise it falls back to "record_set_v1".

func (*Negotiator) ProtocolRange added in v0.4.0

func (n *Negotiator) ProtocolRange() (min string, max string)

ProtocolRange returns the server's [min, max] protocol version. When unknown it falls back to the client's compiled-in ProtocolVersion for both bounds.

func (*Negotiator) ServerSupportsStreamingReads added in v0.4.0

func (n *Negotiator) ServerSupportsStreamingReads() bool

ServerSupportsStreamingReads reports whether the server advertises streaming reads. Absent protocol support is treated as false (V1 unary behavior).

func (*Negotiator) SupportsEncoding added in v0.4.0

func (n *Negotiator) SupportsEncoding(name string) bool

SupportsEncoding reports whether the server advertises the named encoding.

type NotificationFacade added in v0.4.0

type NotificationFacade struct {
	Raw notificationv1.NotificationServiceClient
	// contains filtered or unexported fields
}

NotificationFacade wraps NotificationServiceClient.

func (*NotificationFacade) RetryFailed added in v0.4.0

RetryFailed re-attempts delivery of a FAILED notification log by id.

func (*NotificationFacade) Send added in v0.4.0

func (f *NotificationFacade) Send(ctx context.Context, eventType, recipientID string, variables map[string]string) (*notificationv1.SendNotificationResponse, error)

Send dispatches a notification for eventType to a recipient. The tenant and project default to the caller Metadata. variables fill the template; pass nil when the template needs none. Channels are left empty so the template's default channels are used.

func (*NotificationFacade) SendTemplate added in v0.4.0

func (f *NotificationFacade) SendTemplate(ctx context.Context, eventType, recipientID string, variables map[string]string) ([]string, error)

SendTemplate dispatches a templated notification. The broker renders the template from eventType + variables (one SendNotification RPC). It returns the per-channel log ids the broker created.

func (*NotificationFacade) WaitForDelivery added in v0.4.0

WaitForDelivery reads the notification log status (via GetNotification) until it reaches a terminal state (DELIVERED/FAILED/SUPPRESSED) or the deadline elapses. It is bounded and status-driven — NOT a fixed sleep loop; it respects context cancellation. The poll interval only paces consecutive reads while the status is still non-terminal.

type Options added in v0.4.0

type Options struct {
	// Meta is attached as the 8 UDB headers on every outgoing call, exactly as
	// the hand-written Client.Context does.
	Meta Metadata
	// CallTimeout, when > 0, is applied as a per-call deadline if the caller's
	// context has none.
	CallTimeout time.Duration
	// Retry governs backoff retries. Defaults to DefaultRetryConfig() when zero.
	Retry RetryConfig
	// Authorization, when non-empty, is sent as the `authorization` header
	// (e.g. "Bearer <jwt>").
	Authorization string
	// APIKey, when non-empty, is sent as the `x-api-key` header.
	APIKey string
	// RequestID, when non-empty, is sent as the `x-request-id` header. When
	// empty a per-call id is derived from Meta.CorrelationID if set.
	RequestID string
}

Options configures a GeneratedClient.

type Page added in v0.4.19

type Page struct {
	Rows []map[string]any
	// NextPageToken is the cursor for the following page — empty on the last
	// page. Feed it back verbatim as PageOptions.PageToken; it is opaque.
	NextPageToken string
	// TotalCount is the number of rows in THIS page (see decodeRecordSet).
	TotalCount int32
}

Page is one page of a keyset-paginated read.

type PageOptions added in v0.4.19

type PageOptions struct {
	// Fields restricts the projection; empty selects every column.
	Fields []string
	// Sort defines the order; the primary key is appended as a tiebreaker
	// server-side so the cursor is stable.
	Sort []SortKey
	// Limit is the page size. A non-zero limit engages keyset pagination.
	Limit int32
	// PageToken continues a walk; empty requests the first page.
	PageToken string
}

PageOptions configures a keyset-paginated Select.

type PasskeyHelper added in v0.4.0

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

PasskeyHelper exposes Register/Authenticate passkey flows.

func (*PasskeyHelper) Authenticate added in v0.4.0

func (p *PasskeyHelper) Authenticate(ctx context.Context, userID, credentialJSON string) (*authnv1.FinishWebAuthnAuthenticationResponse, error)

Authenticate runs StartWebAuthnAuthentication -> FinishWebAuthnAuthentication, threading the single-use Start challenge into Finish.

func (*PasskeyHelper) Register added in v0.4.0

func (p *PasskeyHelper) Register(ctx context.Context, userID, label, credentialJSON string) (*authnv1.FinishWebAuthnRegistrationResponse, error)

Register runs StartWebAuthnRegistration -> FinishWebAuthnRegistration. The caller supplies the credential JSON the authenticator produced (or the dev soft-authenticator sentinel). The Start challenge_id is threaded into Finish.

type PolicyBundleSignatureError added in v0.4.0

type PolicyBundleSignatureError struct {
	KeyID         string
	Algorithm     string
	PolicyVersion string
}

PolicyBundleSignatureError is the typed error returned when a bundle's HMAC signature does not match. It carries the bundle's key id / algorithm / version for diagnostics.

func (*PolicyBundleSignatureError) Error added in v0.4.0

func (*PolicyBundleSignatureError) Is added in v0.4.0

func (e *PolicyBundleSignatureError) Is(target error) bool

Is lets errors.Is(err, ErrPolicyBundleSignature) succeed.

type ProtocolSupport added in v0.4.0

type ProtocolSupport struct {
	MinProtocolVersion     string
	MaxProtocolVersion     string
	Encodings              []string
	Compression            []string
	SupportsStreamingReads bool
	SupportsObjectStream   bool
	MaxRecvMessageBytes    int64
	MaxSendMessageBytes    int64
	SupportedRpcs          []string
}

ProtocolSupport is a defensive, hand-written view of the server's CapabilitiesResponse.protocol_support. It mirrors the proto field names but does not depend on the generated stub, so it works before the SDK is regenerated.

type QueryBuilder added in v0.4.0

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

QueryBuilder is the typed neutral-IR read builder. It emits `{"ir": {"op": "read", ...}}` (a `LogicalRead`).

udbclient.Query("acme.v1.Invoice").
	Where("status", "eq", "open").
	OrderBy("created_at", "desc").
	Limit(50)

func Query added in v0.4.0

func Query(messageType string) *QueryBuilder

Query starts a typed neutral-IR read for messageType (the catalog/proto FQN).

func (*QueryBuilder) Execute added in v0.4.0

Execute sends the read through the EXISTING GenericDispatch RPC, defaulting to DefaultIRBackend.

func (*QueryBuilder) ExecuteOn added in v0.4.0

func (q *QueryBuilder) ExecuteOn(ctx context.Context, dispatch IRDispatcher, backend string, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

ExecuteOn sends the read through GenericDispatch against an explicit backend.

func (*QueryBuilder) Include added in v0.4.0

func (q *QueryBuilder) Include(relation string) *QueryBuilder

func (*QueryBuilder) Limit added in v0.4.0

func (q *QueryBuilder) Limit(n int) *QueryBuilder

func (*QueryBuilder) Offset added in v0.4.0

func (q *QueryBuilder) Offset(n int) *QueryBuilder

func (*QueryBuilder) OrderBy added in v0.4.0

func (q *QueryBuilder) OrderBy(field, direction string) *QueryBuilder

OrderBy appends a sort key; direction is the snake_case token "asc" or "desc".

func (*QueryBuilder) Select added in v0.4.0

func (q *QueryBuilder) Select(fields ...string) *QueryBuilder

Select sets the projection (`LogicalProjection.fields`); omit to select every field.

func (*QueryBuilder) ToEnvelope added in v0.4.0

func (q *QueryBuilder) ToEnvelope() (any, error)

ToEnvelope returns the canonical neutral-IR envelope body.

func (*QueryBuilder) ToRequest added in v0.4.0

func (q *QueryBuilder) ToRequest(backend string) (*entityv1.GenericDispatchRequest, error)

ToRequest builds the GenericDispatchRequest — note: no tenant/project/context is set.

func (*QueryBuilder) ToSpecJSON added in v0.4.0

func (q *QueryBuilder) ToSpecJSON() (string, error)

func (*QueryBuilder) Where added in v0.4.0

func (q *QueryBuilder) Where(field, op string, value any) *QueryBuilder

func (*QueryBuilder) WhereFilter added in v0.4.0

func (q *QueryBuilder) WhereFilter(filter any) *QueryBuilder

func (*QueryBuilder) WhereIn added in v0.4.0

func (q *QueryBuilder) WhereIn(field string, values ...any) *QueryBuilder

type RPCInfo added in v0.4.0

type RPCInfo struct {
	Service     string  // e.g. DataBroker
	ServicePkg  string  // e.g. udb.services.v1
	FullMethod  string  // e.g. /udb.services.v1.DataBroker/Select
	Name        string  // wire RPC name, e.g. Select
	APIAlias    string  // descriptor SDK alias, e.g. select
	OperationID string  // OpenAPI operationId, e.g. selectRecords
	HTTPMethod  string  // REST method when the RPC has a descriptor HTTP route
	HTTPPath    string  // REST path when the RPC has a descriptor HTTP route
	Kind        RPCKind // streaming shape
	ReadOnly    bool    // proto EndpointSecurity.operation_kind == READ_ONLY; the
	// authoritative retry-safety flag (never guessed from the name)
	OperationKind string // "read_only" | "mutation" | "destructive"
	ReplaySafe    bool   // proto method_idempotency_contract.replay_safe; whether a

}

RPCInfo describes a single RPC.

func LookupRPC added in v0.4.0

func LookupRPC(nameOrPath string) (RPCInfo, bool)

LookupRPC finds an RPC by short name (e.g. "Select") or full method path.

type RPCKind added in v0.4.0

type RPCKind string

RPCKind classifies an RPC's streaming shape.

const (
	KindUnary           RPCKind = "unary"
	KindServerStreaming RPCKind = "server_streaming"
	KindClientStreaming RPCKind = "client_streaming"
	KindBidi            RPCKind = "bidi"
)

type ReadFence added in v0.4.0

type ReadFence struct {
	MinOutboxLsn      string   `json:"min_outbox_lsn,omitempty"`
	ProjectionTaskIds []string `json:"projection_task_ids,omitempty"`
	MaxWaitMs         uint64   `json:"max_wait_ms"`
}

ReadFence mirrors the Rust `ReadFence` struct (src/runtime/consistency.rs). In Rust, min_outbox_lsn and projection_task_ids carry skip_serializing_if (empty omitted); max_wait_ms is `#[serde(default)]` only (always emitted), so it has NO omitempty here.

func ReadFenceFromReceipt added in v0.4.0

func ReadFenceFromReceipt(r WriteReceipt, maxWaitMs uint64) ReadFence

ReadFenceFromReceipt builds the fence a follow-up read attaches to wait for its own write to be visible. It maps the receipt's SourceLsn -> MinOutboxLsn (the load-bearing cross-type field mapping from Rust `ReadFence::from_receipt`) and copies the projection task ids; it does NOT carry over outbox_seq or manifest_checksum.

func (ReadFence) IsEmpty added in v0.4.0

func (f ReadFence) IsEmpty() bool

IsEmpty reports whether the fence carries no positional constraint (only a wait budget, or nothing at all).

type Repository added in v0.4.0

type Repository struct {
	Descriptor  EntityDescriptor
	MessageType string
}

Repository is a descriptor-backed entity repository over the existing neutral-IR builders. It keeps no identity map or cache; 10.4 owns that layer.

func AccessDecisionAuditRepository added in v0.4.0

func AccessDecisionAuditRepository() (*Repository, error)

func ApiKeyRepository added in v0.4.0

func ApiKeyRepository() (*Repository, error)

func ApiKeyUsageRepository added in v0.4.0

func ApiKeyUsageRepository() (*Repository, error)

func AssetRepository added in v0.4.0

func AssetRepository() (*Repository, error)

func AuthzRevisionRepository added in v0.4.0

func AuthzRevisionRepository() (*Repository, error)

func BackupPolicyRepository added in v0.4.0

func BackupPolicyRepository() (*Repository, error)

func BackupRunRepository added in v0.4.0

func BackupRunRepository() (*Repository, error)

func CertificateBindingRepository added in v0.4.17

func CertificateBindingRepository() (*Repository, error)

func ControlPlaneNodeStateRepository added in v0.4.0

func ControlPlaneNodeStateRepository() (*Repository, error)

func ControlPlaneResourceRepository added in v0.4.0

func ControlPlaneResourceRepository() (*Repository, error)

func DeviceRepository added in v0.4.0

func DeviceRepository() (*Repository, error)

func EmbeddingDocumentRepository added in v0.4.17

func EmbeddingDocumentRepository() (*Repository, error)

func EmbeddingJobRepository added in v0.4.17

func EmbeddingJobRepository() (*Repository, error)

func EmbeddingModelRepository added in v0.4.17

func EmbeddingModelRepository() (*Repository, error)

func EmbeddingSourceRepository added in v0.4.0

func EmbeddingSourceRepository() (*Repository, error)

func EmbeddingWorkItemRepository added in v0.4.17

func EmbeddingWorkItemRepository() (*Repository, error)

func ExecutorPerformanceSummaryRepository added in v0.4.0

func ExecutorPerformanceSummaryRepository() (*Repository, error)

func ExternalIdentityRepository added in v0.4.0

func ExternalIdentityRepository() (*Repository, error)

func FileRepository added in v0.4.0

func FileRepository() (*Repository, error)

func FlagRepository added in v0.4.0

func FlagRepository() (*Repository, error)

func IdentityProviderRepository added in v0.4.0

func IdentityProviderRepository() (*Repository, error)

func LockRepository added in v0.4.0

func LockRepository() (*Repository, error)

func MfaChallengeRepository added in v0.4.0

func MfaChallengeRepository() (*Repository, error)

func MfaPolicyRepository added in v0.4.0

func MfaPolicyRepository() (*Repository, error)

func NotificationDeliveryAttemptRepository added in v0.4.0

func NotificationDeliveryAttemptRepository() (*Repository, error)

func NotificationLogRepository added in v0.4.0

func NotificationLogRepository() (*Repository, error)

func NotificationPreferenceRepository added in v0.4.0

func NotificationPreferenceRepository() (*Repository, error)

func NotificationRepository added in v0.4.0

func NotificationRepository() (*Repository, error)

func NotificationTemplateRepository added in v0.4.0

func NotificationTemplateRepository() (*Repository, error)

func OtpRepository added in v0.4.0

func OtpRepository() (*Repository, error)

func PeerRepository added in v0.4.0

func PeerRepository() (*Repository, error)

func PipelineDefinitionRepository added in v0.4.0

func PipelineDefinitionRepository() (*Repository, error)

func PipelineInstanceRepository added in v0.4.0

func PipelineInstanceRepository() (*Repository, error)

func PipelineMetricSnapshotRepository added in v0.4.0

func PipelineMetricSnapshotRepository() (*Repository, error)

func PipelineStepRepository added in v0.4.0

func PipelineStepRepository() (*Repository, error)

func PolicyApprovalRepository added in v0.4.0

func PolicyApprovalRepository() (*Repository, error)

func PolicyCanaryRepository added in v0.4.0

func PolicyCanaryRepository() (*Repository, error)

func PolicyDraftRepository added in v0.4.0

func PolicyDraftRepository() (*Repository, error)

func PolicyRuleRepository added in v0.4.0

func PolicyRuleRepository() (*Repository, error)

func PolicySetRepository added in v0.4.0

func PolicySetRepository() (*Repository, error)

func PolicySimulationRepository added in v0.4.0

func PolicySimulationRepository() (*Repository, error)

func PolicyTupleRepository added in v0.4.0

func PolicyTupleRepository() (*Repository, error)

func PolicyVersionRepository added in v0.4.0

func PolicyVersionRepository() (*Repository, error)

func QuotaRuleRepository added in v0.4.0

func QuotaRuleRepository() (*Repository, error)

func ReconciliationAnalyticsSummaryRepository added in v0.4.0

func ReconciliationAnalyticsSummaryRepository() (*Repository, error)

func RecoveryCodeRepository added in v0.4.0

func RecoveryCodeRepository() (*Repository, error)

func RepositoryFor added in v0.4.0

func RepositoryFor(messageType string) (*Repository, error)

func RolePermissionRepository added in v0.4.0

func RolePermissionRepository() (*Repository, error)

func RoleRepository added in v0.4.0

func RoleRepository() (*Repository, error)

func RoomRepository added in v0.4.0

func RoomRepository() (*Repository, error)

func SamlReplayEntryRepository added in v0.4.0

func SamlReplayEntryRepository() (*Repository, error)

func ScheduledJobRepository added in v0.4.0

func ScheduledJobRepository() (*Repository, error)

func ScimDirectoryStateRepository added in v0.4.0

func ScimDirectoryStateRepository() (*Repository, error)

func SearchIndexRepository added in v0.4.0

func SearchIndexRepository() (*Repository, error)

func ServiceAccountGrantRepository added in v0.4.17

func ServiceAccountGrantRepository() (*Repository, error)

func SessionRepository added in v0.4.0

func SessionRepository() (*Repository, error)

func SigningKeyRepository added in v0.4.0

func SigningKeyRepository() (*Repository, error)

func TenantConfigRepository added in v0.4.0

func TenantConfigRepository() (*Repository, error)

func TenantRepository added in v0.4.0

func TenantRepository() (*Repository, error)

func TokenFamilyRepository added in v0.4.0

func TokenFamilyRepository() (*Repository, error)

func TokenRevocationRepository added in v0.4.0

func TokenRevocationRepository() (*Repository, error)

func TrackRepository added in v0.4.0

func TrackRepository() (*Repository, error)

func UsageEventRepository added in v0.4.0

func UsageEventRepository() (*Repository, error)

func UserRepository added in v0.4.0

func UserRepository() (*Repository, error)

func UserRoleRepository added in v0.4.0

func UserRoleRepository() (*Repository, error)

func VaultDbCredentialLeaseRepository added in v0.4.0

func VaultDbCredentialLeaseRepository() (*Repository, error)

func VaultSecretRepository added in v0.4.0

func VaultSecretRepository() (*Repository, error)

func VaultTransitKeyRepository added in v0.4.0

func VaultTransitKeyRepository() (*Repository, error)

func WebAuthnCredentialRepository added in v0.4.0

func WebAuthnCredentialRepository() (*Repository, error)

func WebAuthnPolicyRepository added in v0.4.0

func WebAuthnPolicyRepository() (*Repository, error)

func WebhookDeliveryRepository added in v0.4.0

func WebhookDeliveryRepository() (*Repository, error)

func WebhookEndpointRepository added in v0.4.0

func WebhookEndpointRepository() (*Repository, error)

func WorkflowInstanceRepository added in v0.4.0

func WorkflowInstanceRepository() (*Repository, error)

func (*Repository) All added in v0.4.0

func (*Repository) Delete added in v0.4.0

func (r *Repository) Delete(ctx context.Context, dispatch IRDispatcher, key map[string]any, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

func (*Repository) Find added in v0.4.0

func (r *Repository) Find(ctx context.Context, dispatch IRDispatcher, key map[string]any, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

func (*Repository) First added in v0.4.0

func (*Repository) Query added in v0.4.0

func (r *Repository) Query() *QueryBuilder

func (*Repository) Relation added in v0.4.0

func (r *Repository) Relation(name string) (EntityRelationDescriptor, bool)

func (*Repository) RelationBatchQuery added in v0.4.0

func (r *Repository) RelationBatchQuery(name string, parents []map[string]any) (*QueryBuilder, error)

func (*Repository) RelationQuery added in v0.4.0

func (r *Repository) RelationQuery(name string, parent map[string]any) (*QueryBuilder, error)

func (*Repository) Relations added in v0.4.0

func (r *Repository) Relations() []EntityRelationDescriptor

func (*Repository) RequireRelation added in v0.4.0

func (r *Repository) RequireRelation(name string) (EntityRelationDescriptor, error)

func (*Repository) Upsert added in v0.4.0

func (r *Repository) Upsert(ctx context.Context, dispatch IRDispatcher, record map[string]any, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

type RequestContextMeta added in v0.4.0

type RequestContextMeta struct {
	TenantID        string
	ProjectID       string
	UserID          string
	CorrelationID   string
	RequestID       string
	Purpose         string
	ServiceIdentity string
	Scopes          []string
}

RequestContextMeta is a unified, SDK-level request context (critic.md §14).

UDB has TWO proto RequestContext shapes: the DataBroker's flat entity/v1.RequestContext{TenantId, ProjectId, ...} and the native services' nested core/common/v1.RequestContext{Tenant: TenantContext{...}, ...}. App code should not have to import both packages or remember which RPC wants which shape — build this once from Metadata and convert with ToEntity()/ToCommon().

func (RequestContextMeta) ToCommon added in v0.4.0

ToCommon builds the native-service (core/common/v1) RequestContext, nesting the tenant/project under TenantContext as those RPCs expect.

func (RequestContextMeta) ToEntity added in v0.4.0

ToEntity builds the DataBroker (entity/v1) RequestContext.

type RetryConfig added in v0.4.0

type RetryConfig struct {
	MaxAttempts  int           // total tries including the first; <=1 disables retry
	BaseBackoff  time.Duration // backoff for the first retry
	MaxBackoff   time.Duration // backoff ceiling
	Jitter       float64       // 0..1 fraction of randomized jitter added to each backoff
	RetryOnCodes []codes.Code  // transient codes retried only for read-only unary RPCs
}

RetryConfig controls the backoff retry behavior of the generated wrappers. The zero value is unusable; use DefaultRetryConfig().

func DefaultRetryConfig added in v0.4.0

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the proven UDB defaults: 4 attempts, 100ms base, 5s ceiling, full jitter, retrying only read-only unary RPCs on transient codes. Mutating RPCs are never retried automatically.

type Session added in v0.4.0

type Session struct {
	Result *webrtcv1.JoinSessionResponse
	Stream grpc.BidiStreamingClient[webrtcv1.SignalRequest, webrtcv1.SignalResponse]
	// contains filtered or unexported fields
}

Session is the handle JoinSession returns: the atomically-joined peer + ICE + existing peers from the single JoinSession RPC, plus the live signaling stream. Leave closes the stream and removes the peer from the room.

func (*Session) Leave added in v0.4.0

func (s *Session) Leave(ctx context.Context) error

Leave closes the signaling stream and issues LeaveRoom. Safe to call once.

func (*Session) PeerID added in v0.4.0

func (s *Session) PeerID() string

PeerID returns the joined peer's id.

type SortKey added in v0.4.19

type SortKey struct {
	Field      string
	Descending bool
}

SortKey is one ordering key for a paged Select.

type StartAndWaitResult added in v0.4.0

type StartAndWaitResult struct {
	InstanceID string
	Steps      []*assetentityv1.PipelineStep
	Status     assetentityv1.PipelineStatus
}

StartAndWaitResult carries a StartAndWait outcome: the inline steps the StartPipeline response already returned (no GetPipeline proof read needed) and the terminal instance status reached by the bounded status poll.

type StorageFacade added in v0.4.0

type StorageFacade struct {
	Raw storagev1.StorageServiceClient

	// MaxUploadBytes caps the in-memory UploadFile byte path; zero = unlimited.
	// UploadFile returns a typed error BEFORE any RPC when the payload exceeds it.
	MaxUploadBytes int64
	// contains filtered or unexported fields
}

StorageFacade wraps StorageServiceClient.

func (*StorageFacade) DeleteFile added in v0.4.0

func (f *StorageFacade) DeleteFile(ctx context.Context, fileID string) (*storagev1.DeleteFileResponse, error)

DeleteFile removes a file (and schedules its object for GC). tenant defaults to the Metadata.

func (*StorageFacade) DownloadFile added in v0.4.0

func (f *StorageFacade) DownloadFile(ctx context.Context, fileID string, expiresInMinutes int32) (*storagev1.GetDownloadUrlResponse, error)

DownloadFile is the canonical naming-contract download accessor and the PREFERRED happy path: it mints a time-limited presigned download URL for fileID so the bytes never transit the broker. It emits EXACTLY one GetDownloadUrl RPC (no GetFile probe) — a fileId-first alias of GetDownloadUrl. expiresInMinutes of zero lets the server choose its default; tenant defaults to the caller Metadata. Callers that cannot use a presigned HTTP URL and need the bytes returned through the broker use DownloadFileBytes, which drives the server-streaming DownloadFile RPC instead.

func (*StorageFacade) DownloadFileBytes added in v0.4.0

func (f *StorageFacade) DownloadFileBytes(ctx context.Context, fileID string, opts ...DownloadOption) (*DownloadResult, error)

DownloadFileBytes is the byte-fetch download path. The presigned URL flow (DownloadFile -> GetDownloadUrl) is the happy path and keeps bytes OUT of the broker; DownloadFileBytes is for callers that cannot resolve/use a presigned HTTP URL and need the bytes back through the broker. It calls the new server-streaming DownloadFile RPC and reassembles the bounded DownloadFileChunk stream into a single buffer. tenant defaults to the caller Metadata. The MaxBytes cap (option) fails closed with a typed error before the buffer can grow past it.

func (*StorageFacade) FinalizeUpload added in v0.4.0

func (f *StorageFacade) FinalizeUpload(ctx context.Context, fileID string, sizeBytes int64) (*storagev1.FinalizeUploadResponse, error)

FinalizeUpload marks a registered file as uploaded, persisting its actual sizeBytes. tenant defaults to the caller Metadata.

func (*StorageFacade) GetDownloadUrl added in v0.4.0

func (f *StorageFacade) GetDownloadUrl(ctx context.Context, fileID string, expiresInMinutes int32) (*storagev1.GetDownloadUrlResponse, error)

GetDownloadUrl returns a presigned download URL valid for expiresInMinutes (zero lets the server choose its default). tenant defaults to the Metadata.

func (*StorageFacade) GetFile added in v0.4.0

func (f *StorageFacade) GetFile(ctx context.Context, fileID string) (*storagev1.GetFileResponse, error)

GetFile fetches file metadata by id. tenant defaults to the Metadata.

func (*StorageFacade) ListFiles added in v0.4.0

func (f *StorageFacade) ListFiles(ctx context.Context, fileType string, page, pageSize int32) (*storagev1.ListFilesResponse, error)

ListFiles paginates files for the tenant, optionally filtered by fileType. page/pageSize of zero use the server defaults. tenant defaults to the Metadata.

func (*StorageFacade) RegisterUpload added in v0.4.0

func (f *StorageFacade) RegisterUpload(ctx context.Context, filename, contentType, fileType string, sizeBytes int64) (*storagev1.RegisterUploadResponse, error)

RegisterUpload reserves a file id + presigned upload target and runs the pre-upload tenant quota check against sizeBytes. tenant/project default to the caller Metadata.

func (*StorageFacade) UpdateFile added in v0.4.0

func (f *StorageFacade) UpdateFile(ctx context.Context, fileID, filename, contentType, fileType string, isPublic bool) (*storagev1.UpdateFileResponse, error)

UpdateFile updates mutable file metadata. tenant defaults to the Metadata.

func (*StorageFacade) UploadFile added in v0.4.0

func (f *StorageFacade) UploadFile(ctx context.Context, filename string, data []byte, opts ...UploadOption) (*storagev1.FinalizeUploadResponse, error)

UploadFile is the combined register -> PUT -> finalize helper. It performs EXACTLY those three steps with NO hidden Get/List proof read (perf guardrail):

  1. RegisterUpload(filename, len(data)) -> file id + presigned upload_url
  2. HTTP PUT the bytes to upload_url (only when the broker returned one)
  3. FinalizeUpload(file id, len(data)) with the optional checksum/etag

filename and data are positional; all other inputs live in UploadOptions via functional options. The MaxUploadBytes cap is enforced before any RPC.

type Subscription added in v0.4.0

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

Subscription is a live CDC subscription handle.

func (*Subscription) Ready added in v0.4.0

func (s *Subscription) Ready() error

Ready blocks until the first server-driven signal on the subscription. It reads the stream header (server metadata) when available, then waits for the first envelope — buffering it for the next Recv so no event is lost. No timer or sleep is used; it returns when the server speaks or the stream/context ends.

func (*Subscription) Recv added in v0.4.0

func (s *Subscription) Recv() (*eventsv1.CDCEnvelope, error)

Recv returns the next CDC envelope (replaying the one Ready may have buffered).

type TenantFacade added in v0.4.0

type TenantFacade struct {
	Raw tenantv1.TenantServiceClient
	// contains filtered or unexported fields
}

TenantFacade wraps TenantServiceClient.

func (*TenantFacade) Create added in v0.4.0

func (f *TenantFacade) Create(ctx context.Context, code, name string) (*tenantv1.CreateTenantResponse, error)

Create provisions a new tenant from a code + display name.

func (*TenantFacade) Onboard added in v0.4.0

func (f *TenantFacade) Onboard(ctx context.Context, code, name, tenantType, configJSON, brandingJSON string) (*tenantv1.CreateTenantResponse, error)

Onboard is the fuller create path: code, name, type, and JSON config/branding. Empty config/branding are sent as-is (the server treats them as defaults).

type TenantState added in v0.4.0

type TenantState struct {
	// TenantCode is the human code supplied before login. Used only as a hint;
	// never written into tenant-scoped data.
	TenantCode string
	// CanonicalID is the verified canonical tenant UUID from the authenticated
	// principal. Empty until Adopt succeeds.
	CanonicalID string
	// IsVerified reports whether CanonicalID has been adopted post-login.
	IsVerified bool
}

TenantState makes the tenant-code → canonical-UUID transition explicit (critic.md §15). The human tenant code (e.g. "acme", "billing") is only a pre-login hint; after login the broker resolves and verifies the canonical tenant UUID, and THAT is the value every tenant-scoped record/filter must use. Conflating the two is a subtle, high-risk bug (reads miss, writes stamp an unusable tenant, operators blame RLS) — this type keeps them separate and fails fast on mismatch.

func NewTenantState added in v0.4.0

func NewTenantState(code string) TenantState

NewTenantState creates an unverified state from a human tenant code/hint.

func (*TenantState) Adopt added in v0.4.0

func (t *TenantState) Adopt(canonicalID string) error

Adopt records the canonical tenant UUID returned by the verified principal.

func (TenantState) GetVerified added in v0.4.0

func (t TenantState) GetVerified() (string, error)

GetVerified returns the canonical tenant UUID, or an error if login/adoption has not happened yet — so tenant-scoped requests fail fast instead of silently using the human code.

func (TenantState) ValidateTenantID added in v0.4.0

func (t TenantState) ValidateTenantID(recordTenantID string) error

ValidateTenantID rejects a tenant-scoped record/filter whose tenant_id differs from the verified canonical tenant, naming both values (critic.md §15). An empty recordTenantID passes (the caller will fill it from GetVerified()).

type Token added in v0.4.0

type Token struct {
	AccessToken  string
	RefreshToken string
	SessionID    string
	ExpiresAt    time.Time
}

Token is the credential set a TokenManager stores. ExpiresAt is absolute; a zero value means "unknown / never auto-refresh".

func (Token) Valid added in v0.4.0

func (t Token) Valid(now time.Time, skew time.Duration) bool

Valid reports whether the token is non-empty and not within skew of expiry.

type TokenManager added in v0.4.0

type TokenManager struct {

	// RefreshSkew refreshes this long before actual expiry. Default 30s.
	RefreshSkew time.Duration
	// contains filtered or unexported fields
}

TokenManager logs in, stores the token, and refreshes it on demand with a single-flight guard so concurrent callers share one refresh round-trip.

func NewTokenManager added in v0.4.0

func NewTokenManager(auth *AuthClient, store TokenStore) *TokenManager

NewTokenManager builds a manager over an AuthClient. A nil store defaults to an in-memory store.

func (*TokenManager) Login added in v0.4.0

func (m *TokenManager) Login(ctx context.Context, req *authnv1.AuthnRequest) (Token, error)

Login authenticates with a fully-formed AuthnRequest (use AuthClient's typed helpers to build it), stores the resulting Token, and returns it. The access token + session id + absolute expiry are derived from AuthnResponse.

func (*TokenManager) LoginWithDevice added in v0.4.0

func (m *TokenManager) LoginWithDevice(ctx context.Context, req *authnv1.LoginRequest) (Token, error)

LoginWithDevice authenticates via the native AuthnService.Login RPC (rather than the generic Authenticate path), so a stable LoginRequest.DeviceId is sent to the broker — which mints a LISTABLE device row only when device_id is non-empty. This removes the need for a GenericDispatch device-seed workaround without any SDK-side proof read. The resulting Token is stored and returned.

func (*TokenManager) RefreshIfNeeded added in v0.4.0

func (m *TokenManager) RefreshIfNeeded(ctx context.Context) error

RefreshIfNeeded refreshes the stored token if it is stale, sharing one in-flight refresh among concurrent callers. If the token is already fresh it returns immediately.

func (*TokenManager) Token added in v0.4.0

func (m *TokenManager) Token(ctx context.Context) (Token, error)

Token returns the stored token, refreshing it first when it is expired or within RefreshSkew of expiry. Concurrent callers that all see a stale token share exactly one RefreshToken RPC.

type TokenStore added in v0.4.0

type TokenStore interface {
	Load(ctx context.Context) (Token, error)
	Save(ctx context.Context, tok Token) error
}

TokenStore persists a Token across calls (and, optionally, processes). The in-memory MemoryTokenStore is the default; callers can supply a file/keyring backed implementation.

type Udb added in v0.4.0

type Udb struct {
	Meta Metadata

	// Generated is the robustness layer governing the broker connection.
	Generated *GeneratedClient

	Data         *Client                            // DataBroker (Select/Upsert/Delete + raw Broker)
	Auth         *AuthClient                        // Authn + Authz raw clients and helpers
	Authz        *AuthzFacade                       // Can/Require/BatchCan/Explain/NativeAccess (cached)
	ApiKey       *ApiKeyFacade                      // CreateApiKey/RevokeApiKey + raw
	Tenant       *TenantFacade                      // CreateTenant/onboarding + raw
	Notification *NotificationFacade                // SendNotification + raw
	Analytics    analyticsv1.AnalyticsServiceClient // raw analytics client

	Storage *StorageFacade // StorageService (upload/download/file CRUD) + raw
	Asset   *AssetFacade   // AssetService (pipeline + asset CRUD) + raw
	WebRTC  *WebRTCFacade  // WebRTC Room/Peer/Track/Turn sub-facades + Signal stream
	Events  *EventsFacade  // DataBroker PublishCDC/EnqueueOutboxEvent ready/publish-and-wait
	// contains filtered or unexported fields
}

Udb is the unified project facade returned by NewUdb.

func Connect added in v0.4.0

func Connect(ctx context.Context, cfg Config) (*Udb, error)

Connect is the canonical naming-contract constructor: it dials the broker and wires the full project facade. It is a thin alias of NewUdb (no behavior difference) so the simple-client surface reads `udbclient.Connect(ctx, opts)` across languages. NewUdb stays as the original name.

func NewUdb added in v0.4.0

func NewUdb(ctx context.Context, cfg Config) (*Udb, error)

NewUdb dials the broker (and the auth endpoint, if different), builds the generated robustness layer, and wires every available per-domain client.

func (*Udb) Admin added in v0.4.0

func (u *Udb) Admin() *AdminFacade

Admin returns the migration-lifecycle helper for the project.

func (*Udb) Close added in v0.4.0

func (u *Udb) Close() error

Close closes every connection NewUdb owns. Safe to call once.

func (*Udb) Entity added in v0.4.0

func (u *Udb) Entity(fqn string, key EntityKey) *Entity

Entity forwards to the data-plane Client's binder so both u.Entity(...) and u.Data.Entity(...) surfaces from the masterplan exist.

func (*Udb) LoginAndAdoptTenant added in v0.4.0

func (u *Udb) LoginAndAdoptTenant(ctx context.Context, req *authnv1.LoginRequest) (*AdoptedLogin, error)

LoginAndAdoptTenant performs the CANONICAL 2-RPC login-and-adopt sequence:

  1. Login (native AuthnService.Login) to obtain the bearer access token.
  2. AuthenticateBearer to resolve + VERIFY the canonical principal.

It then derives the FULL identity {tenant_id, project_id, user_id, service_identity, scopes} FROM THE VERIFIED PRINCIPAL (never a body hint), atomically adopts that metadata across every facade (adoptMetadata), and installs the bearer as the authorization credential. Both RPCs ALWAYS run — there is no "skip authenticate if a principal is already present" branch. No body tenant copying afterward (the broker derives identity from the verified claim).

func (*Udb) Metadata added in v0.4.0

func (u *Udb) Metadata() *MetadataAccessor

Metadata returns the metadata accessor mounted on the project facade so udb.Metadata().AfterWrite(rc, receipt, maxWaitMs) mirrors TS udb.metadata.afterWrite(receipt).

type UnitOfWork added in v0.4.0

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

func NewUnitOfWork added in v0.4.0

func NewUnitOfWork() *UnitOfWork

func (*UnitOfWork) Attach added in v0.4.0

func (u *UnitOfWork) Attach(repo *Repository, record map[string]any) (map[string]any, error)

func (*UnitOfWork) CommitMutation added in v0.4.0

func (u *UnitOfWork) CommitMutation() *entityv1.Mutation

func (*UnitOfWork) DirtyEntries added in v0.4.0

func (u *UnitOfWork) DirtyEntries() ([]UnitOfWorkEntry, error)

func (*UnitOfWork) Flush added in v0.4.0

func (u *UnitOfWork) Flush(ctx context.Context, client *GeneratedClient, backend ...string) ([]*entityv1.TxStatus, error)

func (*UnitOfWork) MarkClean added in v0.4.0

func (u *UnitOfWork) MarkClean() error

func (*UnitOfWork) RequireTransactionalBackend added in v0.4.0

func (u *UnitOfWork) RequireTransactionalBackend(backend string) error

func (*UnitOfWork) RollbackMutation added in v0.4.0

func (u *UnitOfWork) RollbackMutation() *entityv1.Mutation

func (*UnitOfWork) Track added in v0.4.0

func (u *UnitOfWork) Track(repo *Repository, record map[string]any) (map[string]any, error)

func (*UnitOfWork) TxCommitBatch added in v0.4.0

func (u *UnitOfWork) TxCommitBatch(backend ...string) ([]*entityv1.Mutation, error)

func (*UnitOfWork) TxMutations added in v0.4.0

func (u *UnitOfWork) TxMutations() ([]*entityv1.Mutation, error)

func (*UnitOfWork) ValidateTxStatuses added in v0.4.0

func (u *UnitOfWork) ValidateTxStatuses(statuses []*entityv1.TxStatus) error

type UnitOfWorkConflictError added in v0.4.0

type UnitOfWorkConflictError struct {
	UnitOfWorkTxError
}

type UnitOfWorkEntry added in v0.4.0

type UnitOfWorkEntry struct {
	Repository *Repository
	Record     map[string]any
	// contains filtered or unexported fields
}

type UnitOfWorkTxError added in v0.4.0

type UnitOfWorkTxError struct {
	Status *entityv1.TxStatus
}

func (*UnitOfWorkTxError) Error added in v0.4.0

func (e *UnitOfWorkTxError) Error() string

type UnitOfWorkUnsupportedBackendError added in v0.4.0

type UnitOfWorkUnsupportedBackendError struct {
	Backend string
	Role    string
}

func (*UnitOfWorkUnsupportedBackendError) Error added in v0.4.0

type UpdateOption added in v0.4.23

type UpdateOption func(*updateOptions)

UpdateOption configures Update / Increment.

func WithUpdateExpected added in v0.4.23

func WithUpdateExpected(expected map[string]any) UpdateOption

WithUpdateExpected makes the Update a compare-and-swap: every field -> value must still equal the CURRENT row (row-locked, same tenant/RLS transaction) or the broker returns FAILED_PRECONDITION and writes nothing. Requires the filter to pin every primary-key column by equality. Passing a nil/empty map is rejected with errEmptyCAS BEFORE any RPC — a guarded update must never degrade into an unconditional one (for that, omit this option).

func WithUpdateIdempotencyKey added in v0.4.23

func WithUpdateIdempotencyKey(key string) UpdateOption

WithUpdateIdempotencyKey enables durable keyed replay: a retried Update with the same key returns the original response with was_duplicate=true.

func WithUpdateReturnRecord added in v0.4.23

func WithUpdateReturnRecord() UpdateOption

WithUpdateReturnRecord asks the broker to return the post-update row.

type UploadOption added in v0.4.0

type UploadOption func(*UploadOptions)

UploadOption is a functional option mutating UploadOptions.

func WithChecksum added in v0.4.0

func WithChecksum(c string) UploadOption

WithChecksum sets a content checksum persisted on finalize.

func WithContentType added in v0.4.0

func WithContentType(ct string) UploadOption

WithContentType sets the upload Content-Type (used for the PUT header and the RegisterUpload request).

func WithETag added in v0.4.0

func WithETag(e string) UploadOption

WithETag asserts an object etag on finalize.

func WithFileType added in v0.4.0

func WithFileType(ft string) UploadOption

WithFileType sets the logical file type bucket.

type UploadOptions added in v0.4.0

type UploadOptions struct {
	ContentType string
	FileType    string
	Checksum    string // optional integrity checksum persisted on finalize
	ETag        string // optional object etag asserted on finalize
}

UploadOptions carries the non-positional UploadFile inputs. The CANONICAL cross-language signature keeps filename + bytes positional and everything else here (matching the TS/Python uploadFile(filename, bytes, options) shape).

type UpsertOption added in v0.4.0

type UpsertOption func(*upsertOptions)

UpsertOption configures Upsert.

func ReturnRecord added in v0.4.0

func ReturnRecord() UpsertOption

ReturnRecord requests that Upsert decode the MutationResponse.record_json the broker already returns on the SAME response — it does NOT issue a second Get.

func WithExpected added in v0.4.15

func WithExpected(expected map[string]any) UpsertOption

WithExpected makes the Upsert a compare-and-swap: each field -> value assertion must equal the CURRENT row (located by the bound entity key and row-locked) inside the same transaction and tenant/RLS context as the write. If the row is absent or any assertion fails, the broker returns FAILED_PRECONDITION and writes nothing — so an optimistic "update WHERE version = N" is atomic without raw SQL or an external lock. Combine with WithIdempotencyKey for replay-safety of the winning command. A nil/empty map leaves the request unconditional (unchanged behavior).

func WithIdempotencyKey added in v0.4.15

func WithIdempotencyKey(key string) UpsertOption

WithIdempotencyKey attaches a caller-supplied durable idempotency key to the Upsert. The broker deduplicates replays of the SAME key (surfacing WasDuplicate) so an ambiguous client/network retry cannot create a second row or repeat a side effect, and it re-enables the generated mutation retry policy for this bound-entity path. A key that is present but only whitespace is rejected; an unset key leaves the request's idempotency_key empty (unchanged).

type UpsertResult added in v0.4.0

type UpsertResult struct {
	Response *entityv1.MutationResponse
	Record   map[string]any
	// WasDuplicate is true when the broker collapsed this write onto a prior one
	// via durable idempotency (a replay of the same idempotency key) instead of
	// applying a fresh mutation. Mirrors MutationResponse.was_duplicate so a
	// caller can distinguish an idempotency replay from a fresh write.
	WasDuplicate bool
}

UpsertResult carries an Upsert outcome. Record is populated only when ReturnRecord() was passed and the broker returned a record body.

type WebRTCFacade added in v0.4.0

type WebRTCFacade struct {
	Room  *WebRTCRoomFacade
	Peer  *WebRTCPeerFacade
	Track *WebRTCTrackFacade
	Turn  *WebRTCTurnFacade

	// RawSignaling is the bidi signaling client backing Signal.
	RawSignaling webrtcv1.SignalingServiceClient
	// contains filtered or unexported fields
}

WebRTCFacade groups the WebRTC sub-facades.

func (*WebRTCFacade) JoinSession added in v0.4.0

func (f *WebRTCFacade) JoinSession(ctx context.Context, roomID, displayName, metadataJSON, userAgent string, ttlSeconds int32) (*Session, error)

JoinSession joins a room atomically via the JoinSession RPC (peer + ICE + existing peers in ONE call — no SDK-side JoinRoom+IssueCredentials fan-out), then opens the bidi signaling stream for the session. tenant defaults from the facade Metadata. The caller drives the returned Stream and ends the session with Leave. Reconnect is the caller's concern and is denied after a first observed response until the broker exposes a resume token (guardrail).

func (*WebRTCFacade) Signal added in v0.4.0

Signal opens the bidirectional SDP/ICE signaling stream. The caller drives it with stream.Send / stream.Recv and closes it via stream.CloseSend. This is the honest surface for a bidi stream — the facade does not buffer or fake frames.

type WebRTCPeerFacade added in v0.4.0

type WebRTCPeerFacade struct {
	Raw webrtcv1.PeerServiceClient
	// contains filtered or unexported fields
}

WebRTCPeerFacade wraps PeerServiceClient.

func (*WebRTCPeerFacade) GetPeer added in v0.4.0

func (f *WebRTCPeerFacade) GetPeer(ctx context.Context, peerID string) (*webrtcv1.GetPeerResponse, error)

GetPeer fetches a peer by id. tenant defaults to the Metadata.

func (*WebRTCPeerFacade) JoinRoom added in v0.4.0

func (f *WebRTCPeerFacade) JoinRoom(ctx context.Context, roomID, displayName, metadataJSON, userAgent string) (*webrtcv1.JoinRoomResponse, error)

JoinRoom adds a peer to a room. metadataJSON is an optional JSON blob. tenant defaults to the Metadata.

func (*WebRTCPeerFacade) LeaveRoom added in v0.4.0

func (f *WebRTCPeerFacade) LeaveRoom(ctx context.Context, roomID, peerID string) (*webrtcv1.LeaveRoomResponse, error)

LeaveRoom removes a peer from a room. tenant defaults to the Metadata.

func (*WebRTCPeerFacade) ListPeers added in v0.4.0

func (f *WebRTCPeerFacade) ListPeers(ctx context.Context, roomID, state string) (*webrtcv1.ListPeersResponse, error)

ListPeers lists peers in a room, optionally filtered by state. tenant defaults to the Metadata.

type WebRTCRoomFacade added in v0.4.0

type WebRTCRoomFacade struct {
	Raw webrtcv1.RoomServiceClient
	// contains filtered or unexported fields
}

WebRTCRoomFacade wraps RoomServiceClient.

func (*WebRTCRoomFacade) CloseRoom added in v0.4.0

func (f *WebRTCRoomFacade) CloseRoom(ctx context.Context, roomID string) (*webrtcv1.CloseRoomResponse, error)

CloseRoom closes a room by id. tenant defaults to the Metadata.

func (*WebRTCRoomFacade) CreateRoom added in v0.4.0

func (f *WebRTCRoomFacade) CreateRoom(ctx context.Context, name string, maxParticipants int32, configJSON, createdBy string) (*webrtcv1.CreateRoomResponse, error)

CreateRoom provisions a room. configJSON is an optional JSON config; createdBy defaults to the caller Metadata UserID when empty. tenant defaults to the Metadata.

func (*WebRTCRoomFacade) GetRoom added in v0.4.0

func (f *WebRTCRoomFacade) GetRoom(ctx context.Context, roomID string) (*webrtcv1.GetRoomResponse, error)

GetRoom fetches a room by id. tenant defaults to the Metadata.

func (*WebRTCRoomFacade) ListRooms added in v0.4.0

func (f *WebRTCRoomFacade) ListRooms(ctx context.Context, state string, page, pageSize int32) (*webrtcv1.ListRoomsResponse, error)

ListRooms paginates rooms for the tenant, optionally filtered by state. page/pageSize of zero use the server defaults. tenant defaults to the Metadata.

func (*WebRTCRoomFacade) UpdateRoom added in v0.4.0

func (f *WebRTCRoomFacade) UpdateRoom(ctx context.Context, roomID, name, state, configJSON string) (*webrtcv1.UpdateRoomResponse, error)

UpdateRoom updates a room's name/state/config. tenant defaults to the Metadata.

type WebRTCTrackFacade added in v0.4.0

type WebRTCTrackFacade struct {
	Raw webrtcv1.TrackServiceClient
	// contains filtered or unexported fields
}

WebRTCTrackFacade wraps TrackServiceClient.

func (*WebRTCTrackFacade) ListTracks added in v0.4.0

func (f *WebRTCTrackFacade) ListTracks(ctx context.Context, roomID, peerID, kind string) (*webrtcv1.ListTracksResponse, error)

ListTracks lists tracks in a room, optionally filtered by peerID and kind. tenant defaults to the Metadata.

func (*WebRTCTrackFacade) MuteTrack added in v0.4.0

func (f *WebRTCTrackFacade) MuteTrack(ctx context.Context, trackID string, muted bool) (*webrtcv1.MuteTrackResponse, error)

MuteTrack sets the muted state of a track. tenant defaults to the Metadata.

func (*WebRTCTrackFacade) PublishTrack added in v0.4.0

func (f *WebRTCTrackFacade) PublishTrack(ctx context.Context, roomID, peerID, kind, label, settingsJSON, metadataJSON string) (*webrtcv1.PublishTrackResponse, error)

PublishTrack publishes a media track for a peer. settingsJSON/metadataJSON are optional JSON blobs. tenant defaults to the Metadata.

func (*WebRTCTrackFacade) UnpublishTrack added in v0.4.0

func (f *WebRTCTrackFacade) UnpublishTrack(ctx context.Context, trackID string) (*webrtcv1.UnpublishTrackResponse, error)

UnpublishTrack removes a published track by id. tenant defaults to the Metadata.

type WebRTCTurnFacade added in v0.4.0

type WebRTCTurnFacade struct {
	Raw webrtcv1.TurnServiceClient
	// contains filtered or unexported fields
}

WebRTCTurnFacade wraps TurnServiceClient.

func (*WebRTCTurnFacade) IssueCredentials added in v0.4.0

func (f *WebRTCTurnFacade) IssueCredentials(ctx context.Context, roomID, peerID string, ttlSeconds int32) (*webrtcv1.IssueCredentialsResponse, error)

IssueCredentials mints short-lived TURN credentials for a peer in a room. ttlSeconds of zero lets the server choose its default. tenant defaults to the Metadata.

type WriteBuilder added in v0.4.0

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

WriteBuilder is the typed neutral-IR write builder. It emits `{"ir": {"op": "write", ...}}` (a `LogicalWrite`). Defaults to insert (conflict = `Error`); call Merge / IgnoreConflicts / UpdateOnConflict for upsert semantics.

func WriteTo added in v0.4.0

func WriteTo(messageType string) *WriteBuilder

WriteTo starts a typed neutral-IR write (insert/upsert) for messageType.

func (*WriteBuilder) Execute added in v0.4.0

func (*WriteBuilder) ExecuteOn added in v0.4.0

func (w *WriteBuilder) ExecuteOn(ctx context.Context, dispatch IRDispatcher, backend string, opts ...grpc.CallOption) (*entityv1.GenericDispatchResponse, error)

func (*WriteBuilder) IgnoreConflicts added in v0.4.0

func (w *WriteBuilder) IgnoreConflicts() *WriteBuilder

IgnoreConflicts skips conflicting rows (`ConflictStrategy::Ignore`).

func (*WriteBuilder) Merge added in v0.4.0

func (w *WriteBuilder) Merge() *WriteBuilder

Merge is a full upsert — replace every column on conflict (`ConflictStrategy::Replace`).

func (*WriteBuilder) Record added in v0.4.0

func (w *WriteBuilder) Record(row map[string]any) *WriteBuilder

func (*WriteBuilder) Records added in v0.4.0

func (w *WriteBuilder) Records(rows ...map[string]any) *WriteBuilder

func (*WriteBuilder) Returning added in v0.4.0

func (w *WriteBuilder) Returning(fields ...string) *WriteBuilder

func (*WriteBuilder) ToEnvelope added in v0.4.0

func (w *WriteBuilder) ToEnvelope() (any, error)

func (*WriteBuilder) ToRequest added in v0.4.0

func (w *WriteBuilder) ToRequest(backend string) (*entityv1.GenericDispatchRequest, error)

func (*WriteBuilder) ToSpecJSON added in v0.4.0

func (w *WriteBuilder) ToSpecJSON() (string, error)

func (*WriteBuilder) UpdateOnConflict added in v0.4.0

func (w *WriteBuilder) UpdateOnConflict(fields []string, conflictOn ...string) *WriteBuilder

UpdateOnConflict is a partial upsert — update only fields on conflict (`ConflictStrategy::Update`). conflictOn names an alternate unique key; omit to use the manifest PK.

type WriteReceipt added in v0.4.0

type WriteReceipt struct {
	SourceLsn         string   `json:"source_lsn"`
	OutboxSeq         uint64   `json:"outbox_seq"`
	ProjectionTaskIds []string `json:"projection_task_ids"`
	ManifestChecksum  string   `json:"manifest_checksum"`
	WrittenAtUnixMs   int64    `json:"written_at_unix_ms"`
}

WriteReceipt mirrors the Rust `WriteReceipt` struct (src/runtime/consistency.rs). The Rust struct serializes ALL five fields unconditionally (no skip_serializing_if), so none of the JSON tags carry `omitempty`.

func ParseWriteReceipt added in v0.4.0

func ParseWriteReceipt(b []byte) (WriteReceipt, error)

ParseWriteReceipt decodes write_receipt_json bytes into a WriteReceipt. Empty input yields a zero receipt and a nil error (no write produced a receipt).

func ReceiptFromMutation added in v0.4.0

func ReceiptFromMutation(m *entityv1.MutationResponse) (WriteReceipt, error)

ReceiptFromMutation captures the WriteReceipt from a MutationResponse body field (the primary capture path; the x-udb-write-receipt header is the forward/embedded fallback). An empty body field yields a zero receipt and a nil error.

func (WriteReceipt) IsEmpty added in v0.4.0

func (r WriteReceipt) IsEmpty() bool

IsEmpty reports whether the receipt carries no write information.

Jump to

Keyboard shortcuts

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