Skip to content
This repository was archived by the owner on Feb 6, 2026. It is now read-only.

Commit 955da2a

Browse files
committed
feat: add shared utilities for GCP functions to reduce code duplication
- Create shared/utils.ts with common GCP functions (getAccessToken, normalizeGcpResourceValues, buildUrlWithParams, etc.) - Modify createDefaultFuncSpec to automatically prepend shared utilities to all GCP func files - Remove duplicated helper functions from individual func files (create, update, delete, refresh, discover, import) - Maintain self-contained constraint by prepending utilities at build time - Reduces ~200+ lines of duplicated code across 6+ files - Improves maintainability while preserving existing architecture This resolves code duplication while keeping each func file self-contained and ensures consistent helper implementations across all GCP functions.
1 parent 5259492 commit 955da2a

8 files changed

Lines changed: 335 additions & 895 deletions

File tree

‎bin/clover/src/pipelines/gcp/funcs/actions/create.ts‎

Lines changed: 2 additions & 130 deletions
Original file line numberDiff line numberDiff line change
@@ -53,60 +53,8 @@ async function main(component: Input): Promise<Output> {
5353

5454
const { token, projectId } = await getAccessToken(serviceAccountJson);
5555

56-
// Build the URL by replacing path parameters
57-
let url = `${baseUrl}${insertApiPath.path}`;
58-
const queryParams: string[] = [];
59-
60-
// Replace path parameters with values from resource_value or domain
61-
// Parameters not found in the path template are added as query parameters
62-
if (insertApiPath.parameterOrder) {
63-
for (const paramName of insertApiPath.parameterOrder) {
64-
let paramValue;
65-
66-
// Use extracted project_id for project/projectId parameter
67-
if (paramName === "project" || paramName === "projectId") {
68-
paramValue = projectId;
69-
} else if (paramName === "parent") {
70-
paramValue = _.get(component.properties, ["domain", "parent"]);
71-
if (!paramValue && projectId) {
72-
// auto-construct for project-only resources
73-
const availableScopesJson = _.get(component.properties, ["domain", "extra", "availableScopes"]);
74-
const availableScopes = availableScopesJson ? JSON.parse(availableScopesJson) : [];
75-
const isProjectOnly = availableScopes.length === 1 && availableScopes[0] === "projects";
76-
77-
if (isProjectOnly) {
78-
const location = _.get(component.properties, ["domain", "location"]) ||
79-
_.get(component.properties, ["domain", "zone"]) ||
80-
_.get(component.properties, ["domain", "region"]);
81-
if (location) {
82-
paramValue = `projects/${projectId}/locations/${location}`;
83-
}
84-
}
85-
}
86-
} else {
87-
paramValue = _.get(component.properties, ["domain", paramName]);
88-
}
89-
90-
if (paramValue) {
91-
// Handle {+param} (reserved expansion - don't encode, allows slashes)
92-
if (url.includes(`{+${paramName}}`)) {
93-
url = url.replace(`{+${paramName}}`, paramValue);
94-
} else if (url.includes(`{${paramName}}`)) {
95-
// Handle {param} (simple expansion - encode)
96-
url = url.replace(`{${paramName}}`, encodeURIComponent(paramValue));
97-
} else {
98-
// Parameter not in path template - add as query parameter
99-
// This handles APIs like GCS where project is a query param, not a path param
100-
queryParams.push(`${paramName}=${encodeURIComponent(paramValue)}`);
101-
}
102-
}
103-
}
104-
}
105-
106-
// Append query parameters to URL
107-
if (queryParams.length > 0) {
108-
url += (url.includes("?") ? "&" : "?") + queryParams.join("&");
109-
}
56+
// Build the URL using shared utility (handles both path and query parameters)
57+
const url = buildUrlWithParams(baseUrl, insertApiPath, component, projectId);
11058

11159
const httpMethod = insertApiPath.httpMethod || "POST";
11260

@@ -295,79 +243,3 @@ function extractResourceId(resource: any, useFullPath: boolean): string | undefi
295243
// For Compute Engine style APIs or fallback, use simple name/id
296244
return resource.name || resource.id;
297245
}
298-
299-
async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> {
300-
// Parse service account JSON to extract project_id (optional)
301-
let projectId: string | undefined;
302-
try {
303-
const serviceAccount = JSON.parse(serviceAccountJson);
304-
projectId = serviceAccount.project_id;
305-
} catch {
306-
// If parsing fails or project_id is missing, continue without it
307-
projectId = undefined;
308-
}
309-
310-
const activateResult = await siExec.waitUntilEnd("gcloud", [
311-
"auth",
312-
"activate-service-account",
313-
"--key-file=-",
314-
"--quiet"
315-
], {
316-
input: serviceAccountJson
317-
});
318-
319-
if (activateResult.exitCode !== 0) {
320-
throw new Error(`Failed to activate service account: ${activateResult.stderr}`);
321-
}
322-
323-
const tokenResult = await siExec.waitUntilEnd("gcloud", [
324-
"auth",
325-
"print-access-token"
326-
]);
327-
328-
if (tokenResult.exitCode !== 0) {
329-
throw new Error(`Failed to get access token: ${tokenResult.stderr}`);
330-
}
331-
332-
return {
333-
token: tokenResult.stdout.trim(),
334-
projectId,
335-
};
336-
}
337-
338-
// URL normalization for GCP resource values
339-
const GCP_URL_PATTERN = /^https:\/\/[^/]*\.?googleapis\.com\//;
340-
const LOCATION_SEGMENTS = new Set(["regions", "zones", "locations"]);
341-
342-
function normalizeGcpResourceValues<T>(obj: T): T {
343-
if (obj === null || obj === undefined) return obj;
344-
if (Array.isArray(obj)) return obj.map(item => normalizeGcpResourceValues(item)) as T;
345-
if (typeof obj === "object") {
346-
const normalized: Record<string, unknown> = {};
347-
for (const [key, value] of Object.entries(obj)) {
348-
if (typeof value === "string" && GCP_URL_PATTERN.test(value)) {
349-
const pathParts = new URL(value).pathname.split("/").filter(Boolean);
350-
if (pathParts.length >= 2 && LOCATION_SEGMENTS.has(pathParts[pathParts.length - 2])) {
351-
normalized[key] = pathParts[pathParts.length - 1];
352-
} else {
353-
const projectsIdx = pathParts.indexOf("projects");
354-
if (projectsIdx !== -1) {
355-
normalized[key] = pathParts.slice(projectsIdx).join("/");
356-
} else {
357-
// For non-project APIs (e.g., Storage), extract after API version (v1, v2, etc.)
358-
const versionIdx = pathParts.findIndex(p => /^v\d+/.test(p));
359-
normalized[key] = versionIdx !== -1 && versionIdx + 1 < pathParts.length
360-
? pathParts.slice(versionIdx + 1).join("/")
361-
: pathParts[pathParts.length - 1] || value;
362-
}
363-
}
364-
} else if (typeof value === "object" && value !== null) {
365-
normalized[key] = normalizeGcpResourceValues(value);
366-
} else {
367-
normalized[key] = value;
368-
}
369-
}
370-
return normalized as T;
371-
}
372-
return obj;
373-
}

