# RIO CDK Constructs

This package contains CDK2 constructs for RIO teams.

> NPM: `@rio-cloud/cdk-v2-constructs`

## Bootstrapping of CDK project

```
$ npx cdk init --language typescript
```

## Installation

```
$ npm install --save @rio-cloud/cdk-v2-constructs
```

## See also

 * [How to contribute](./docs/contribution.md)
 * [Changelog](./docs/changelog.md)
 * [brief API description](./docs/API.md)
 * [Agent documentation](./docs/AGENTS_DOCUMENTATION.md)

## Internal documentation for library devs
[Documentation](./docs/developers-readme.md)

## Constructs overview (Under construction...)

### Fargate trace sampling

`RioFargateService` and `RioFargateServiceBlueGreenAlpha` configure Datadog
trace sampling through `datadogOptions.traceSampling`. The default is
`TraceSamplingMode.DEFAULT`: it sets `DD_APM_TARGET_TPS=5` and
`DD_APM_ERROR_TPS=10` on the Datadog Agent sidecar. This replaces the
historical application-level fixed rate of `DD_TRACE_SAMPLE_RATE=1.0`.
These settings apply per Agent; each Fargate task has its own Agent sidecar.

The head-sampling target is averaged over time, so traffic spikes can exceed
it. Error sampling captures additional local error trace chunks missed by
head sampling; it does not cap the total number of error traces ingested.

RIO uses target-per-second sampling as its default because it is appropriate
for both low- and high-traffic services: low-traffic services can retain all
their traces, while high-traffic services are sampled toward the target.

For Kotlin/Spring Boot services on Fargate it is recommended to use the
Datadog Java tracer, `dd-java-agent`, as a JVM agent. It automatically
instruments supported Spring Boot libraries and enables the Agent-side
target-per-second sampling configured by this construct.

Do not use the OpenTelemetry Java agent. The default tracing behavior for RIO
Fargate Services—`DD_APM_TARGET_TPS`—controls Datadog SDKs, not OTLP
ingestion. OpenTelemetry users must configure sampling in their own SDK and
maintain that integration separately.

- `DEFAULT` (or no option) emits the RIO Agent head-sampling target of 5
  traces per second and an additional error-sampling budget of 10 error trace
  chunks per second, per Agent (and therefore per running service instance).
  This target-per-second approach is a practical default for both low- and
  high-traffic services.
- `DATADOG_DEFAULT` emits no sampling variables, leaving Datadog's sampling
  defaults in control.
- `FIXED_RATE` requires `fixedRate` (from 0 through 1) and emits a global
  `DD_TRACE_SAMPLING_RULES` rule on the application container.
  Datadog tracers additionally enforce their built-in 100-traces-per-second
  rate limit when sampling rules are configured. This construct deliberately
  does not expose or override that safeguard, so `fixedRate` is subject to
  that per-instance upper bound on high-traffic services.
- `TARGET_PER_SECOND` requires `targetTracesPerSecond` and emits
  `DD_APM_TARGET_TPS` on the Agent sidecar. This is an average head-sampling
  target per Agent. Optional `errorTracesPerSecond` configures
  `DD_APM_ERROR_TPS`, the budget for additional local error trace chunks per
  second missed by head sampling.

For example:

```ts
datadogOptions: {
  traceSampling: {
    mode: TraceSamplingMode.TARGET_PER_SECOND,
    targetTracesPerSecond: 20,
    errorTracesPerSecond: 10,
  },
},
```

`DD_TRACE_SAMPLING_RULES`, `DD_TRACE_SAMPLE_RATE`, `DD_APM_TARGET_TPS`, or
`DD_APM_ERROR_TPS` SHOULD not be set directly in
`containerDefinitionOption.environment`. Direct configuration remains possible
for backwards compatibility and produces a synthesis warning only.
Users who choose this approach are responsible for its configuration,
compatibility, and ongoing maintenance.

### Watchful

Watchful constructs help generate some default monitors based on the resources defined in your stack. E.g. - If your stack contains a lambda function, and you configure watchful construct, then it will create out of box metric monitors for Throttling, Lambda error and Log error monitors. The ever-growing list of resources that watchful creates monitors for as of today are:

- Application load balancer
- Cloudfront
- Documentdb
- Dynamodb
- Fargate
- Lambda
- RDS

Simply add the following to your CDK stack to get started.
```
  import * as rio from '@rio-cloud/cdk-v2-constructs';
    ...
    const dw = new rio.watchfulv2.Watchful(this, 'Watchful', {
      serviceName,
    });
    dw.watchScope(this); // Generates alarms for all supported resources
    ...
```

There are options to override some defaults too. Please be aware that the library is very opinionated and is written with the most general use cases in mind. It is necessary to keep the use of the library simple enough, which means that there is only limited flexibility regarding the configuration options. Having said that, feel free to reach out to team CLAID over slack #rio-platform-support in case of feature requests.

The broad classification of the monitors created by watchful are
- Log error monitors
- Metrics Query monitors: Basically everything other than log error monitors

For Metrics query monitors, you can configure the priority (defaults as 3). For log error monitors, you can configure priority, renotification interval and can configure if the auto close of the monitor is disabled.
```
    ...
    const dw = new Watchful(stack, 'Watchful2', { 
      logErrorMonitorConfig: {
        disableAutoClose: true, 
        renotifyInterval: 150,
        priority: 4,
      },
      queryErrorMonitorConfig: {
        priority: 4
      }
    });
    dw.watchScope(stack);
```

There is an `overrideAlarmThreshold` method which can be used to override the default watchful thresholds. Please make sure to use the method before the `watchscope` function.
E.g. -
```
...
const dw = new Watchful(stack, 'Watchful', {});
dw.overrideAlarmThreshold({
  monitoredResourceScope: lambdaA,
  monitorType: MonitorType.ERRORS,
  threshold: 5,
});
dw.watchScope(stack);
```

### ClassifyPipelineType

The pipelines can be tagged with key 'pipeline_type' to the following values:

* deploy: To tag the production pipeline releasing the application
* branch: The branch pipeline. Mostly used to test contributions / renovate updates
* vulnerability: The vulnerability pipeline

The construct `ClassifyPipelineType` can be used to tag the pipeline accordingly. This tag is also picked up by the Datadog pipeline metric used to monitor the pipelines. It is added as a tag to the metric. This gives you more flexibility with managing the monitors also. E.g. some teams don't want to get alerted for branch pipelines. You can then leverage this metric tag to filter the pipelines.

Example:

```typescript
const pipeline = new pipelines.CodePipeline(this, 'Pipeline', {
      ...
    });
rio.ClassifyPipelineType.apply(pipeline, rio.RioPipelineType.DEPLOY);
```
