Skip to content
Open
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.0.85] - 2026-11-04

### Fixed

- `tinybird preview` no longer hides errors when deleting the existing preview branch: only a 404 is treated as "branch doesn't exist"; other failures are reported as `Failed to delete existing preview branch`.
- CI workflows generated by `tinybird init` no longer run overlapping previews for the same branch: GitHub workflows get a `concurrency` group that cancels the older run, and GitLab jobs get a per-branch `resource_group`. Existing projects can add the same settings to their workflow files.

## [0.0.84] - 2026-09-08

### Changed
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@tinybirdco/sdk",
"version": "0.0.84",
"version": "0.0.85",
"description": "TypeScript SDK for Tinybird Forward - define datasources and pipes as TypeScript",
"type": "module",
"main": "./dist/index.js",
Expand Down
51 changes: 51 additions & 0 deletions src/cli/commands/init.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,57 @@ describe("Init Command", () => {
});
});

describe("CI workflow generation", () => {
async function readGeneratedWorkflow(
workflowProvider: "github" | "gitlab",
workflowPath: string
): Promise<string> {
const originalCwd = process.cwd();
process.chdir(tempDir);

try {
const result = await runInit({
cwd: tempDir,
skipLogin: true,
devMode: "branch",
clientPath: "lib/tinybird.ts",
includeCiWorkflow: true,
workflowProvider,
skipWorkflowPrompt: true,
});

expect(result.success).toBe(true);
return fs.readFileSync(path.join(tempDir, workflowPath), "utf-8");
} finally {
process.chdir(originalCwd);
}
}

it("serializes GitHub preview workflows by ref", async () => {
const content = await readGeneratedWorkflow(
"github",
".github/workflows/tinybird-ci.yaml"
);

expect(content).toContain("concurrency:");
expect(content).toContain(
"group: tinybird-preview-${{ github.head_ref || github.ref }}"
);
expect(content).toContain("cancel-in-progress: true");
});

it("serializes GitLab preview jobs by branch", async () => {
const content = await readGeneratedWorkflow(
"gitlab",
".gitlab/tinybird-ci.yaml"
);

expect(content).toContain(
"resource_group: tinybird-preview-${CI_COMMIT_REF_SLUG}"
);
});
});

