Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"prepublishOnly": "npm run clean && npm run build",
"pretest": "npm run build",
"test": "vitest run",
"test:integration": "INFLUX_TEST_ENABLED=true vitest run tests/integration.test.ts",
"test:integration": "INFLUX_TEST_ENABLED=true vitest run integration",
"test:watch": "vitest",
"test:infra:up": "docker compose -f docker-compose.test.yml up -d --wait",
"test:infra:down": "docker compose -f docker-compose.test.yml down",
Expand Down
50 changes: 50 additions & 0 deletions tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Test suite

Run `npm run build` first — tests spawn the compiled `build/index.js`.

| Command | Runs |
| -------------------------- | ------------------------------------------------------------------ |
| `npm test` | Everything; live-instance tests self-skip |
| `npm run test:integration` | Every file matching `integration`, with `INFLUX_TEST_ENABLED=true` |

## Conventions

Three kinds of test live here, distinguished by how they are marked.

**Active** — asserts what the code does today and must keep doing. Green.

**`describe.skip("[P<n>] …")`** — acceptance criteria for a planned change that
has not landed. Skipped so CI stays green, but each one fails against current
code, so un-skipping is all that is needed to drive the work. Where an
acceptance test has a paired active test asserting the opposite, the pair is
deliberate: the active test goes red when the fix lands, which forces the stale
characterization to be deleted rather than left behind. Two acceptance tests are
no-regression guards that pass both before and after, and say so in a comment.

**`it.todo(…)`** — a test that cannot be written yet because the answer it would
assert against is unknown. Each names the question ID and what unblocks it.
These appear in every vitest run, so the open list stays visible in CI output.

## Coverage for the write-path error and packaging fixes

| Bug | Tests |
| ----------------------------------------------- | ------------------------------------------------------- |
| Write path drops the InfluxDB error body | `write-error-core.test.ts`, `write-error-cloud.test.ts` |
| Which endpoint each product type writes to | `write-routing.test.ts` |
| `zod` is a runtime dependency, declared as dev | `packaging.test.ts` |
| `ping()` version/build header passthrough | `base-connection-ping.test.ts` |
| `write_line_protocol` contract, error surfacing | `protocol-write.test.ts` |

None of these are version-gated — they're bugs in the current server,
independent of which InfluxDB release is on the other end.

## Live-instance gates

`INFLUX_TEST_ENABLED` covers any live instance; tests under it must pass on the
CI Core container.

```bash
npm run test:infra:up
source env.test.example && npm run test:integration
npm run test:infra:down
```
85 changes: 85 additions & 0 deletions tests/base-connection-ping.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/**
* `ping()` — version/build header parsing.
*
* The `x-influxdb-version` and `x-influxdb-build` response headers are fetched
* but never parsed, compared, or otherwise used. This pins the current
* passthrough behavior, independent of any specific InfluxDB version.
*/

import { describe, it, expect, vi, afterEach } from "vitest";
import { BaseConnectionService } from "../src/services/base-connection.service.js";
import { InfluxProductType } from "../src/helpers/enums/influx-product-types.enum.js";
import type { McpServerConfig } from "../src/config.js";

const TOKEN = "test-token-not-used";

function configFor(type: InfluxProductType): McpServerConfig {
return {
influx: {
url: "http://localhost:19999/",
token: TOKEN,
type,
cluster_id:
type === InfluxProductType.CloudDedicated
? "00000000-0000-0000-0000-000000000000"
: undefined,
},
server: { name: "influxdb-mcp-server", version: "test" },
tools: { profile: "operator" },
};
}

/** Stub `fetch` with a success response and return the recorded calls. */
function stubFetchOk(headers: Record<string, string> = {}) {
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
status: 200,
headers: { get: (name: string) => headers[name.toLowerCase()] ?? null },
json: async () => ({ status: "pass" }),
});
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}

afterEach(() => {
vi.unstubAllGlobals();
});

