# V2 Unified Stats API

The V2 Unified Stats API provides comprehensive time-series and breakdown statistics across all gateways and services in the Flashback Platform. It replaces older statistics endpoints with a consistent, predictable, and fully-typed interface.

## Overview

The V2 Stats API unifies reporting across Storage, AI, Private Chat, Policies, and Credits. It uses standardized parameter names, shared data structures, and consistent metric definitions.

### Key Characteristics

* **Unified Parameter Structure**: All endpoints share the same core filtering (`scope`, `id`, `window`, `timeBucketSize`).
* **Standardized Response Shapes**: Every time-series endpoint returns a `TimeSeriesResponse`, and every breakdown returns a `BreakdownResponse`.
* **Consistent Metric Naming**:
  * `requests` instead of `apiCalls` or `count`.
  * `tokensIn`/`tokensOut` for base model usage.
  * `policyTokensIn`/`policyTokensOut` for policy-evaluation overhead.
  * `latencyMs` for weighted-average response times.
* **Flexible Granularity**: Time-series data is automatically bucketed based on the requested `window` (e.g., a 24-hour window defaults to 10-minute buckets).
* **Rich Breakdowns**: Slice data by various dimensions like workspaces, repositories, models, or users.

## Scope and Time Window

All V2 Stats API endpoints require `scope` and `window` parameters. `id` is required for non-org scopes:

* `scope`: The organizational level to query (`org`, `workspace`, `repo`).
* `id`: The unique identifier (UUID) for the chosen scope (`workspace` or `repo`).
* `window`: The time range looking backwards from now (e.g., `24h`, `7d`, `30d`, `90d`, `180d`, `365d`).
* Optional resource filters can be provided per domain (`apiKeyId`, `bucketId`, `model`, `userId`, `ruleId`, `aiLlmId`).

## V2 Unified Stats API Calls

### Storage Gateway Stats

Metrics related to object storage operations (uploads, downloads, requests).

| Method                                                                          | API Reference                                                                                                                                                                              | Description                                                                                |
| ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| <mark style="color:green;">`GET`</mark> `/v2/stats/storage`                     | [**get\_\_v2\_stats\_storage**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_storage)                                           | Time-series for storage gateway metrics.                                                   |
| <mark style="color:green;">`GET`</mark> `/v2/stats/storage/breakdown/{by}`      | [**get\_\_v2\_stats\_storage\_breakdown\_by**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_storage_breakdown_by)               | Storage breakdown by dimension (workspaces, repos, buckets, nodes), with resource filters. |
| <mark style="color:green;">`GET`</mark> `/v2/stats/storage/breakdown/providers` | [**get\_\_v2\_stats\_storage\_breakdown\_providers**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_storage_breakdown_providers) | Detailed storage breakdown including protocol and endpoint.                                |

### AI Gateway Stats

Metrics for AI proxy operations (excluding Private Chat usage).

| Method                                                                | API Reference                                                                                                                                                      | Description                                                                                         |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| <mark style="color:green;">`GET`</mark> `/v2/stats/ai`                | [**get\_\_v2\_stats\_ai**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_ai)                             | Time-series for AI gateway metrics.                                                                 |
| <mark style="color:green;">`GET`</mark> `/v2/stats/ai/breakdown/{by}` | [**get\_\_v2\_stats\_ai\_breakdown\_by**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_ai_breakdown_by) | AI breakdown by dimension (workspaces, repos, models, providers, aiConfigs), with resource filters. |

### Private Chat Stats

Metrics specifically for the Flashback Private Chat application.

| Method                                                                            | API Reference                                                                                                                                                                                   | Description                               |
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| <mark style="color:green;">`GET`</mark> `/v2/stats/private-chat`                  | [**get\_\_v2\_stats\_private\_chat**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_private_chat)                                     | Time-series for private-chat metrics.     |
| <mark style="color:green;">`GET`</mark> `/v2/stats/private-chat/breakdown/models` | [**get\_\_v2\_stats\_private\_chat\_breakdown\_models**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_private_chat_breakdown_models) | Private chat usage breakdown by AI model. |
| <mark style="color:green;">`GET`</mark> `/v2/stats/private-chat/breakdown/users`  | [**get\_\_v2\_stats\_private\_chat\_breakdown\_users**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_private_chat_breakdown_users)   | Private chat usage breakdown by user.     |

### Policies Stats

Metrics for AI Governance and Policy enforcement (DLP, PII redaction, etc.).

| Method                                                                      | API Reference                                                                                                                                                                  | Description                                                  |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------ |
| <mark style="color:green;">`GET`</mark> `/v2/stats/policies`                | [**get\_\_v2\_stats\_policies**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_policies)                             | Time-series of policy violations, alerts, and blocks.        |
| <mark style="color:green;">`GET`</mark> `/v2/stats/policies/tokens`         | [**get\_\_v2\_stats\_policies\_tokens**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_policies_tokens)              | Time-series of token overhead consumed by policy evaluation. |
| <mark style="color:green;">`GET`</mark> `/v2/stats/policies/breakdown/{by}` | [**get\_\_v2\_stats\_policies\_breakdown\_by**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_policies_breakdown_by) | Policy breakdown by rules or users.                          |

