// Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

syntax = "proto3";

package banyandb.fodc.v1;

import "banyandb/common/v1/common.proto";
import "banyandb/database/v1/database.proto";
import "banyandb/database/v1/rpc.proto";
import "google/protobuf/timestamp.proto";

option go_package = "github.com/apache/skywalking-banyandb/api/proto/banyandb/fodc/v1";

service FODCService {
  // Bi-directional stream for agent registration and heartbeat
  rpc RegisterAgent(stream RegisterAgentRequest) returns (stream RegisterAgentResponse);

  // Bi-directional stream for metrics
  // Agent sends StreamMetricsRequest (metrics data), Proxy sends StreamMetricsResponse (metrics requests)
  rpc StreamMetrics(stream StreamMetricsRequest) returns (stream StreamMetricsResponse);

  // Bi-directional stream for cluster topology
  rpc StreamClusterTopology(stream StreamClusterTopologyRequest) returns (stream StreamClusterTopologyResponse);

  // Bi-directional stream for lifecycle data
  rpc StreamLifecycle(stream StreamLifecycleRequest) returns (stream StreamLifecycleResponse);

  // Bi-directional stream for crash diagnostics
  // Agent sends StreamCrashDiagnosticsRequest (panic collections), Proxy sends StreamCrashDiagnosticsResponse (requests)
  rpc StreamCrashDiagnostics(stream StreamCrashDiagnosticsRequest) returns (stream StreamCrashDiagnosticsResponse);

  // Bi-directional stream for memory-pressure pprof profiles.
  // Proxy drives via StreamPressureProfilesResponse (list metadata, or fetch one
  // profile's bytes); agent replies with StreamPressureProfilesRequest (metadata
  // records, or binary chunks).
  rpc StreamPressureProfiles(stream StreamPressureProfilesRequest) returns (stream StreamPressureProfilesResponse);

  // Bi-directional stream for the authoritative schema registry fingerprint.
  // The Proxy picks one schema-serving (liaison) agent by role and drives it via
  // StreamSchemaRegistryResponse (request_registry); that one agent reads the
  // authoritative registry from its local node and replies with
  // StreamSchemaRegistryRequest (the fingerprints). Only the selected agent is
  // ever asked, so the registry is read once per collection, not once per node.
  rpc StreamSchemaRegistry(stream StreamSchemaRegistryRequest) returns (stream StreamSchemaRegistryResponse);
}

message RegisterAgentRequest {
  string node_role = 1;
  map<string, string> labels = 2;
  string pod_name = 4;
  repeated string container_names = 5;
}

message RegisterAgentResponse {
  bool success = 1;
  string message = 2;
  int64 heartbeat_interval_seconds = 3;
  string agent_id = 4;
}

message StreamMetricsRequest {
  repeated Metric metrics = 1;
  google.protobuf.Timestamp timestamp = 2;
}

// MetricType represents the Prometheus metric type.
enum MetricType {
  METRIC_TYPE_UNSPECIFIED = 0;
  METRIC_TYPE_GAUGE = 1;
  METRIC_TYPE_COUNTER = 2;
  METRIC_TYPE_HISTOGRAM = 3;
  METRIC_TYPE_SUMMARY = 4;
  METRIC_TYPE_UNTYPED = 5;
}

message Metric {
  string name = 1;
  map<string, string> labels = 2;
  double value = 3;
  string description = 4;
  google.protobuf.Timestamp timestamp = 5;
  MetricType type = 6;
}

message StreamMetricsResponse {
  google.protobuf.Timestamp start_time = 1; // Optional start time for time window
  google.protobuf.Timestamp end_time = 2; // Optional end time for time window
}

message Call {
  string id = 1;
  string target = 2;
  string source = 3;
}

message Topology {
  repeated banyandb.database.v1.Node nodes = 1;
  repeated Call calls = 2;
}

message StreamClusterTopologyRequest {
  google.protobuf.Timestamp timestamp = 1;
  Topology topology = 2;
}

message StreamClusterTopologyResponse {
  // Request topology from agent
  bool request_topology = 1;
}

message StreamLifecycleRequest {
  google.protobuf.Timestamp timestamp = 1;
  string pod_name = 2;
  LifecycleData lifecycle_data = 3;
}

message StreamLifecycleResponse {
  bool request_lifecycle = 1;
}

// StreamSchemaRegistryRequest is one message of the selected agent's streamed
// reply to a request_registry command. A group's objects are split across
// messages so no single message carries a whole (potentially large) group; the
// proxy merges chunks that share a group name. The agent ends the round with a
// final message that has done set, which is how the proxy knows to stop waiting.
// A group whose own read failed rides on SchemaRegistryGroup.error; a fatal
// whole-read failure (e.g. the local registry endpoint was unreachable) is a
// single group chunk with an empty group name carrying the error.
message StreamSchemaRegistryRequest {
  // group carries a chunk of one group's registry fingerprints; unset on the
  // final message. Chunks that share a group name are merged by the proxy.
  SchemaRegistryGroup group = 1;
  // done marks the last message of the round; no group messages follow it.
  bool done = 2;
}

