// 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.common.v1;

import "google/protobuf/duration.proto";
import "google/protobuf/struct.proto";
import "google/protobuf/timestamp.proto";
import "validate/validate.proto";

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

enum Catalog {
  CATALOG_UNSPECIFIED = 0;
  CATALOG_STREAM = 1;
  CATALOG_MEASURE = 2;
  CATALOG_PROPERTY = 3;
  CATALOG_TRACE = 4;
}

// Metadata is for multi-tenant, multi-model use
message Metadata {
  // group contains a set of options, like retention policy, max
  string group = 1;
  // name of the entity
  string name = 2;
  // id is the unique identifier of the entity
  // if id is not set, the system will generate a unique id
  uint32 id = 3;
  // readonly. create_revision is the revision of last creation on this key.
  int64 create_revision = 4;
  // readonly. mod_revision is the revision of last modification on this key.
  int64 mod_revision = 5;
}

// IntervalRule is a structured duration
message IntervalRule {
  enum Unit {
    UNIT_UNSPECIFIED = 0;
    UNIT_HOUR = 1;
    UNIT_DAY = 2;
  }
  // unit can only be UNIT_HOUR or UNIT_DAY
  Unit unit = 1 [(validate.rules).enum.defined_only = true];
  uint32 num = 2 [(validate.rules).uint32.gt = 0];
}

message LifecycleStage {
  // The stage name (e.g., "warm", "cold").
  // This should be a non-empty string.
  string name = 1 [(validate.rules).string.min_len = 1];

  // Number of shards allocated for this stage.
  // Must be greater than zero.
  uint32 shard_num = 2 [(validate.rules).uint32.gt = 0];

  // Defines the interval for data segmentation in this stage.
  // This is a required field and uses the IntervalRule structure.
  IntervalRule segment_interval = 3 [(validate.rules).message.required = true];

  // Specifies the time-to-live for data in this stage before moving to the next.
  // This is also a required field using the IntervalRule structure.
  IntervalRule ttl = 4 [(validate.rules).message.required = true];

  // Node selector specifying target nodes for this stage.
  // Optional; if provided, it must be a non-empty string.
  string node_selector = 5 [(validate.rules).string.min_len = 1];

  // Indicates whether segments that are no longer live should be closed.
  bool close = 6;

  // replicas is the number of replicas for this stage.
  // This is an optional field and defaults to 0.
  // A value of 0 means no replicas, while a value of 1 means one primary shard and one replica.
  // Higher values indicate more replicas.
  uint32 replicas = 7;
}

message ResourceOpts {
  // shard_num is the number of shards
  uint32 shard_num = 1 [(validate.rules).uint32.gt = 0];
  // segment_interval indicates the length of a segment
  IntervalRule segment_interval = 2;
  // ttl indicates time to live, how long the data will be cached
  IntervalRule ttl = 3;
  // stages defines the ordered lifecycle stages. Data progresses through these stages sequentially.
  repeated LifecycleStage stages = 4;
  // default_stages is the name of the default stage
  repeated string default_stages = 5;
  // replicas is the number of replicas. This is used to ensure high availability and fault tolerance.
  // This is an optional field and defaults to 0.
  // A value of 0 means no replicas, while a value of 1 means one primary shard and one replica.
  // Higher values indicate more replicas.
  uint32 replicas = 6;
}

// PipelineEvent identifies a pipeline-wide event that can be independently enabled.
enum PipelineEvent {
  PIPELINE_EVENT_UNSPECIFIED = 0;
  // In-merge filter during Hot-phase LSM compaction merges.
  PIPELINE_EVENT_MERGE = 1;
  // Tail-sampling gate at Hot-phase segment finalization.
  PIPELINE_EVENT_FINALIZE = 2;
}

// SamplerPlugin configures a user-supplied native Go plugin (.so) that owns a
// keep/drop verdict over a vectorized batch of traces.
message SamplerPlugin {
  // path is the plugin .so filename, resolved within the data node's trusted plugin directory.
  string path = 1 [(validate.rules).string.min_len = 1];
  // symbol is the constructor symbol the engine looks up; defaults to "NewSampler" if empty.
  string symbol = 2;
  // abi_version is the ABI version the plugin was built against.
  uint32 abi_version = 3 [(validate.rules).uint32 = {gte: 1}];
  // config is the plugin-defined configuration serialized to canonical JSON for the constructor.
  google.protobuf.Struct config = 4;
}

// Plugin is one link in a pipeline's processing chain.
message Plugin {
  // name is the operator-facing identity for this link.
  string name = 1 [(validate.rules).string.min_len = 1];
  // kind selects the plugin type; exactly one arm must be set.
  oneof kind {
    // sampler owns a keep/drop verdict over a vectorized batch of traces.
    SamplerPlugin sampler = 2;
  }
}

// StageRule binds the pipeline to one lifecycle stage and declares that stage's
// retention plugin chain.
message StageRule {
  // stage is the stage name from the Group's ResourceOpts.stages.
  string stage = 1 [(validate.rules).string.min_len = 1];
  // plugins is the ordered retention chain for this stage.
  repeated Plugin plugins = 2;
}

// TracePipelineConfig is the group-scoped, name-less in-merge retention configuration.
// Identity comes from the carrying Group; there is one config per group by construction.
message TracePipelineConfig {
  // enabled activates the pipeline.
  bool enabled = 1;
  // plugins is the ordered chain of plugins evaluated by enabled events.
  repeated Plugin plugins = 2;
  // merge_grace is the whole-selection maturity delay for destructive in-merge sampling.
  // Sampling is deferred when any selected part extends beyond now - merge_grace;
  // this is not a per-trace completeness guarantee.
  // Strictly positive if set; engine default 2h if unset.
  google.protobuf.Duration merge_grace = 3 [(validate.rules).duration = {
    gt: {seconds: 0}
  }];
  // finalize_grace is the per-segment settling window for the scheduled finalization pass.
  // Strictly positive if set; engine default 5m if unset.
  google.protobuf.Duration finalize_grace = 4 [(validate.rules).duration = {
    gt: {seconds: 0}
  }];
  // stages declares per-stage retention rules.
  repeated StageRule stages = 5;
  // schema_names lists explicit schema names to target within the Group.
  repeated string schema_names = 6 [(validate.rules).repeated.items.string.min_len = 1];
  // schema_name_regex is an RE2 pattern matched against schema names.
  string schema_name_regex = 7;
  // enabled_events lists the pipeline-wide events to run.
  repeated PipelineEvent enabled_events = 8 [(validate.rules).repeated.items.enum = {
    defined_only: true
    not_in: [0]
  }];
}

// Group is an internal object for Group management
message Group {
  // metadata define the group's identity
  common.v1.Metadata metadata = 1 [(validate.rules).message.required = true];
  // catalog denotes which type of data the group contains
  common.v1.Catalog catalog = 2;
  // resourceOpts indicates the structure of the underlying kv storage
  ResourceOpts resource_opts = 3;
  // updated_at indicates when resources of the group are updated
  google.protobuf.Timestamp updated_at = 4;
  // created_at is the first-appearance timestamp; survives updates unchanged.
  google.protobuf.Timestamp created_at = 5;
  // pipeline carries the optional group-scoped in-merge retention config.
  // Absent or non-CATALOG_TRACE group means no sampler.
  optional TracePipelineConfig pipeline = 6;
}
