Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/launch.next' into colerogers.fir…
Browse files Browse the repository at this point in the history
…eperf
  • Loading branch information
colerogers committed Sep 9, 2022
2 parents 2768405 + a54cd0b commit 37d60d9
Show file tree
Hide file tree
Showing 12 changed files with 398 additions and 61 deletions.
35 changes: 32 additions & 3 deletions CHANGELOG.md
@@ -1,3 +1,32 @@
- Fixes a bug that disallowed setting customClaims and/or sessionClaims in blocking functions (#1199).
- Add v2 Schedule Triggers (#1177).
- Add performance monitoring triggers to v2 alerts (#1223).
### Breaking Changes

- Deprecated `allowInvalidAppCheckToken` option. Instead use
`enforceAppCheck`.

> App Check enforcement on callable functions is disabled by default in v4.
> Requests containing invalid App Check tokens won't be denied unless you
> explicitly enable App Check enforcement using the new `enforceAppCheck` option.
> Furthermore, when enforcement is enabled, callable functions will deny
> all requests without App Check tokens.
- Dropped support for Node.js versions 8, 10, and 12.
- Dropped support for Admin SDK versions 8 and 9.
- Removed the `functions.handler` namespace.
- `DataSnapshot` passed to the Firebase Realtime Database trigger now
matches the `DataSnapshot` returned by the Admin SDK, with null values
removed.
- Removed `__trigger` object on function handlers.
- Reorganized source code location. This affects only apps that directly import files instead of using the recommend entry points specified in the
- Reworked the `apps` library and removed `lodash` as a runtime dependency.

### Enhancements

- Logs created with the `functions.logger` package in v2 functions
are now annotated with each request's trace ID, making it easy to correlate
log entries with the incoming request. Trace IDs are especially useful for
cases where 2nd gen's concurrency feature permits a function
to handle multiple requests at any given time. See
[Correlate log entries](https://cloud.google.com/logging/docs/view/correlate-logs) to learn more.
- `functions.logger.error` now always outputs an error object and is included in Google Cloud Error Reporting.
- The logging severity of Auth/App Check token validation has changed from `info` to `debug` level.
- Event parameters for 2nd generation functions are now strongly typed, permitting stronger TypeScript types for matched parameters.
82 changes: 42 additions & 40 deletions docgen/toc.ts
Expand Up @@ -6,18 +6,12 @@
* down the api model.
*/
import * as yaml from 'js-yaml';
import {
ApiPackage,
ApiItem,
ApiItemKind,
ApiParameterListMixin,
ApiModel,
} from 'api-extractor-model-me';
import { ModuleSource } from '@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference';
import { FileSystem, PackageName } from '@rushstack/node-core-library';
import {ApiItem, ApiItemKind, ApiModel, ApiPackage, ApiParameterListMixin,} from 'api-extractor-model-me';
import {ModuleSource} from '@microsoft/tsdoc/lib-commonjs/beta/DeclarationReference';
import {FileSystem, PackageName} from '@rushstack/node-core-library';
import yargs from 'yargs';
import { writeFileSync } from 'fs';
import { resolve, join } from 'path';
import {writeFileSync} from 'fs';
import {join, resolve} from 'path';

function getSafeFileName(f: string): string {
return f.replace(/[^a-z0-9_\-\.]/gi, '_').toLowerCase();
Expand Down Expand Up @@ -108,13 +102,33 @@ export function generateToc({
}
}

const toc = [];
generateTocRecursively(apiModel, g3Path, addFileNameSuffix, toc);
// Firebase Functions only have 1 entry point. Let's traverse the tree to find it.
const apiItems: ApiItem[] = [];
let cursor = apiModel as ApiItem;
while (cursor?.kind !== ApiItemKind.EntryPoint) {
apiItems.push(...cursor.members);
cursor = apiItems.pop();
}
if (!cursor) {
throw new Error("Couldn't find entry point from api model. Are you sure you've generated the api model?")
}

const entryPointName = (
cursor.canonicalReference.source! as ModuleSource
).escapedPath.replace('@firebase/', '');

const entryPointToc: ITocItem = {
title: entryPointName,
path: `${g3Path}/${getFilenameForApiItem(cursor, addFileNameSuffix)}`,
section: [],
};

generateTocRecursively(cursor, g3Path, addFileNameSuffix, entryPointToc);

writeFileSync(
resolve(outputFolder, 'toc.yaml'),
yaml.dump(
{ toc },
{ toc: entryPointToc },
{
quotingType: '"',
}
Expand All @@ -126,43 +140,31 @@ function generateTocRecursively(
apiItem: ApiItem,
g3Path: string,
addFileNameSuffix: boolean,
toc: ITocItem[]
toc: ITocItem
) {
// generate toc item only for entry points
if (apiItem.kind === ApiItemKind.EntryPoint) {
// Entry point
const entryPointName = (
apiItem.canonicalReference.source! as ModuleSource
).escapedPath.replace('@firebase/', '');
const entryPointToc: ITocItem = {
title: entryPointName,
path: `${g3Path}/${getFilenameForApiItem(apiItem, addFileNameSuffix)}`,
section: [],
};

for (const member of apiItem.members) {
// only classes and interfaces have dedicated pages
// only namespaces/classes gets included in ToC.
if (
member.kind === ApiItemKind.Interface ||
member.kind === ApiItemKind.Namespace
[
ApiItemKind.Class,
ApiItemKind.Namespace,
ApiItemKind.Interface,
].includes(member.kind)
) {
const fileName = getFilenameForApiItem(member, addFileNameSuffix);
const title =
member.displayName[0].toUpperCase() + member.displayName.slice(1);
entryPointToc.section!.push({
const section: ITocItem = {
title,
path: `${g3Path}/${fileName}`,
});
}
if (!toc.section) {
toc.section = [];
}
toc.section.push(section);
generateTocRecursively(member, g3Path, addFileNameSuffix, section);
}
}

toc.push(entryPointToc);
} else {
// travel the api tree to find the next entry point
for (const member of apiItem.members) {
generateTocRecursively(member, g3Path, addFileNameSuffix, toc);
}
}
}

const { input, output, path } = yargs(process.argv.slice(2))
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 6 additions & 2 deletions package.json
@@ -1,6 +1,6 @@
{
"name": "firebase-functions",
"version": "3.22.0",
"version": "3.23.0",
"description": "Firebase SDK for Cloud Functions",
"keywords": [
"firebase",
Expand Down Expand Up @@ -56,7 +56,8 @@
"./v2/eventarc": "./lib/v2/providers/eventarc.js",
"./v2/identity": "./lib/v2/providers/identity.js",
"./v2/database": "./lib/v2/providers/database.js",
"./v2/scheduler": "./lib/v2/providers/scheduler.js"
"./v2/scheduler": "./lib/v2/providers/scheduler.js",
"./v2/remoteConfig": "./lib/v2/providers/remoteConfig.js"
},
"typesVersions": {
"*": {
Expand Down Expand Up @@ -146,6 +147,9 @@
],
"v2/scheduler": [
"lib/v2/providers/scheduler"
],
"v2/remoteConfig": [
"lib/v2/providers/remoteConfig"
]
}
},
Expand Down
74 changes: 74 additions & 0 deletions spec/v2/providers/remoteConfig.spec.ts
@@ -0,0 +1,74 @@
// The MIT License (MIT)
//
// Copyright (c) 2022 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

import { expect } from "chai";
import * as remoteConfig from "../../../src/v2/providers/remoteConfig";
import * as options from "../../../src/v2/options";

describe("onConfigUpdated", () => {
afterEach(() => {
options.setGlobalOptions({});
});

it("should create a function with a handler", () => {
const fn = remoteConfig.onConfigUpdated(() => 2);

expect(fn.__endpoint).to.deep.eq({
platform: "gcfv2",
labels: {},
eventTrigger: {
eventType: remoteConfig.eventType,
eventFilters: {},
retry: false,
},
});
expect(fn.run(1 as any)).to.eq(2);
});

it("should create a function with opts and a handler", () => {
options.setGlobalOptions({
memory: "512MiB",
region: "us-west1",
});

const fn = remoteConfig.onConfigUpdated(
{
region: "us-central1",
retry: true,
},
() => 2
);

expect(fn.__endpoint).to.deep.eq({
platform: "gcfv2",
availableMemoryMb: 512,
region: ["us-central1"],
labels: {},
eventTrigger: {
eventType: remoteConfig.eventType,
eventFilters: {},
retry: true,
},
});
expect(fn.run(1 as any)).to.eq(2);
});
});
2 changes: 1 addition & 1 deletion src/params/types.ts
Expand Up @@ -63,7 +63,7 @@ export class TernaryExpression<
}

value(): T {
return this.test.value ? this.ifTrue : this.ifFalse;
return this.test.value() ? this.ifTrue : this.ifFalse;
}

toString() {
Expand Down
13 changes: 10 additions & 3 deletions src/v1/cloud-functions.ts
Expand Up @@ -220,7 +220,7 @@ export interface Runnable<T> {
}

/**
* The Cloud Function type for HTTPS triggers. This should be exported from your
* The function type for HTTPS triggers. This should be exported from your
* JavaScript file to define a Cloud Function.
*
* @remarks
Expand All @@ -240,9 +240,16 @@ export interface HttpsFunction {
}

/**
* The Cloud Function type for Blocking triggers.
* The function type for Auth Blocking triggers.
*
* @remarks
* This type is a special JavaScript function for Auth Blocking triggers which takes Express
* {@link https://expressjs.com/en/api.html#req | `Request` } and
* {@link https://expressjs.com/en/api.html#res | `Response` } objects as its only
* arguments.
*/
export interface BlockingFunction {
/** @public */
(req: Request, resp: Response): void | Promise<void>;

/** @internal */
Expand All @@ -253,7 +260,7 @@ export interface BlockingFunction {
}

/**
* The Cloud Function type for all non-HTTPS triggers. This should be exported
* The function type for all non-HTTPS triggers. This should be exported
* from your JavaScript file to define a Cloud Function.
*
* This type is a special JavaScript function which takes a templated
Expand Down
29 changes: 26 additions & 3 deletions src/v1/providers/auth.ts
Expand Up @@ -71,9 +71,11 @@ export interface UserOptions {
}

/**
* Handles events related to Firebase authentication users.
* Handles events related to Firebase Auth users events.
*
* @param userOptions - Resource level options
* @returns UserBuilder - Builder used to create Cloud Functions for Firebase Auth user lifecycle events
* @returns UserBuilder - Builder used to create functions for Firebase Auth user lifecycle events
*
* @public
*/
export function user(userOptions?: UserOptions): UserBuilder {
Expand All @@ -95,14 +97,15 @@ export function _userWithOptions(options: DeploymentOptions, userOptions: UserOp
}

/**
* Builder used to create Cloud Functions for Firebase Auth user lifecycle events.
* Builder used to create functions for Firebase Auth user lifecycle events.
* @public
*/
export class UserBuilder {
private static dataConstructor(raw: Event): UserRecord {
return userRecordConstructor(raw.data);
}

/* @internal */
constructor(
private triggerResource: () => string,
private options: DeploymentOptions,
Expand All @@ -111,6 +114,9 @@ export class UserBuilder {

/**
* Responds to the creation of a Firebase Auth user.
*
* @param handler Event handler that responds to the creation of a Firebase Auth user.
*
* @public
*/
onCreate(
Expand All @@ -121,6 +127,9 @@ export class UserBuilder {

/**
* Responds to the deletion of a Firebase Auth user.
*
* @param handler Event handler that responds to the deletion of a Firebase Auth user.
*
* @public
*/
onDelete(
Expand All @@ -129,6 +138,13 @@ export class UserBuilder {
return this.onOperation(handler, "user.delete");
}

/**
* Blocks request to create a Firebase Auth user.
*
* @param handler Event handler that blocks creation of a Firebase Auth user.
*
* @public
*/
beforeCreate(
handler: (
user: AuthUserRecord,
Expand All @@ -138,6 +154,13 @@ export class UserBuilder {
return this.beforeOperation(handler, "beforeCreate");
}

/**
* Blocks request to sign-in a Firebase Auth user.
*
* @param handler Event handler that blocks sign-in of a Firebase Auth user.
*
* @public
*/
beforeSignIn(
handler: (
user: AuthUserRecord,
Expand Down

0 comments on commit 37d60d9

Please sign in to comment.