message StreamSchemaRegistryResponse {
  // Proxy asks the selected agent to read and report the registry fingerprints.
  bool request_registry = 1;
}

// SchemaRegistryGroup carries one group's authoritative registry fingerprints.
// The agent computes the fingerprints so the wire carries only uint64 digests,
// never raw schema bodies; a group's objects may arrive across several chunks
// that share a group name, which the proxy merges.
message SchemaRegistryGroup {
  string group = 1;
  repeated SchemaObjectFingerprint objects = 2;
  // error is set when this group's registry read failed; its objects are then
  // omitted and the group degrades to UNKNOWN with this reason attached. As a
  // special case, an empty group name with error set is the agent's fatal
  // whole-read failure, which the proxy surfaces across every group.
  string error = 3;
}

message SchemaObjectFingerprint {
  // kind is schema.Kind.String(), matching ObjectConsistency.kind.
  string kind = 1;
  string name = 2;
  uint64 fingerprint = 3;
}

message LifecycleData {
  repeated LifecycleReport reports = 1;
  repeated GroupLifecycleInfo groups = 2;
}

message GroupLifecycleInfo {
  string name = 1;
  string catalog = 2;
  banyandb.common.v1.ResourceOpts resource_opts = 3;
  repeated banyandb.database.v1.DataInfo data_info = 4;
  // errors lists every failure observed while collecting data_info for this
  // group: top-level CollectDataInfo failures (GetGroup, missing collector,
  // dial failure -- prefixed "top-level: ") and per-node broadcast failures
  // (prefixed "future error: ", "node error: ", "broadcast failed: ").
  // Combined with len(data_info), consumers can tell the following four
  // states apart:
  //   - data_info empty && errors empty       -> no nodes reported (group inactive)
  //   - data_info empty && errors non-empty   -> total failure
  //   - data_info non-empty && errors empty   -> full success
  //   - data_info non-empty && errors non-empty -> partial failure
  repeated string errors = 5;
  // schema_consistency is the verdict on whether this group's schema agrees
  // across the registry, every node's cache, and every node's runtime. Each
  // node's fingerprints (data and liaison) live in schema_consistency.objects.
  SchemaConsistency schema_consistency = 6;
}

// SchemaConsistency is the single, self-contained schema layer: it holds the
// verdict plus every object's fingerprints across all three layers -- registry
// truth, and each node's cache and runtime -- so DataInfo/LiaisonInfo carry no
// schema of their own.
message SchemaConsistency {
  ConsistencyStatus status = 1;
  // objects lists every schema object in the group exactly once, pairing its
  // registry-truth fingerprint with each node's cache/runtime fingerprints.
  repeated ObjectConsistency objects = 2;
  repeated SchemaIssue issues = 3;
}

// ObjectConsistency is one schema object's fingerprints across all layers: the
// registry truth plus every node that reported it.
message ObjectConsistency {
  // kind is schema.Kind.String().
  string kind = 1;
  string name = 2;
  // registry_fingerprint is the registry truth; zero when the object exists
  // only on nodes (an orphan) and not in the registry.
  uint64 registry_fingerprint = 3;
  repeated NodeFingerprint node_fingerprints = 4;
}

// NodeFingerprint is one node's cache/runtime fingerprints for a single object.
// Only the node id is carried; full node info lives in DataInfo/LiaisonInfo.
message NodeFingerprint {
  string node = 1;
  uint64 cache_fingerprint = 2;
  uint64 runtime_fingerprint = 3;
}

// SchemaIssue is one object-on-one-node disagreement. Fingerprint values are not
// repeated here; look them up in SchemaConsistency.objects by kind+name (the
// registry truth and that node's cache/runtime).
message SchemaIssue {
  // kind is schema.Kind.String().
  string kind = 1;
  string name = 2;
  // node is the node id the disagreement was observed on.
  string node = 3;
  SchemaIssueType type = 4;
}

// SchemaIssueType names which layer boundary the disagreement sits on.
enum SchemaIssueType {
  SCHEMA_ISSUE_TYPE_UNSPECIFIED = 0;
  // Registry has it, the node's cache does not. A frequent root cause is the
  // node silently rejecting the schema; grep the node log for "is ignored".
  SCHEMA_ISSUE_TYPE_MISSING_IN_CACHE = 1;
  // The node holds it but the registry does not.
  SCHEMA_ISSUE_TYPE_ORPHAN = 2;
  // Registry and cache disagree: the watch is behind.
  SCHEMA_ISSUE_TYPE_CACHE_STALE = 3;
  // Cache and runtime disagree: the derived index was never reapplied.
  SCHEMA_ISSUE_TYPE_RUNTIME_NOT_APPLIED = 4;
}

