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
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*!
* Licensed to the 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. The 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.
*/
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";

import { Wrapper } from "src/utils/Wrapper";

import { renderStructuredLog, renderTIContextPreamble, tiContextFields } from "./renderStructuredLog";

const translate = (key: string) => key;

describe("tiContextFields", () => {
it("contains the six fields bound via bind_contextvars", () => {
expect(tiContextFields).toEqual(
expect.arrayContaining(["ti_id", "dag_id", "task_id", "run_id", "try_number", "map_index"]),
);
expect(tiContextFields).toHaveLength(6);
});
});

describe("renderStructuredLog — TI context field stripping", () => {
it("does not render TI context fields as per-line structured attributes", () => {
const result = renderStructuredLog({
index: 0,
logLink: "",
logMessage: {
dag_id: "my_dag",
event: "Task started",
level: "info",
map_index: -1,
run_id: "run_1",
task_id: "my_task",
ti_id: "abc-123",
timestamp: "2025-01-01T00:00:00Z",
try_number: 1,
},
renderingMode: "jsx",
translate: translate as never,
});

render(<Wrapper>{result}</Wrapper>);

for (const field of tiContextFields) {
expect(screen.queryByText(new RegExp(`${field}=`, "u"))).toBeNull();
}
expect(screen.getByText("Task started")).toBeInTheDocument();
});

it("still renders non-TI structured fields normally", () => {
const result = renderStructuredLog({
index: 0,
logLink: "",
logMessage: {
dag_id: "my_dag",
event: "Task started",
level: "info",
some_custom_key: "some_value",
ti_id: "abc-123",
timestamp: "2025-01-01T00:00:00Z",
},
renderingMode: "jsx",
translate: translate as never,
});

render(<Wrapper>{result}</Wrapper>);

expect(screen.getByText(/some_custom_key/u)).toBeInTheDocument();
expect(screen.queryByText(/ti_id/u)).toBeNull();
});
});