describe("ping – version reporting, current behavior", () => {
it("returns the x-influxdb-version header unparsed", async () => {
const fetchMock = stubFetchOk({
"x-influxdb-version": "3.11.0-0.rc.1",
"x-influxdb-build": "Enterprise",
});

const result = await new BaseConnectionService(
configFor(InfluxProductType.Enterprise),
).ping();

expect(fetchMock).toHaveBeenCalled();
expect(result).toEqual({
ok: true,
version: "3.11.0-0.rc.1",
build: "Enterprise",
});
});

it('reports build "Other" when only a version header is present', async () => {
stubFetchOk({ "x-influxdb-version": "3.11.0" });

const result = await new BaseConnectionService(
configFor(InfluxProductType.Core),
).ping();

expect(result).toEqual({ ok: true, version: "3.11.0", build: "Other" });
});

it("reports no version at all when the header is absent", async () => {
stubFetchOk();
const result = await new BaseConnectionService(
configFor(InfluxProductType.Enterprise),
).ping();

expect(result).toEqual({ ok: true, version: undefined, build: undefined });
});
});
220 changes: 220 additions & 0 deletions tests/fixtures/write-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
/**
* Write-path error fixtures.
*
* Companion to `error-responses.ts`, which covers the query path. Shapes follow
* the same two families:
*
* Axios errors (Core/Enterprise/Clustered HTTP paths)
* error.response.status, error.response.statusText, error.response.data
* SDK HttpError (Cloud Dedicated/Serverless client paths)
* error.statusCode, error.statusMessage, error.body, error.json, error.message
*
* ── Provenance ──────────────────────────────────────────────────────────────
*
* RECORDED Body text observed against a real instance, or carried over from
* `error-responses.ts`.
* PROVISIONAL Body text is a placeholder pending live verification. Tests
* using these fixtures must assert on structure and on substrings
* the fixture itself defines (`DUPLICATED_TAG_KEY`), never on
* exact InfluxDB wording, so that correcting the fixture does not
* invalidate the assertion.
*
* The duplicate-tag-key response shape is resolved: verified 2026-07-28
* against both an Enterprise instance (`--upgrade-pacha-tree`, 3.11.0-0.rc.1)
* and a Core instance (3.11.0-nightly) — identical response on both. See
* `CORE_400_DUPLICATE_TAG_UNDER_PARTIAL_DATA` below.
*
* Whether a stopped node makes `write_lp` return 503 (instead of the current
* 400) remains unverified — needs a live instance with a node stopped
* mid-write. See `CORE_503_NODE_STOPPED` below.
*/

import type { AxiosErrorShape, SdkErrorShape } from "./error-responses.js";

export type { AxiosErrorShape, SdkErrorShape };

// ── The 3.11 duplicate-tag-key case ─────────────────────────────────────────
//
// 3.11 rejects a line carrying the same tag key twice up front, the same way
// duplicate field keys were already refused. The rejection needs to reach the
// model naming the duplicated tag, not just as a generic "bad request."

/**
* Line protocol that 3.11 rejects: the same tag key appears twice.
*
* A one-letter tag key (e.g. `m,t=a,t=a f=1i`) is not usable in an assertion —
* `not.toContain("t")` matches ordinary English in the generic error string
* and passes for the wrong reason — so the fixture uses a distinctive key
* instead. The condition under test is identical.
*/
export const DUPLICATE_TAG_LINE = "m,region=east,region=west f=1i";

/** The tag key duplicated in {@link DUPLICATE_TAG_LINE}. */
export const DUPLICATED_TAG_KEY = "region";

/**
* RECORDED — duplicated tag named only inside the partial-write
* `data[].error_message` structure.
*
* Verified 2026-07-28 against both Core (3.11.0-nightly) and Enterprise
* (3.11.0-0.rc.1, `--upgrade-pacha-tree`) — identical on both. `data.error`
* resolves to the generic "partial write of line protocol occurred" and the
* actionable detail is one level down, under `data[].error_message`. The MCP
* server sends `accept_partial=true` on the Core/Enterprise v3 path, so this
* is the shape a real rejection takes; resolving `data.error` alone is not
* sufficient. `original_line` is truncated by InfluxDB itself, mid tag value —
* not something our code does.
*/
export const CORE_400_DUPLICATE_TAG_UNDER_PARTIAL_DATA: AxiosErrorShape = {
response: {
status: 400,
statusText: "Bad Request",
data: {
error: "partial write of line protocol occurred",
data: [
{
error_message: `invalid line protocol - multiple instances of '${DUPLICATED_TAG_KEY}' tag found`,
line_number: 1,
original_line: "m,region=east,region",
},
],
},
},
message: "Request failed with status code 400",
};

// ── Status arms that currently discard the body ─────────────────────────────

/** RECORDED — Core rejects an unauthenticated request with this exact text. */
export const CORE_401_UNAUTHENTICATED: AxiosErrorShape = {
response: {
status: 401,
statusText: "Unauthorized",
data: { error: "the request was not authenticated" },
},
message: "Request failed with status code 401",
};

/** PROVISIONAL — permission-scoped token refused by the write endpoint. */
export const CORE_403_UNAUTHORIZED: AxiosErrorShape = {
response: {
status: 403,
statusText: "Forbidden",
data: { error: "the request was not authorized" },
},
message: "Request failed with status code 403",
};