### Credits Stats

Financial and usage metrics regarding credit consumption and grants.

| Method                                                                     | API Reference                                                                                                                                                                | Description                                |
| -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |
| <mark style="color:green;">`GET`</mark> `/v2/stats/credits`                | [**get\_\_v2\_stats\_credits**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_credits)                             | Credit consumption/grant time-series.      |
| <mark style="color:green;">`GET`</mark> `/v2/stats/credits/breakdown/{by}` | [**get\_\_v2\_stats\_credits\_breakdown\_by**](https://docs.flashback.tech/support-reference/platform-api-reference/v2-unified-stats-api/get__v2_stats_credits_breakdown_by) | Credit consumption breakdown by dimension. |

## Common Use Cases

### 1. Fetching Organization-Wide Storage Usage Over 30 Days

```typescript
const response = await client.getStorageGatewayStats({
  scope: 'org',
  id: 'org-uuid-123',
  window: '30d'
});

console.log(`Total Requests: ${response.summary.total}`);
console.log(`Average Daily Requests: ${response.summary.avg}`);

response.series.forEach(point => {
  const date = new Date(point.ts * 1000).toLocaleDateString();
  console.log(`${date}: ${point.dwlBytes} bytes downloaded`);
});
```

### 2. Identifying the Most Expensive AI Models

```typescript
const response = await client.getAiGatewayBreakdown('models', {
  scope: 'workspace',
  id: 'workspace-uuid-456',
  window: '7d'
});

response.entities.forEach(model => {
  console.log(`Model: ${model.entityId}`);
  console.log(`Requests: ${model.totals.requests}`);
  console.log(`Tokens (In/Out): ${model.totals.tokensIn} / ${model.totals.tokensOut}`);
});
```

### 3. Monitoring Policy Violations

```typescript
const response = await client.getPolicyStats({
  scope: 'repo',
  id: 'repo-uuid-789',
  window: '24h'
});

console.log(`Total Violations: ${response.summary.total}`);
// You can also inspect the time-series points in response.series
// to see exactly when violations spiked.
```

## Shared Response Structures

The V2 API relies heavily on two primary response envelopes.

### Time-Series Response (`TimeSeriesResponse<T>`)

Returned by all root-level stats endpoints (e.g., `/v2/stats/ai`).

```json
{
  "success": true,
  "meta": {
    "start": 1704067200,
    "end": 1704153600,
    "scope": "org",
    "window": "24h",
    "timeBucketSize": "1h"
  },
  "summary": {
    "total": 1500,
    "avg": 50,
    "stdDev": 10,
    "min": 0,
    "max": 100,
    "p10": 10,
    "p50": 50,
    "p90": 90
  },
  "series": [
    {
      "ts": 1704067200,
      "requests": 45,
      // ... domain specific metrics
    }
  ]
}
```

### Breakdown Response (`BreakdownResponse<T>`)

Returned by all `/breakdown/{by}` endpoints. Can optionally include time-series data for each entity if `includeSeries=true` is passed.

```json
{
  "success": true,
  "meta": {
    "start": 1704067200,
    "end": 1704153600,
    "scope": "org",
    "breakdownBy": "models",
    "includesSeries": false,
    "limit": 50,
    "offset": 0,
    "totalEntities": 5
  },
  "summary": {
    "total": 5
  },
  "entities": [
    {
      "entityId": "gpt-4",
      "entityName": "GPT-4", // Optional
      "totals": {
        "requests": 1200,
        // ... domain specific metrics
      }
    }
  ]
}
```

## Error Handling

### 400 Bad Request

**Cause:** Missing required parameters (like `scope`, `id`, or `window`), or invalid parameter values.

```typescript
try {
  await client.getStorageGatewayStats({
    scope: 'invalid_scope' as any,
    id: 'org-id',
    window: '24h'
  });
} catch (error) {
  if (error.status === 400) {
    console.error("Invalid parameters provided");
  }
}
```

### 500 Internal Server Error

**Cause:** Server-side aggregation error or database timeout.

## Best Practices

1. **Use the Right Granularity**: Don't query a `365d` window if you only need yesterday's data. Smaller windows are faster to aggregate.
2. **Leverage Breakdowns for Dashboards**: Breakdown endpoints with `includeSeries=true` are highly optimized for building UI dashboards (like charts with multiple lines representing different models/workspaces).
3. **Filter by Resource**: If you only care about one specific model, API key, bucket, rule, user, or AI config, use resource filters such as `model=gpt-4`, `apiKeyId=...`, `bucketId=...`, `ruleId=...`, `userId=...`, or `aiLlmId=...`.
4. **Use the Client Library**: The `@flashbacktech/flashbackclient` library handles all the complex generic typings for these responses automatically.