describe("renderTIContextPreamble", () => {
it("text mode: returns key=value pairs joined by spaces, prefixed with label", () => {
const result = renderTIContextPreamble(
{ dag_id: "my_dag", task_id: "my_task", ti_id: "abc-123" },
"text",
"Task Identity",
);

expect(result).toContain("Task Identity");
expect(result).toContain("ti_id=abc-123");
expect(result).toContain("dag_id=my_dag");
expect(result).toContain("task_id=my_task");
});

it("text mode: no label when omitted", () => {
const result = renderTIContextPreamble({ dag_id: "my_dag", ti_id: "abc-123" }, "text");

expect(result).toContain("dag_id=my_dag");
expect(result).toContain("ti_id=abc-123");
expect(result).not.toContain("Task Identity");
});

it("text mode: only renders fields present in context", () => {
const result = renderTIContextPreamble({ ti_id: "abc-123" }, "text", "Task Identity");

expect(result).toContain("ti_id=abc-123");
expect(result).not.toContain("dag_id");
});

it("jsx mode: renders label and key=value spans", () => {
const element = renderTIContextPreamble(
{ dag_id: "my_dag", ti_id: "abc-123", try_number: 1 },
"jsx",
"Task Identity",
);

const { container } = render(<Wrapper>{element}</Wrapper>);

expect(screen.getByText("Task Identity")).toBeInTheDocument();
// Keys render in their own spans
expect(screen.getByText("dag_id")).toBeInTheDocument();
expect(screen.getByText("ti_id")).toBeInTheDocument();
// Values are text nodes adjacent to the = sign; check via container text content
expect(container.textContent).toContain("dag_id=my_dag");
expect(container.textContent).toContain("ti_id=abc-123");
});

it("jsx mode: no label element when label is omitted", () => {
const element = renderTIContextPreamble({ dag_id: "my_dag" }, "jsx");

render(<Wrapper>{element}</Wrapper>);

expect(screen.queryByText("Task Identity")).toBeNull();
expect(screen.getByText("dag_id")).toBeInTheDocument();
});

it("jsx mode: only renders fields present in context", () => {
const element = renderTIContextPreamble({ ti_id: "abc-123" }, "jsx", "Task Identity");

render(<Wrapper>{element}</Wrapper>);

expect(screen.getByText("ti_id")).toBeInTheDocument();
expect(screen.queryByText("dag_id")).toBeNull();
});

it("jsx mode: empty context renders label only", () => {
const element = renderTIContextPreamble({}, "jsx", "Task Identity");

render(<Wrapper>{element}</Wrapper>);

expect(screen.getByText("Task Identity")).toBeInTheDocument();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@
* specific language governing permissions and limitations
* under the License.
*/

/* eslint-disable max-lines */
import { chakra, Code, Link } from "@chakra-ui/react";
import type { TFunction } from "i18next";
import type { JSX } from "react";
import * as React from "react";
import { Link as RouterLink } from "react-router-dom";

import type { StructuredLogMessage } from "openapi/requests/types.gen";
import type { StructuredLogMessage, TaskInstancesLogResponse } from "openapi/requests/types.gen";
import AnsiRenderer from "src/components/AnsiRenderer";
import Time from "src/components/Time";
import { urlRegex } from "src/constants/urlRegex";
Expand Down Expand Up @@ -109,6 +111,69 @@ const addAnsiWithLinks = (line: string) => {

const sourceFields = ["logger", "chan", "lineno", "filename", "loc"];

// Fields bound once per task-instance process via bind_contextvars — identical on every log line,
// so we strip them from per-line rendering and show them once as a preamble instead.
export const tiContextFields = ["ti_id", "dag_id", "task_id", "run_id", "try_number", "map_index"];

export const renderTIContextPreamble = (
context: Record<string, unknown>,
renderingMode: "jsx" | "text" = "jsx",
label?: string,
): JSX.Element | string => {
const fields = tiContextFields.filter((field) => field in context);

if (renderingMode === "text") {
const prefix = label === undefined ? "" : `${label} `;

return prefix + fields.map((field) => `${field}=${String(context[field])}`).join(" ");
}

return (
<chakra.span lineHeight={1.5} opacity={0.7}>
{label === undefined ? undefined : <chakra.span fontWeight="medium">{label}</chakra.span>}
{fields.map((field) => (
<React.Fragment key={field}>
{" "}
<span>
<chakra.span color="fg.info">{field}</chakra.span>={String(context[field])}
</span>
</React.Fragment>
))}
</chakra.span>
);
};

const extractFromStructuredDatum = (
line: string | StructuredLogMessage,
): Record<string, unknown> | undefined => {
if (typeof line === "string") {
return undefined;
}
const ctx: Record<string, unknown> = {};

for (const field of tiContextFields) {
if (Object.hasOwn(line, field) && line[field] !== undefined) {
ctx[field] = line[field];
}
}

return Object.keys(ctx).length > 0 ? ctx : undefined;
};

export const extractTIContext = (
data: TaskInstancesLogResponse["content"],
): Record<string, unknown> | undefined => {
for (const datum of data) {
const ctx = extractFromStructuredDatum(datum);

if (ctx !== undefined) {
return ctx;
}
}

return undefined;
};

const renderStructuredLogImpl = ({
index,
logLevelFilters,
Expand Down Expand Up @@ -240,6 +305,9 @@ const renderStructuredLogImpl = ({
if (!showSource && sourceFields.includes(key)) {
continue; // eslint-disable-line no-continue
}
if (tiContextFields.includes(key)) {
continue; // eslint-disable-line no-continue
}
const val = reStructured[key] as boolean | number | object | string | null;

// Let strings, ints, etc through as is, but JSON stringify anything more complex
Expand Down
44 changes: 44 additions & 0 deletions airflow-core/src/airflow/ui/src/mocks/handlers/log.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,50 @@ export const handlers: Array<HttpHandler> = [
continuation_token: null,
}),
),
http.get("/api/v2/dags/log_grouping/dagRuns/manual__2025-02-18T12:19/taskInstances/ti_context/-1", () =>
HttpResponse.json({
...ti,
dag_run_id: "manual__2025-02-18T12:19",
task_display_name: "ti_context",
task_id: "ti_context",
}),
),
http.get("/api/v2/dags/log_grouping/dagRuns/manual__2025-02-18T12:19/taskInstances/ti_context/logs/1", () =>
HttpResponse.json({
content: [
{
event: "::group::Log message source details",
sources: [
"/home/airflow/logs/dag_id=log_grouping/run_id=manual__2025-02-18T12:19/task_id=ti_context/attempt=1.log",
],
},
{ event: "::endgroup::" },
{
dag_id: "log_grouping",
event: "Task started",
level: "info",
map_index: -1,
run_id: "manual__2025-02-18T12:19",
task_id: "ti_context",
ti_id: "01951900-16f6-7c1c-ae66-91bdfe9e0cfd",
timestamp: "2025-02-18T12:19:56.263258Z",
try_number: 1,
},
{
dag_id: "log_grouping",
event: "Task finished",
level: "info",
map_index: -1,
run_id: "manual__2025-02-18T12:19",
task_id: "ti_context",
ti_id: "01951900-16f6-7c1c-ae66-91bdfe9e0cfd",
timestamp: "2025-02-18T12:19:56.467235Z",
try_number: 1,
},
],
continuation_token: null,
}),
),
http.get("/api/v2/dags/log_grouping/dagRuns/manual__2025-02-18T12:19/taskInstances/log_source/-1", () =>
HttpResponse.json({
...ti,
Expand Down
Loading
Loading