/** PROVISIONAL — body exceeds the configured limit. Plain-text body. */
export const CORE_413_PAYLOAD_TOO_LARGE: AxiosErrorShape = {
response: {
status: 413,
statusText: "Payload Too Large",
data: "the request body was too large: limit is 10485760 bytes",
},
message: "Request failed with status code 413",
};

/** PROVISIONAL — line protocol parsed but semantically rejected. */
export const CORE_422_UNPROCESSABLE: AxiosErrorShape = {
response: {
status: 422,
statusText: "Unprocessable Entity",
data: {
error:
"invalid column type for column 'value', expected iox::column_type::field::float, got iox::column_type::field::string",
},
},
message: "Request failed with status code 422",
};

// ── 503 — the status neither handler has an arm for ─────────────────────────

/**
* PROVISIONAL — a stopped node.
*
* InfluxDB 3.11's release notes (Core/Enterprise-scoped) document a 400→503
* change for the legacy `/api/v2/write` endpoint that Core/Enterprise also
* expose for backward compatibility — not the `/api/v3/write_lp` endpoint
* this server actually calls for those product types. Whether
* `/api/v3/write_lp` behaves the same on a stopped node is unverified,
* answerable only on a live instance with a node stopped mid-write. The
* fixture exists so the handler's 503 arm is testable either way — the arm is
* also needed for the separate `Clustered` product (InfluxDB Clustered, the
* self-hosted sibling to Cloud Dedicated — not a multi-node Enterprise
* deployment), which does call `/api/v2/write` (see `write-routing.test.ts`).
* That's unrelated to these Core/Enterprise release notes: `Clustered` is a
* different product on its own release train.
*/
export const CORE_503_NODE_STOPPED: AxiosErrorShape = {
response: {
status: 503,
statusText: "Service Unavailable",
data: { error: "node is stopped and not accepting writes" },
},
message: "Request failed with status code 503",
};

// ── Object-body fallback ────────────────────────────────────────────────────

/**
* RECORDED shape, unhandled status.
*
* Any status with no arm falls through to a fallback that interpolates
* `error.response.data` directly. When the body is parsed JSON — the normal
* case — the model receives `[object Object]`.
*/
export const CORE_500_OBJECT_BODY: AxiosErrorShape = {
response: {
status: 500,
statusText: "Internal Server Error",
data: { error: "internal error while persisting write" },
},
message: "Request failed with status code 500",
};

/** RECORDED shape — plain-text body on an unhandled status, which does survive. */
export const CORE_500_STRING_BODY: AxiosErrorShape = {
response: {
status: 500,
statusText: "Internal Server Error",
data: "internal error while persisting write",
},
message: "Request failed with status code 500",
};

// ── Cloud SDK (HttpError) write failures ────────────────────────────────────
//
// `@influxdata/influxdb3-client` throws `HttpError`, which carries `statusCode`
// rather than `response.status`. Every status branch in the write handler tests
// `error.response?.status` and therefore misses on these entirely.

/** PROVISIONAL — Cloud rejection of {@link DUPLICATE_TAG_LINE}. */
export const CLOUD_SDK_400_DUPLICATE_TAG: SdkErrorShape = {
statusCode: 400,
statusMessage: "Bad Request",
body: `{"code":"invalid","message":"invalid line protocol: duplicate tag key '${DUPLICATED_TAG_KEY}' on line 1"}`,
json: {
code: "invalid",
message: `invalid line protocol: duplicate tag key '${DUPLICATED_TAG_KEY}' on line 1`,
},
message: `invalid line protocol: duplicate tag key '${DUPLICATED_TAG_KEY}' on line 1`,
};

/** RECORDED shape — Cloud rejects an invalid token. */
export const CLOUD_SDK_401_UNAUTHORIZED: SdkErrorShape = {
statusCode: 401,
statusMessage: "Unauthorized",
body: '{"code":"unauthorized","message":"unauthorized access"}',
json: { code: "unauthorized", message: "unauthorized access" },
message: "unauthorized access",
};

/** PROVISIONAL — Cloud write rejected while a node is unavailable. */
export const CLOUD_SDK_503_UNAVAILABLE: SdkErrorShape = {
statusCode: 503,
statusMessage: "Service Unavailable",
body: '{"code":"unavailable","message":"service temporarily unavailable"}',
json: { code: "unavailable", message: "service temporarily unavailable" },
message: "service temporarily unavailable",
};
Loading