‎bin/clover/src/pipelines/gcp/funcs/actions/delete.ts‎

Lines changed: 2 additions & 127 deletions
Original file line numberDiff line numberDiff line change
@@ -36,76 +36,8 @@ async function main(component: Input): Promise<Output> {
3636

3737
const { token, projectId } = await getAccessToken(serviceAccountJson);
3838

39-
// Build the URL by replacing path parameters
40-
let url: string;
41-
42-
// If resourceId is already a full path matching the API structure, use it directly
43-
// This handles cases where resourceId is "projects/xxx/datasets/yyy/tables/zzz"
44-
if (isFullResourcePath(resourceId, deleteApiPath.path)) {
45-
url = `${baseUrl}${resourceId}`;
46-
} else {
47-
url = `${baseUrl}${deleteApiPath.path}`;
48-
49-
// Replace path parameters with values from resource_value or domain
50-
// GCP APIs use RFC 6570 URI templates: {param} and {+param} (reserved expansion)
51-
if (deleteApiPath.parameterOrder) {
52-
for (const paramName of deleteApiPath.parameterOrder) {
53-
let paramValue;
54-
55-
// For the resource identifier, use resourceId
56-
if (paramName === deleteApiPath.parameterOrder[deleteApiPath.parameterOrder.length - 1]) {
57-
paramValue = resourceId;
58-
} else if (paramName === "project" || paramName === "projectId") {
59-
// Use extracted project_id for project/projectId parameter
60-
paramValue = projectId;
61-
} else if (paramName === "parent") {
62-
// "parent" is a common GCP pattern: projects/{project}/locations/{location}
63-
paramValue = _.get(component.properties, ["resource", "payload", "parent"]) ||
64-
_.get(component.properties, ["domain", "parent"]);
65-
if (!paramValue && projectId) {
66-
// Only auto-construct for project-only resources
67-
// Multi-scope resources require explicit parent
68-
const availableScopesJson = _.get(component.properties, ["domain", "extra", "availableScopes"]);
69-
const availableScopes = availableScopesJson ? JSON.parse(availableScopesJson) : [];
70-
const isProjectOnly = availableScopes.length === 1 && availableScopes[0] === "projects";
71-
72-
if (isProjectOnly) {
73-
const location = _.get(component.properties, ["resource", "payload", "location"]) ||
74-
_.get(component.properties, ["domain", "location"]) ||
75-
_.get(component.properties, ["domain", "zone"]) ||
76-
_.get(component.properties, ["domain", "region"]);
77-
if (location) {
78-
paramValue = `projects/${projectId}/locations/${location}`;
79-
}
80-
}
81-
}
82-
} else {
83-
paramValue = _.get(component.properties, ["resource", "payload", paramName]) ||
84-
_.get(component.properties, ["domain", paramName]);
85-
86-
// GCP often returns full URLs for reference fields e.g.
87-
// region: //www.googleapis.com/compute/v1/projects/myproject/regions/us-central1
88-
// network: //www.googleapis.com/compute/v1/projects/myproject/networks/my-network
89-
90-
// Extract just the resource name from the URL
91-
if (paramValue && typeof paramValue === "string" && paramValue.startsWith("https://")) {
92-
const urlParts = paramValue.split("/");
93-
paramValue = urlParts[urlParts.length - 1];
94-
}
95-
}
96-
97-
if (paramValue) {
98-
// Handle {+param} (reserved expansion - don't encode, allows slashes)
99-
if (url.includes(`{+${paramName}}`)) {
100-
url = url.replace(`{+${paramName}}`, paramValue);
101-
} else {
102-
// Handle {param} (simple expansion - encode)
103-
url = url.replace(`{${paramName}}`, encodeURIComponent(paramValue));
104-
}
105-
}
106-
}
107-
}
108-
}
39+
// Build the URL using shared utility
40+
const url = buildUrlWithParams(baseUrl, deleteApiPath, component, projectId, { resourceId });
10941

11042
// Make the API request with retry logic
11143
const response = await siExec.withRetry(async () => {
@@ -201,60 +133,3 @@ ${errorText}`
201133
status: "ok",
202134
};
203135
}
204-
205-
async function getAccessToken(serviceAccountJson: string): Promise<{ token: string; projectId: string | undefined }> {
206-
// Parse service account JSON to extract project_id (optional)
207-
let projectId: string | undefined;
208-
try {
209-
const serviceAccount = JSON.parse(serviceAccountJson);
210-
projectId = serviceAccount.project_id;
211-
} catch {
212-
// If parsing fails or project_id is missing, continue without it
213-
projectId = undefined;
214-
}
215-
216-
const activateResult = await siExec.waitUntilEnd("gcloud", [
217-
"auth",
218-
"activate-service-account",
219-
"--key-file=-",
220-
"--quiet"
221-
], {
222-
input: serviceAccountJson
223-
});
224-
225-
if (activateResult.exitCode !== 0) {
226-
throw new Error(`Failed to activate service account: ${activateResult.stderr}`);
227-
}
228-
229-
const tokenResult = await siExec.waitUntilEnd("gcloud", [
230-
"auth",
231-
"print-access-token"
232-
]);
233-
234-
if (tokenResult.exitCode !== 0) {
235-
throw new Error(`Failed to get access token: ${tokenResult.stderr}`);
236-
}
237-
238-
return {
239-
token: tokenResult.stdout.trim(),
240-
projectId,
241-
};
242-
}
243-
244-
// Check if resourceId is already a full path matching the API path structure
245-
function isFullResourcePath(resourceId: string, pathTemplate: string): boolean {
246-
if (!resourceId.includes('/')) return false;
247-
248-
// Extract static segments from template (non-parameter parts)
249-
// e.g., "projects/{+projectId}/datasets/{+datasetId}/tables/{+tableId}" -> ["projects", "datasets", "tables"]
250-
const templateSegments = pathTemplate.split('/').filter(s => !s.startsWith('{'));
251-
252-
// Check if resourceId contains these segments in order
253-
let lastIdx = -1;
254-
for (const seg of templateSegments) {
255-
const idx = resourceId.indexOf(seg, lastIdx + 1);
256-
if (idx === -1) return false;
257-
lastIdx = idx;
258-
}
259-
return true;
260-
}

0 commit comments

Comments
 (0)