// ConsistencyStatus is the group-level rollup.
enum ConsistencyStatus {
  CONSISTENCY_STATUS_UNSPECIFIED = 0;
  CONSISTENCY_STATUS_CONSISTENT = 1;
  CONSISTENCY_STATUS_INCONSISTENT = 2;
  // Collection was incomplete, or a disagreement has not yet persisted long
  // enough to be reported.
  CONSISTENCY_STATUS_UNKNOWN = 3;
}

message LifecycleReport {
  string filename = 1;
  string report_json = 2;
}

message CrashBreadcrumb {
  google.protobuf.Timestamp time = 1;
  string stage = 2;
  string component = 3;
  map<string, string> fields = 4;
}

message CrashPanicRecord {
  google.protobuf.Timestamp occurred_at = 1;
  string component = 2;
  string panic_value = 3;
  bool recovered = 4;
  string goroutine_stack = 5;
  repeated CrashBreadcrumb breadcrumbs = 6;
  map<string, string> process_metadata = 7;
}

message StreamCrashDiagnosticsRequest {
  google.protobuf.Timestamp fetched_at = 1;
  string source_endpoint = 2;
  string artifact_dir = 3;
  CrashPanicRecord panic_record = 4;
  repeated string files = 5;
}

message StreamCrashDiagnosticsResponse {
  // Request crash diagnostics from agent
  bool request_diagnostics = 1;
}

// One pprof profile inside a capture event (metadata only, no bytes).
message PressureProfileInfo {
  string type = 1; // "heap" | "goroutine"
  string filename = 2; // base name, e.g. "heap.pprof"
  string filepath = 3; // absolute path on the agent's disk, e.g. /tmp/pressure-profiles/20260627T101112.000000000Z/heap.pprof
  string format = 4; // "pprof" (gzip-compressed protobuf)
  int64 size_bytes = 5; // on-disk size
}

// Metadata for one capture event (no bytes). pod/role are NOT carried here:
// the proxy enriches them from the registered AgentIdentity, same as crash.
message PressureProfileRecord {
  string profile_id = 1; // = event directory name (UTC ns timestamp)
  google.protobuf.Timestamp captured_at = 2;
  string source_endpoint = 3; // pprof endpoint pulled, e.g. http://localhost:6060
  uint64 rss_bytes = 4; // RSS at trigger (process_resident_memory_bytes); top-N sort key
  uint64 cgroup_limit_bytes = 5; // cgroup memory.max
  uint32 trigger_percent = 6; // configured threshold percent (e.g. 75)
  uint64 threshold_bytes = 7; // cgroup_limit_bytes * trigger_percent / 100
  repeated PressureProfileInfo profiles = 8;
}

// One slice of a profile's bytes during download.
message PressureProfileChunk {
  string request_id = 1; // echoes FetchPressureProfile.request_id -- correlates this chunk stream to its fetch
  string profile_id = 2;
  string type = 3; // "heap" | "goroutine"
  bytes data = 4; // a bounded slice (e.g. <= 1MB)
  bool last = 5; // true on the final chunk
  string error = 6; // non-empty if the file cannot be served (e.g. evicted / not found)
}

// Agent -> Proxy: either a metadata record (answer to list_profiles) or a byte
// chunk (answer to fetch_profile).
message StreamPressureProfilesRequest {
  oneof payload {
    PressureProfileRecord record = 1;
    ListComplete list_complete = 2;
    PressureProfileChunk chunk = 3;
  }
}

// Agent -> Proxy: sent once after all records for a ListProfiles request have been
// streamed (including the zero-record case), so the proxy knows the agent is done
// without waiting out a fixed window.
message ListComplete {
  string request_id = 1; // echoes ListProfiles.request_id
}

message FetchPressureProfile {
  string request_id = 1; // proxy-generated per fetch; echoed back in every PressureProfileChunk to correlate
  string profile_id = 2;
  string type = 3; // "heap" | "goroutine"
  string filepath = 4; // the absolute path the agent reported in PressureProfileInfo.filepath; agent opens it AFTER validating it is within --pressure-profiler-dir
}

// Proxy -> Agent: either "stream all your metadata" or "stream one profile's bytes".
message StreamPressureProfilesResponse {
  oneof command {
    ListProfiles list_profiles = 1;
    FetchPressureProfile fetch_profile = 2;
  }
}

// Proxy -> Agent: stream all capture-event metadata for this request id.
message ListProfiles {
  string request_id = 1; // proxy-generated per list; echoed back in ListComplete to correlate
}

// GroupLifecycleService provides group lifecycle information from liaison nodes.
// Registered on the internal gRPC server so FODC agent can access it.
service GroupLifecycleService {
  // InspectAll lists all groups and returns their full lifecycle info in one call.
  rpc InspectAll(InspectAllRequest) returns (InspectAllResponse);
}

message InspectAllRequest {}

message InspectAllResponse {
  repeated GroupLifecycleInfo groups = 1;
}
