Skip to content
Draft
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
12 changes: 9 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,22 @@ jobs:
runs-on: ubuntu-latest
needs: test
timeout-minutes: 30
# Secrets live in the e2e-live environment, scoped to a dedicated CI workspace.
environment: e2e-live
# All runs share one workspace; serialize so production deploys never overlap.
concurrency:
group: sdk-e2e-live
cancel-in-progress: false
env:
TINYBIRD_E2E_BASE_URL: ${{ vars.TINYBIRD_E2E_BASE_URL || 'https://api.tinybird.co' }}
TINYBIRD_E2E_USER_TOKEN: ${{ secrets.TINYBIRD_E2E_USER_TOKEN }}
TINYBIRD_E2E_WORKSPACE_ADMIN_TOKEN: ${{ secrets.TINYBIRD_E2E_WORKSPACE_ADMIN_TOKEN }}
TINYBIRD_E2E_WORKSPACE_TOKEN: ${{ secrets.TINYBIRD_E2E_WORKSPACE_TOKEN }}
TINYBIRD_E2E_DEPLOY_TOKEN: ${{ secrets.TINYBIRD_E2E_DEPLOY_TOKEN }}

steps:
- name: Check required live E2E secrets
id: check-secrets
run: |
if [ -z "${TINYBIRD_E2E_USER_TOKEN}" ] || [ -z "${TINYBIRD_E2E_WORKSPACE_ADMIN_TOKEN}" ]; then
if [ -z "${TINYBIRD_E2E_WORKSPACE_TOKEN}" ] || [ -z "${TINYBIRD_E2E_DEPLOY_TOKEN}" ]; then
echo "run_e2e_tests=false" >> "$GITHUB_OUTPUT"
echo "Skipping live E2E: required secrets are not configured."
else
Expand Down
30 changes: 8 additions & 22 deletions e2e-live/append.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
beforeAll,
beforeEach,
afterEach,
afterAll,
} from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
Expand All @@ -15,9 +14,7 @@ import { getBranch, deleteBranch, BranchApiError } from "../src/api/branches.js"
import { createClient } from "../src/client/base.js";
import {
getLiveE2EConfigFromEnv,
assertWorkspaceAdminToken,
createWorkspaceWithToken,
deleteWorkspace,
createRunScopedName,
type LiveE2EConfig,
} from "./cloud-workspace.js";
import {
Expand Down Expand Up @@ -63,26 +60,21 @@ describeLive("E2E Live: append", () => {
let tempDir = "";
let originalEnv: NodeJS.ProcessEnv;

let workspaceId = "";
let workspaceName = "";
let workspaceToken = "";
const workspaceToken = liveConfig?.workspaceToken ?? "";
const runName = createRunScopedName("sdk_append");
let branchName = "";
let branchToken = "";

beforeAll(async () => {
beforeAll(() => {
ensureDistBuild();
await assertWorkspaceAdminToken(config);

const workspace = await createWorkspaceWithToken(config, "sdk_append");
workspaceId = workspace.id;
workspaceName = workspace.name;
workspaceToken = workspace.token;
});

beforeEach(async () => {
tempDir = createTempProjectDir();
originalEnv = { ...process.env };
process.env.GITHUB_REF_NAME = `live-append/${workspaceName}`;
// The SDK prefers GITHUB_HEAD_REF (set on pull_request runs) over GITHUB_REF_NAME.
delete process.env.GITHUB_HEAD_REF;
process.env.GITHUB_REF_NAME = `live-append/${runName}`;
process.env.TINYBIRD_TOKEN = workspaceToken;

const initResult = await runInit({
Expand Down Expand Up @@ -130,16 +122,10 @@ describeLive("E2E Live: append", () => {
cleanupTempProjectDir(tempDir);
});

afterAll(async () => {
if (workspaceId && workspaceName) {
await deleteWorkspace(config, workspaceId, workspaceName);
}
});

it("appends rows from a local CSV file and serves them via endpoint query", async () => {
const csvPath = path.join(tempDir, "page_views.csv");
const timestamp = toTinybirdDateTime(new Date());
const pathname = "/append-live-e2e";
const pathname = `/append-live-e2e/${runName}`;

fs.writeFileSync(
csvPath,
Expand Down
29 changes: 10 additions & 19 deletions e2e-live/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import { getBranch, deleteBranch, BranchApiError } from "../src/api/branches.js"
import { createClient } from "../src/client/base.js";
import {
getLiveE2EConfigFromEnv,
assertWorkspaceAdminToken,
createWorkspaceWithToken,
deleteWorkspace,
createRunScopedName,
type LiveE2EConfig,
} from "./cloud-workspace.js";
import {
Expand Down Expand Up @@ -65,24 +63,20 @@ describeLive("E2E Live: build", () => {
let tempDir = "";
let originalEnv: NodeJS.ProcessEnv;

let workspaceId = "";
let workspaceName = "";
let workspaceToken = "";
const workspaceToken = liveConfig?.workspaceToken ?? "";
const runName = createRunScopedName("sdk_build");
let tinybirdBranchName = "";

beforeAll(async () => {
beforeAll(() => {
ensureDistBuild();
await assertWorkspaceAdminToken(config);
const workspace = await createWorkspaceWithToken(config, "sdk_build");
workspaceId = workspace.id;
workspaceName = workspace.name;
workspaceToken = workspace.token;
});

beforeEach(() => {
tempDir = createTempProjectDir();
originalEnv = { ...process.env };
process.env.GITHUB_REF_NAME = `live-build/${workspaceName}`;
// The SDK prefers GITHUB_HEAD_REF (set on pull_request runs) over GITHUB_REF_NAME.
delete process.env.GITHUB_HEAD_REF;
process.env.GITHUB_REF_NAME = `live-build/${runName}`;
process.env.TINYBIRD_TOKEN = workspaceToken;
});

Expand All @@ -104,10 +98,6 @@ describeLive("E2E Live: build", () => {
}
}
}

if (workspaceId && workspaceName) {
await deleteWorkspace(config, workspaceId, workspaceName);
}
});

it("builds and deploys resources, then serves queries from the deployed endpoint", async () => {
Expand Down Expand Up @@ -153,14 +143,15 @@ describeLive("E2E Live: build", () => {
token: branchToken,
});

const pathname = `/live-e2e/${runName}`;
await client.ingest("page_views", {
timestamp: toTinybirdDateTime(new Date()),
session_id: "live_test_session",
pathname: "/live-e2e",
pathname,
referrer: null,
});

const rows = await waitForPipeData(branchToken, config.baseUrl);
expect(rows.length).toBeGreaterThan(0);
expect(rows.map((row) => row.pathname)).toContain(pathname);
});
});
195 changes: 37 additions & 158 deletions e2e-live/cloud-workspace.ts
Original file line number Diff line number Diff line change
@@ -1,182 +1,61 @@
import { loadEnvFiles } from "../src/cli/config.js";
import { tinybirdFetch } from "../src/api/fetcher.js";

import { runDeploy } from "../src/cli/commands/deploy.js";

/**
* Live E2E suites run against a single, dedicated CI workspace.
*
* - TINYBIRD_E2E_WORKSPACE_TOKEN: the workspace's admin token. Used for branch
* operations (create/get/delete require ADMIN scope), ingestion, queries and pull.
* - TINYBIRD_E2E_DEPLOY_TOKEN: a static token with WORKSPACE:DEPLOY scope, used for
* production deployments. Optional locally; falls back to the workspace token.
*
* No user tokens are needed: suites never create or delete workspaces.
*/
export interface LiveE2EConfig {
baseUrl: string;
userToken: string;
workspaceAdminToken: string;
}

export interface WorkspaceResponse {
id: string;
name: string;
token?: string;
}

interface WorkspaceTokenInfo {
id: string;
name: string;
scope?: string;
}

interface JsonRequestOptions {
method: "GET" | "POST" | "DELETE";
token: string;
body?: string;
contentType?: string;
workspaceToken: string;
deployToken: string;
}

// Load env from repository root where tinybird.config.* usually lives.
loadEnvFiles(process.cwd());

function parseJsonOrThrow(responseText: string, endpoint: string): unknown {
try {
return JSON.parse(responseText);
} catch {
throw new Error(`Expected JSON from ${endpoint}, got: ${responseText || "<empty>"}`);
}
}

async function requestJson(endpoint: string, options: JsonRequestOptions): Promise<unknown> {
const response = await tinybirdFetch(endpoint, {
method: options.method,
headers: {
Authorization: `Bearer ${options.token}`,
...(options.contentType ? { "Content-Type": options.contentType } : {}),
},
body: options.body,
});

const responseText = await response.text();
if (!response.ok) {
throw new Error(
`Request failed (${options.method} ${endpoint}): ` +
`${response.status} ${response.statusText} - ${responseText || "<empty>"}`
);
}

return parseJsonOrThrow(responseText, endpoint);
}

export function getLiveE2EConfigFromEnv(): LiveE2EConfig | null {
const userToken = process.env.TINYBIRD_E2E_USER_TOKEN;
const workspaceAdminToken = process.env.TINYBIRD_E2E_WORKSPACE_ADMIN_TOKEN;
const workspaceToken = process.env.TINYBIRD_E2E_WORKSPACE_TOKEN;
const baseUrl = process.env.TINYBIRD_E2E_BASE_URL ?? "https://api.tinybird.co";

if (!userToken || !workspaceAdminToken) {
if (!workspaceToken) {
return null;
}

return {
baseUrl,
userToken,
workspaceAdminToken,
workspaceToken,
deployToken: process.env.TINYBIRD_E2E_DEPLOY_TOKEN || workspaceToken,
};
}

export function createWorkspaceName(prefix = "sdk_e2e"): string {
/**
* Unique, branch-safe identifier for this run so concurrent CI runs sharing the
* workspace never collide on branch names.
*/
export function createRunScopedName(prefix: string): string {
const runId = process.env.GITHUB_RUN_ID ?? "local";
const suffix = Math.random().toString(36).slice(2, 8);
return `${prefix}_${Date.now()}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
}

export async function assertWorkspaceAdminToken(config: LiveE2EConfig): Promise<void> {
const endpoint = new URL("/v1/workspace", config.baseUrl).toString();
const payload = (await requestJson(endpoint, {
method: "GET",
token: config.workspaceAdminToken,
})) as WorkspaceTokenInfo;

if (!payload.id || !payload.name) {
throw new Error("Workspace admin token validation failed: missing workspace identity in response.");
}

if (payload.scope !== "admin") {
throw new Error(
`Workspace admin token validation failed: expected scope=admin, got scope=${payload.scope ?? "unknown"}.`
);
}
return `${prefix}_${runId}_${suffix}`.replace(/[^a-zA-Z0-9_]/g, "_");
}

export async function createWorkspace(
config: LiveE2EConfig,
workspaceName: string
): Promise<WorkspaceResponse> {
const endpoint = new URL("/v1/workspaces", config.baseUrl).toString();
const body = new URLSearchParams({ name: workspaceName }).toString();

const payload = (await requestJson(endpoint, {
method: "POST",
token: config.userToken,
body,
contentType: "application/x-www-form-urlencoded",
})) as WorkspaceResponse;

if (!payload.id || !payload.name) {
throw new Error("Workspace creation failed: response missing id or name.");
}

return payload;
}

export async function getWorkspaceWithToken(
config: LiveE2EConfig,
workspaceId: string
): Promise<WorkspaceResponse> {
const endpoint = new URL(`/v1/workspaces/${encodeURIComponent(workspaceId)}`, config.baseUrl);
endpoint.searchParams.set("with_token", "true");

const payload = (await requestJson(endpoint.toString(), {
method: "GET",
token: config.userToken,
})) as WorkspaceResponse;

if (!payload.id || !payload.name) {
throw new Error(`Failed to fetch workspace ${workspaceId}: response missing id or name.`);
}

return payload;
}

export async function waitForWorkspaceToken(
config: LiveE2EConfig,
workspaceId: string,
maxAttempts = 15,
delayMs = 1_000
): Promise<string> {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const workspace = await getWorkspaceWithToken(config, workspaceId);
if (workspace.token) {
return workspace.token;
}
await new Promise((resolve) => setTimeout(resolve, delayMs));
/**
* Deploy to production with the WORKSPACE:DEPLOY token, then switch back to the
* workspace admin token for ingestion, queries and pull. The workspace is shared
* across suites and runs, so destructive operations are allowed: each deploy
* replaces whatever the previous one left behind.
*/
export async function deployToProduction(config: LiveE2EConfig, cwd: string) {
process.env.TINYBIRD_TOKEN = config.deployToken;
try {
return await runDeploy({ cwd, allowDestructiveOperations: true });
} finally {
process.env.TINYBIRD_TOKEN = config.workspaceToken;
}

throw new Error(`Timed out waiting for workspace token (workspace=${workspaceId}).`);
}

export async function createWorkspaceWithToken(
config: LiveE2EConfig,
namePrefix = "sdk_e2e"
): Promise<Required<WorkspaceResponse>> {
const workspace = await createWorkspace(config, createWorkspaceName(namePrefix));
const token = await waitForWorkspaceToken(config, workspace.id);
return {
id: workspace.id,
name: workspace.name,
token,
};
}

export async function deleteWorkspace(
config: LiveE2EConfig,
workspaceId: string,
workspaceName: string
): Promise<void> {
const endpoint = new URL(`/v1/workspaces/${encodeURIComponent(workspaceId)}`, config.baseUrl);
endpoint.searchParams.set("confirmation", workspaceName);

await requestJson(endpoint.toString(), {
method: "DELETE",
token: config.userToken,
});
}
Loading
Loading