describe("directory creation", () => {
it("creates lib directory if it does not exist", async () => {
expect(fs.existsSync(path.join(tempDir, "lib"))).toBe(false);
Expand Down
5 changes: 5 additions & 0 deletions src/cli/commands/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ on:
- "${pathPrefix}tinybird.json"
- "${pathPrefix}**/*.ts"

concurrency:
group: tinybird-preview-\${{ github.head_ref || github.ref }}
cancel-in-progress: true

env:
TINYBIRD_TOKEN: \${{ secrets.TINYBIRD_TOKEN }}

Expand Down Expand Up @@ -226,6 +230,7 @@ function generateGitlabCiWorkflow(workingDirectory?: string): string {

tinybird_ci:
stage: tinybird
resource_group: tinybird-preview-\${CI_COMMIT_REF_SLUG}
image: node:22
rules:
- changes:
Expand Down
100 changes: 96 additions & 4 deletions src/cli/commands/preview.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ vi.mock("../../generator/index.js", () => ({
}));

vi.mock("../../api/branches.js", () => ({
BranchApiError: class BranchApiError extends Error {
constructor(message: string, public readonly status: number) {
super(message);
this.name = "BranchApiError";
}
},
createBranch: vi.fn(),
deleteBranch: vi.fn(),
getBranch: vi.fn(),
Expand Down Expand Up @@ -77,7 +83,7 @@ describe("Preview command", () => {
it("uses config-only last_partition when creating cloud preview branch", async () => {
const { loadConfigAsync } = await import("../config.js");
const { buildFromInclude } = await import("../../generator/index.js");
const { getBranch, createBranch } = await import("../../api/branches.js");
const { getBranch, createBranch, BranchApiError } = await import("../../api/branches.js");
const { deployToMain } = await import("../../api/deploy.js");

vi.mocked(loadConfigAsync).mockResolvedValue({
Expand All @@ -97,7 +103,7 @@ describe("Preview command", () => {
entities: { datasources: {}, pipes: {}, connections: {}, rawDatasources: [], rawPipes: [], sourceFiles: [] },
stats: { datasourceCount: 0, pipeCount: 0, connectionCount: 0 },
});
vi.mocked(getBranch).mockRejectedValue(new Error("not found"));
vi.mocked(getBranch).mockRejectedValue(new BranchApiError("not found", 404));
vi.mocked(createBranch).mockResolvedValue({
id: "b1",
name: "tmp_ci_feature_test",
Expand All @@ -123,7 +129,7 @@ describe("Preview command", () => {
it("creates cloud preview branch without data when branch_data_mode is not set", async () => {
const { loadConfigAsync } = await import("../config.js");
const { buildFromInclude } = await import("../../generator/index.js");
const { getBranch, createBranch } = await import("../../api/branches.js");
const { getBranch, createBranch, BranchApiError } = await import("../../api/branches.js");
const { deployToMain } = await import("../../api/deploy.js");

vi.mocked(loadConfigAsync).mockResolvedValue({
Expand All @@ -143,7 +149,7 @@ describe("Preview command", () => {
entities: { datasources: {}, pipes: {}, connections: {}, rawDatasources: [], rawPipes: [], sourceFiles: [] },
stats: { datasourceCount: 0, pipeCount: 0, connectionCount: 0 },
});
vi.mocked(getBranch).mockRejectedValue(new Error("not found"));
vi.mocked(getBranch).mockRejectedValue(new BranchApiError("not found", 404));
vi.mocked(createBranch).mockResolvedValue({
id: "b1",
name: "tmp_ci_feature_test",
Expand Down Expand Up @@ -211,4 +217,90 @@ describe("Preview command", () => {
expect(createBranch).not.toHaveBeenCalled();
});
});

describe("existing preview branch cleanup", () => {
const setupCloudPreview = async () => {
const { loadConfigAsync } = await import("../config.js");
const { buildFromInclude } = await import("../../generator/index.js");
const { BranchApiError, createBranch, deleteBranch, getBranch } = await import("../../api/branches.js");
const { deployToMain } = await import("../../api/deploy.js");

vi.mocked(loadConfigAsync).mockResolvedValue({
include: ["test.ts"],
token: "p.test-token",
baseUrl: "https://api.tinybird.co",
configPath: "/test/tinybird.config.json",
devMode: "branch",
cwd: "/test",
gitBranch: "feature-test",
tinybirdBranch: "feature_test",
isMainBranch: false,
branchDataMode: null,
});
vi.mocked(buildFromInclude).mockResolvedValue({
resources: { datasources: [], pipes: [], connections: [] },
entities: { datasources: {}, pipes: {}, connections: {}, rawDatasources: [], rawPipes: [], sourceFiles: [] },
stats: { datasourceCount: 0, pipeCount: 0, connectionCount: 0 },
});
vi.mocked(createBranch).mockResolvedValue({
id: "b1",
name: "tmp_ci_feature_test",
token: "p.branch",
created_at: "2024-01-01T00:00:00Z",
});
vi.mocked(deployToMain).mockResolvedValue({
success: true,
result: "success",
datasourceCount: 0,
pipeCount: 0,
connectionCount: 0,
});

return { BranchApiError, createBranch, deleteBranch, getBranch };
};

it("creates a preview branch when the existing branch lookup returns 404", async () => {
const { BranchApiError, createBranch, getBranch } = await setupCloudPreview();
vi.mocked(getBranch).mockRejectedValue(new BranchApiError("branch not found", 404));

const result = await runPreview();

expect(result.success).toBe(true);
expect(createBranch).toHaveBeenCalled();
});

it("creates a preview branch when the existing branch is deleted concurrently", async () => {
const { BranchApiError, createBranch, deleteBranch, getBranch } = await setupCloudPreview();
vi.mocked(getBranch).mockResolvedValue({
id: "existing",
name: "tmp_ci_feature_test",
created_at: "2024-01-01T00:00:00Z",
});
vi.mocked(deleteBranch).mockRejectedValue(new BranchApiError("branch not found", 404));

const result = await runPreview();

expect(result.success).toBe(true);
expect(createBranch).toHaveBeenCalled();
});

it("reports a non-404 failure when deleting the existing preview branch", async () => {
const { BranchApiError, createBranch, deleteBranch, getBranch } = await setupCloudPreview();
vi.mocked(getBranch).mockResolvedValue({
id: "existing",
name: "tmp_ci_feature_test",
created_at: "2024-01-01T00:00:00Z",
});
vi.mocked(deleteBranch).mockRejectedValue(
new BranchApiError("deletion rejected with 422", 422)
);

const result = await runPreview();

expect(result.success).toBe(false);
expect(result.error).toContain("Failed to delete existing preview branch");
expect(result.error).toContain("deletion rejected with 422");
expect(createBranch).not.toHaveBeenCalled();
});
});
});
24 changes: 20 additions & 4 deletions src/cli/commands/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@

import { loadConfigAsync, LOCAL_BASE_URL, type ResolvedConfig, type DevMode } from "../config.js";
import { buildFromInclude, type BuildFromIncludeResult } from "../../generator/index.js";
import { createBranch, deleteBranch, getBranch, type CreateBranchOptions, type TinybirdBranch } from "../../api/branches.js";
import {
BranchApiError,
createBranch,
deleteBranch,
getBranch,
type CreateBranchOptions,
type TinybirdBranch,
} from "../../api/branches.js";
import { deployToMain } from "../../api/deploy.js";
import { buildToTinybird } from "../../api/build.js";
import {
Expand Down Expand Up @@ -224,6 +231,7 @@ export async function runPreview(options: PreviewCommandOptions = {}): Promise<P

// Cloud mode - delete existing branch if it exists, then create fresh and deploy
let branch: TinybirdBranch;
const previewBranchPhase: { current: "delete" | "create" } = { current: "create" };
try {
const apiConfig = { baseUrl: config.baseUrl, token: config.token };
const branchOptions: CreateBranchOptions | undefined =
Expand All @@ -233,6 +241,7 @@ export async function runPreview(options: PreviewCommandOptions = {}): Promise<P

// Check if branch already exists and delete it for a fresh start
try {
previewBranchPhase.current = "delete";
const existingBranch = await getBranch(apiConfig, previewBranchName);
if (existingBranch) {
if (debug) {
Expand All @@ -243,13 +252,16 @@ export async function runPreview(options: PreviewCommandOptions = {}): Promise<P
console.log(`[debug] Existing branch deleted`);
}
}
} catch {
// Branch doesn't exist, that's fine
} catch (error) {
if (!(error instanceof BranchApiError && error.status === 404)) {
throw error;
}
if (debug) {
console.log(`[debug] No existing branch to delete`);
}
}

previewBranchPhase.current = "create";
if (debug) {
console.log(`[debug] Creating preview branch: ${previewBranchName}`);
}
Expand All @@ -262,7 +274,11 @@ export async function runPreview(options: PreviewCommandOptions = {}): Promise<P
} catch (error) {
return {
success: false,
error: `Failed to create preview branch: ${(error as Error).message}`,
error: `${
previewBranchPhase.current === "delete"
? "Failed to delete existing preview branch"
: "Failed to create preview branch"
}: ${(error as Error).message}`,
durationMs: Date.now() - startTime,
};
}
Expand Down
Loading