Skip to content
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

fix: determine duplicate function precedence based on extension #5623

Merged
merged 11 commits into from
Apr 13, 2023
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
5 changes: 4 additions & 1 deletion src/lib/functions/registry.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,10 @@ export class FunctionsRegistry {
await Promise.all(deletedFunctions.map((func) => this.unregisterFunction(func.name)))

await Promise.all(
functions.map(async ({ displayName, mainFile, name, runtime: runtimeName }) => {
// zip-it-and-ship-it returns an array sorted based on which extension should have precedence,
// where the last ones precede the previous ones. This is why
// we reverse the array so we get the right functions precedence in the CLI.
functions.reverse().map(async ({ displayName, mainFile, name, runtime: runtimeName }) => {
const runtime = runtimes[runtimeName]

// If there is no matching runtime, it means this function is not yet
Expand Down
4 changes: 2 additions & 2 deletions src/lib/functions/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,9 @@ export const startFunctionsServer = async (options) => {
functionsDirectories.push(distPath)
}
} else {
// The order of the function directories matters. Leftmost directories take
// The order of the function directories matters. Rightmost directories take
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, this feels unrelated to the extension precedence. Is this a separate problem you've identified?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is actually related. In zip-it-and-ship-it we have defined that the rightmost directory takes precedence. Since me reversing the array in this PR is mimicking ZISI behavior, it meant that we had to also use that same logic here in the CLI.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But we're reversing the array of the functions that come out, not the list of directories going in?

(Sorry if I'm missing the point.)

Copy link
Contributor Author

@khendrikse khendrikse Apr 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No worries! I'll try to explain it better.

Previously:

In the CLI we were passing the following to ZISI:
directories: [user-func-dir, internal-func-dir]

This meant that zisi returns a list of functions with the following precedence:

  • user-func-dir/hello.ts
  • user-func-dir/hello.js
  • internal-func-dir/hello.js

This is because ZISI will let functions from the rightmost directory take precedence. (fun fact: we pass the internal folder first in netlify/build as well)

That wasn't a problem before in the CLI, as we'd register the first function we'd encounter (in this case user-func-dir/hello.ts), making the user function take precedence, just like we do in netlify/build.

Currently

To make sure we get the same precedence as ZISI passes on to us, I reversed the functions array we got from ZISI before we register functions. But to also make sure that user functions take precedence like they did before, and like they do because of the way we pass the internal-func folder first in netlify/build, I also had to change the way we pass the sourcedirectories.

Otherwise we'd first register the internal-func-dir/hello.js

// precedence.
const sourceDirectories = [settings.functions, internalFunctionsDir].filter(Boolean)
const sourceDirectories = [internalFunctionsDir, settings.functions].filter(Boolean)

functionsDirectories.push(...sourceDirectories)
}
Expand Down
68 changes: 67 additions & 1 deletion tests/unit/lib/functions/registry.test.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,40 @@
import { expect, test, vi } from 'vitest'
import { mkdir, mkdtemp, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { join } from 'path'

import { describe, expect, test, vi } from 'vitest'

import { FunctionsRegistry } from '../../../../src/lib/functions/registry.mjs'
import { watchDebounced } from '../../../../src/utils/command-helpers.mjs'

const duplicateFunctions = [
{
filename: 'hello.js',
content: `exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ message: 'Hello World from .js' }) })`,
},
{
filename: 'hello.ts',
content: `exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ message: 'Hello World from .ts' }) })`,
},
{
filename: 'hello2.js',
content: `exports.handler = async (event) => ({ statusCode: 200, body: JSON.stringify({ message: 'Hello World from .ts' }) })`,
},
{
filename: 'hello2/main.go',
subDir: 'hello2',
content: `package main
import (
"fmt"
)

func main() {
fmt.Println("Hello, world from a go function!")
}
`,
},
]

vi.mock('../../../../src/utils/command-helpers.mjs', async () => {
const helpers = await vi.importActual('../../../../src/utils/command-helpers.mjs')

Expand Down Expand Up @@ -35,6 +67,40 @@ test('registry should only pass functions config to zip-it-and-ship-it', async (
await prepareDirectoryScanStub.mockRestore()
})

describe('the registry handles duplicate functions based on extension precedence', () => {
test('where .js takes precedence over .go, and .go over .ts', async () => {
const projectRoot = await mkdtemp(join(tmpdir(), 'functions-extension-precedence'))
const functionsDirectory = join(projectRoot, 'functions')
await mkdir(functionsDirectory)

duplicateFunctions.forEach(async (func) => {
if (func.subDir) {
const subDir = join(functionsDirectory, func.subDir)
await mkdir(subDir)
}
const file = join(functionsDirectory, func.filename)
await writeFile(file, func.content)
})
const functionsRegistry = new FunctionsRegistry({
projectRoot,
config: {},
timeouts: { syncFunctions: 1, backgroundFunctions: 1 },
settings: { port: 8888 },
})
const prepareDirectoryScanStub = vi.spyOn(FunctionsRegistry, 'prepareDirectoryScan').mockImplementation(() => {})
const setupDirectoryWatcherStub = vi.spyOn(functionsRegistry, 'setupDirectoryWatcher').mockImplementation(() => {})

await functionsRegistry.scan([functionsDirectory])
const { functions } = functionsRegistry

expect(functions.get('hello').runtime.name).toBe('js')
expect(functions.get('hello2').runtime.name).toBe('go')

await setupDirectoryWatcherStub.mockRestore()
await prepareDirectoryScanStub.mockRestore()
})
})

test('should add included_files to watcher', async () => {
const registry = new FunctionsRegistry({})
const func = {
Expand Down