-
Notifications
You must be signed in to change notification settings - Fork 1k
feat: add extension.yaml to Functions Build converter #8990
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
taeold
wants to merge
21
commits into
master
Choose a base branch
from
extension-adapter-support
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 10 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
9145702
feat: add extension.yaml adapter for Functions deployment
taeold 4238d98
refactor: improve extensionAdapter test file
taeold 108ba75
refactor: simplify extensionAdapter code
taeold 1b2aa27
refactor: unify endpoint creation and remove any types
taeold 5bc2318
refactor: simplify parameter conversion logic
taeold a3ff006
refactor: remove runtime parameter from extensionAdapter
taeold d44834a
fix: address code review feedback for extensionAdapter
taeold 1a5ff94
refactor: simplify IAM and lifecycle handling with TODOs
taeold 3000da5
refactor: simplify extensionAdapter using existing utilities
taeold f6a5f91
style: clean up extensionAdapter per code review
taeold 4f55af6
fix: address extensionAdapter code review feedback and add edge case …
taeold 90b33fa
refactor: improve extensionAdapter based on code review feedback
taeold 27486aa
fix: address additional extensionAdapter review feedback
taeold d62d0ff
fix: optimize extension detection and clean up code
taeold 3a8f3d2
feat: add default Firestore v2 filters for parity with emulator
taeold 9f154da
test: update expected output for v2-function test
taeold 8a6cabc
refactor: remove redundant endpoints initialization
taeold 12b3dee
Merge branch 'master' into extension-adapter-support
taeold 786f483
fix: convert multiSelect extension params to list type in functions
taeold 07bcfda
fix: auto-detect numeric select params and convert to IntParam
taeold 319553b
docs: add comprehensive documentation about system params in extensio…
taeold File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { expect } from "chai"; | ||
import * as fs from "fs"; | ||
import * as path from "path"; | ||
import { detectAndAdaptExtension } from "./extensionAdapter"; | ||
|
||
describe("extensionAdapter golden tests", () => { | ||
const fixturesDir = path.resolve(__dirname, "../../../src/test/fixtures/extensionAdapter"); | ||
|
||
const getFixtures = (): string[] => { | ||
return fs.readdirSync(fixturesDir).filter((dir) => { | ||
const stats = fs.statSync(path.join(fixturesDir, dir)); | ||
return ( | ||
stats.isDirectory() && | ||
fs.existsSync(path.join(fixturesDir, dir, "extension.yaml")) && | ||
fs.existsSync(path.join(fixturesDir, dir, "expected.json")) | ||
); | ||
}); | ||
}; | ||
|
||
const fixtures = getFixtures(); | ||
|
||
fixtures.forEach((fixtureName) => { | ||
it(`should correctly convert ${fixtureName}`, async () => { | ||
const fixtureDir = path.join(fixturesDir, fixtureName); | ||
const expectedPath = path.join(fixtureDir, "expected.json"); | ||
const expected = JSON.parse(fs.readFileSync(expectedPath, "utf8")); | ||
|
||
const result = await detectAndAdaptExtension(fixtureDir, "test-project"); | ||
|
||
expect(result).to.not.be.undefined; | ||
expect(result).to.deep.equal(expected); | ||
}); | ||
}); | ||
|
||
it("should return undefined for directory without extension.yaml", async () => { | ||
const result = await detectAndAdaptExtension("/tmp/no-extension", "test-project"); | ||
|
||
expect(result).to.be.undefined; | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,332 @@ | ||
import * as path from "path"; | ||
import * as fs from "fs"; | ||
import { logger } from "../../logger"; | ||
import { FirebaseError } from "../../error"; | ||
import * as build from "./build"; | ||
import * as params from "./params"; | ||
import * as api from "../../api"; | ||
import * as proto from "../../gcp/proto"; | ||
import { readExtensionYaml, DEFAULT_RUNTIME } from "../../extensions/emulator/specHelper"; | ||
import { getResourceRuntime } from "../../extensions/utils"; | ||
import { | ||
Resource, | ||
Param, | ||
FUNCTIONS_RESOURCE_TYPE, | ||
FUNCTIONS_V2_RESOURCE_TYPE, | ||
FunctionResourceProperties, | ||
FunctionV2ResourceProperties, | ||
} from "../../extensions/types"; | ||
|
||
// Reuse validFunctionTypes from specHelper | ||
const validFunctionTypes = [ | ||
FUNCTIONS_RESOURCE_TYPE, | ||
FUNCTIONS_V2_RESOURCE_TYPE, | ||
"firebaseextensions.v1beta.scheduledFunction", | ||
]; | ||
|
||
/** | ||
* Convert extension parameter references to CEL format | ||
* ${param:NAME} -> {{ params.NAME }} | ||
* ${NAME} -> {{ params.NAME }} (some extensions use this shorthand) | ||
*/ | ||
function convertParamReference(value: string): string { | ||
return value | ||
.replace(/\${param:([^}]+)}/g, "{{ params.$1 }}") | ||
.replace(/\${([^:}]+)}/g, "{{ params.$1 }}"); | ||
} | ||
|
||
/** | ||
* Process any field that might contain parameter references | ||
*/ | ||
function processField<T>(value: T): T { | ||
if (value === null || value === undefined) { | ||
return value; | ||
} | ||
|
||
if (typeof value === "string") { | ||
if (value.includes("${param:") || (value.includes("${") && value.includes("}"))) { | ||
return convertParamReference(value) as T; | ||
} | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return value; | ||
} | ||
|
||
if (Array.isArray(value)) { | ||
return value.map(processField) as T; | ||
} | ||
|
||
if (typeof value === "object") { | ||
const processed: Record<string, unknown> = {}; | ||
for (const [key, val] of Object.entries(value)) { | ||
processed[key] = processField(val); | ||
} | ||
return processed as T; | ||
} | ||
|
||
return value; | ||
} | ||
|
||
/** | ||
* Convert an extension resource to a functions deployment endpoint | ||
*/ | ||
function createEndpoint(resource: Resource, projectId: string): build.Endpoint { | ||
const runtime = getResourceRuntime(resource) || DEFAULT_RUNTIME; | ||
const isV2 = resource.type === FUNCTIONS_V2_RESOURCE_TYPE; | ||
|
||
const v1Resource = resource as Resource & { | ||
properties?: FunctionResourceProperties["properties"]; | ||
}; | ||
const v2Resource = resource as Resource & { | ||
properties?: FunctionV2ResourceProperties["properties"]; | ||
}; | ||
|
||
const location = isV2 ? v2Resource.properties?.location : v1Resource.properties?.location; | ||
const baseEndpoint = { | ||
entryPoint: resource.entryPoint || resource.name, | ||
platform: (isV2 ? "gcfv2" : "gcfv1") as "gcfv1" | "gcfv2", | ||
project: projectId, | ||
runtime, | ||
region: [processField(location || api.functionsDefaultRegion())], | ||
}; | ||
|
||
let endpoint: build.Endpoint; | ||
|
||
if (isV2 && v2Resource.properties) { | ||
const props = v2Resource.properties; | ||
if (props.eventTrigger) { | ||
const eventTrigger: build.EventTrigger = { | ||
eventType: props.eventTrigger.eventType, | ||
retry: props.eventTrigger.retryPolicy === "RETRY_POLICY_RETRY", | ||
}; | ||
|
||
if (props.eventTrigger.eventFilters) { | ||
eventTrigger.eventFilters = {}; | ||
for (const filter of props.eventTrigger.eventFilters) { | ||
eventTrigger.eventFilters[filter.attribute] = processField(filter.value); | ||
} | ||
} | ||
if (props.eventTrigger.channel) { | ||
eventTrigger.channel = processField(props.eventTrigger.channel); | ||
} | ||
if (props.eventTrigger.triggerRegion) { | ||
eventTrigger.region = processField(props.eventTrigger.triggerRegion); | ||
} | ||
|
||
endpoint = { ...baseEndpoint, eventTrigger }; | ||
} else { | ||
endpoint = { ...baseEndpoint, httpsTrigger: {} }; | ||
} | ||
} else if (!isV2 && v1Resource.properties) { | ||
const props = v1Resource.properties; | ||
if (props.eventTrigger) { | ||
const eventTrigger: build.EventTrigger = { | ||
eventType: props.eventTrigger.eventType, | ||
retry: false, | ||
}; | ||
|
||
if (props.eventTrigger.resource || props.eventTrigger.service) { | ||
eventTrigger.eventFilters = {}; | ||
if (props.eventTrigger.resource) { | ||
eventTrigger.eventFilters.resource = processField(props.eventTrigger.resource); | ||
} | ||
if (props.eventTrigger.service) { | ||
eventTrigger.eventFilters.service = processField(props.eventTrigger.service); | ||
} | ||
} | ||
|
||
endpoint = { ...baseEndpoint, eventTrigger }; | ||
} else if (props.scheduleTrigger) { | ||
endpoint = { | ||
...baseEndpoint, | ||
scheduleTrigger: { | ||
schedule: processField(props.scheduleTrigger.schedule) || "", | ||
timeZone: processField(props.scheduleTrigger.timeZone) || null, | ||
}, | ||
}; | ||
} else if (props.taskQueueTrigger) { | ||
const taskQueueTrigger: build.TaskQueueTrigger = {}; | ||
if (props.taskQueueTrigger.rateLimits) { | ||
taskQueueTrigger.rateLimits = processField(props.taskQueueTrigger.rateLimits); | ||
} | ||
if (props.taskQueueTrigger.retryConfig) { | ||
taskQueueTrigger.retryConfig = processField(props.taskQueueTrigger.retryConfig); | ||
} | ||
endpoint = { ...baseEndpoint, taskQueueTrigger }; | ||
} else { | ||
endpoint = { ...baseEndpoint, httpsTrigger: {} }; | ||
} | ||
} else { | ||
endpoint = { ...baseEndpoint, httpsTrigger: {} }; | ||
} | ||
|
||
if (!isV2 && v1Resource.properties) { | ||
if (v1Resource.properties.timeout) { | ||
const timeout = v1Resource.properties.timeout; | ||
if (typeof timeout === "string" && (timeout.includes("${param:") || timeout.includes("${"))) { | ||
endpoint.timeoutSeconds = processField(timeout); | ||
} else { | ||
endpoint.timeoutSeconds = proto.secondsFromDuration(timeout); | ||
} | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
if (v1Resource.properties.availableMemoryMb !== undefined) { | ||
endpoint.availableMemoryMb = processField(v1Resource.properties.availableMemoryMb); | ||
} | ||
} else if (isV2 && v2Resource.properties?.serviceConfig) { | ||
const serviceConfig = v2Resource.properties.serviceConfig; | ||
proto.copyIfPresent(endpoint, serviceConfig, "timeoutSeconds"); | ||
if (endpoint.timeoutSeconds !== undefined) { | ||
endpoint.timeoutSeconds = processField(endpoint.timeoutSeconds); | ||
} | ||
if (serviceConfig.availableMemory !== undefined) { | ||
const mem = serviceConfig.availableMemory; | ||
if (typeof mem === "string" && (mem.includes("${param:") || mem.includes("${"))) { | ||
endpoint.availableMemoryMb = processField(mem); | ||
} else if (typeof mem === "string") { | ||
endpoint.availableMemoryMb = parseInt(mem); | ||
} else { | ||
endpoint.availableMemoryMb = mem; | ||
} | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
proto.renameIfPresent(endpoint, serviceConfig, "minInstances", "minInstanceCount"); | ||
proto.renameIfPresent(endpoint, serviceConfig, "maxInstances", "maxInstanceCount"); | ||
if (endpoint.minInstances !== undefined) { | ||
endpoint.minInstances = processField(endpoint.minInstances); | ||
} | ||
if (endpoint.maxInstances !== undefined) { | ||
endpoint.maxInstances = processField(endpoint.maxInstances); | ||
} | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
return endpoint; | ||
} | ||
|
||
/** | ||
* Convert extension params to build params | ||
*/ | ||
function convertParam(param: Param): params.Param { | ||
if (param.type === "secret") { | ||
return { | ||
type: "secret", | ||
name: param.param, | ||
}; | ||
} | ||
|
||
const stringParam: params.StringParam = { | ||
type: "string", | ||
name: param.param, | ||
label: param.label, | ||
}; | ||
|
||
if (param.description !== undefined) stringParam.description = param.description; | ||
if (param.immutable !== undefined) stringParam.immutable = param.immutable; | ||
if (param.default !== undefined) stringParam.default = processField(String(param.default)); | ||
|
||
// Handle different input types | ||
switch (param.type) { | ||
case "select": { | ||
if (param.options) { | ||
stringParam.input = { | ||
select: { | ||
options: param.options.map((opt) => ({ | ||
label: opt.label || String(opt.value), | ||
value: String(opt.value), | ||
})), | ||
}, | ||
}; | ||
} | ||
break; | ||
} | ||
case "multiSelect": { | ||
if (param.options) { | ||
stringParam.input = { | ||
multiSelect: { | ||
options: param.options.map((opt) => ({ | ||
label: opt.label || String(opt.value), | ||
value: String(opt.value), | ||
})), | ||
}, | ||
}; | ||
} | ||
break; | ||
} | ||
case "selectResource": | ||
stringParam.input = { | ||
resource: { | ||
type: param.resourceType || "storage.googleapis.com/Bucket", | ||
}, | ||
}; | ||
break; | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
default: | ||
if (param.validationRegex) { | ||
const text: any = { | ||
validationRegex: param.validationRegex, | ||
}; | ||
if (param.validationErrorMessage !== undefined) { | ||
text.validationErrorMessage = param.validationErrorMessage; | ||
} | ||
if (param.example !== undefined) { | ||
text.example = param.example; | ||
} | ||
stringParam.input = { text }; | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
} | ||
|
||
return stringParam; | ||
} | ||
|
||
/** | ||
* Detect and convert extension.yaml to functions Build format for deployment | ||
*/ | ||
export async function detectAndAdaptExtension( | ||
projectDir: string, | ||
projectId: string, | ||
): Promise<build.Build | undefined> { | ||
const extensionYamlPath = path.join(projectDir, "extension.yaml"); | ||
|
||
try { | ||
await fs.promises.access(extensionYamlPath); | ||
} catch { | ||
return undefined; | ||
} | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
const extensionSpec = await readExtensionYaml(projectDir); | ||
|
||
if (!extensionSpec.name || !extensionSpec.version) { | ||
throw new FirebaseError("extension.yaml is missing required fields: name or version"); | ||
} | ||
|
||
if (!extensionSpec.resources || extensionSpec.resources.length === 0) { | ||
throw new FirebaseError("extension.yaml must contain at least one resource"); | ||
} | ||
|
||
logger.info(`Detected extension "${extensionSpec.name}" v${extensionSpec.version}`); | ||
logger.info("Adapting extension.yaml for functions deployment..."); | ||
|
||
// TODO: Handle IAM roles - extensions can require specific IAM roles for their service account | ||
// TODO: Support lifecycle events (onInstall, onUpdate, onConfigure) - these are task queue functions | ||
|
||
const functionsBuild = build.empty(); | ||
|
||
functionsBuild.endpoints = {}; | ||
taeold marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for (const resource of extensionSpec.resources) { | ||
if (validFunctionTypes.includes(resource.type)) { | ||
functionsBuild.endpoints[resource.name] = createEndpoint(resource, projectId); | ||
} | ||
} | ||
|
||
if (Object.keys(functionsBuild.endpoints).length === 0) { | ||
throw new FirebaseError("No function resources found in extension.yaml"); | ||
} | ||
|
||
logger.info(`Found ${Object.keys(functionsBuild.endpoints).length} function(s) in extension`); | ||
|
||
functionsBuild.params = (extensionSpec.params || []).map(convertParam); | ||
|
||
if (extensionSpec.apis) { | ||
functionsBuild.requiredAPIs = extensionSpec.apis.map((api) => ({ | ||
api: api.apiName, | ||
reason: api.reason, | ||
})); | ||
} | ||
|
||
return functionsBuild; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.