From aef70342f80ed7a194db36eeb521610d0ef5652d Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Fri, 1 Aug 2025 11:05:51 -0700 Subject: [PATCH 1/5] wip --- dartfn/pubspec.yaml | 4 ++-- functions_framework_builder/pubspec.yaml | 6 +++--- functions_framework_builder/test/builder_test.dart | 4 ++-- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/dartfn/pubspec.yaml b/dartfn/pubspec.yaml index d5ee0938..6846bd10 100644 --- a/dartfn/pubspec.yaml +++ b/dartfn/pubspec.yaml @@ -20,7 +20,7 @@ dependencies: path: ^1.8.0 dev_dependencies: - build: ^2.1.0 + build: ^3.0.0 build_config: ^1.0.0 build_runner: ^2.1.0 build_verify: ^3.0.0 @@ -28,6 +28,6 @@ dev_dependencies: dart_flutter_team_lints: ^3.0.0 glob: ^2.0.0 grinder: ^0.9.0 - source_gen: '>=1.0.0 <3.0.0' + source_gen: ^3.0.0 test: ^1.16.6 yaml: ^3.1.0 diff --git a/functions_framework_builder/pubspec.yaml b/functions_framework_builder/pubspec.yaml index e1b844bd..7ca28016 100644 --- a/functions_framework_builder/pubspec.yaml +++ b/functions_framework_builder/pubspec.yaml @@ -9,7 +9,7 @@ environment: dependencies: analyzer: '>=6.9.0 <8.0.0' - build: ^2.3.1 + build: ^3.0.0 build_config: ^1.0.0 collection: ^1.17.0 dart_style: '>=2.3.7 <4.0.0' @@ -20,11 +20,11 @@ dependencies: meta: ^1.7.0 path: ^1.8.0 shelf: ^1.0.0 - source_gen: '>=1.4.0 <3.0.0' + source_gen: ^3.0.0 source_helper: ^1.3.3 dev_dependencies: - build_test: ^2.1.2 + build_test: ^3.0.0 dart_flutter_team_lints: ^3.0.0 package_config: ^2.0.0 stream_transform: ^2.0.0 diff --git a/functions_framework_builder/test/builder_test.dart b/functions_framework_builder/test/builder_test.dart index 09c574fe..4a1484b6 100644 --- a/functions_framework_builder/test/builder_test.dart +++ b/functions_framework_builder/test/builder_test.dart @@ -504,7 +504,7 @@ package:$_pkgName/functions.dart:8:10 await testBuilder( functionsFrameworkBuilder(), srcs, - reader: await PackageAssetReader.currentIsolate(), + packageConfig: (await PackageAssetReader.currentIsolate()).packageConfig, ); }); @@ -647,7 +647,7 @@ Future _generateTest( fail(output); }); }, - reader: await PackageAssetReader.currentIsolate(), + packageConfig: (await PackageAssetReader.currentIsolate()).packageConfig, ); } From a82744315b8d3358b7f3a6ef26b5911183bc968f Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Fri, 1 Aug 2025 14:30:09 -0700 Subject: [PATCH 2/5] update min sdk --- .github/workflows/lint.yml | 22 +++++----- .github/workflows/unit.yml | 44 ++++++++++---------- dartfn/pubspec.yaml | 2 +- dartfn/templates/cloudevent/pubspec.yaml | 2 +- dartfn/templates/helloworld/pubspec.yaml | 2 +- dartfn/templates/json/pubspec.yaml | 2 +- examples/fullstack/backend/pubspec.yaml | 2 +- examples/fullstack/frontend-cli/pubspec.yaml | 2 +- examples/fullstack/frontend/pubspec.yaml | 2 +- examples/hello/pubspec.yaml | 2 +- examples/json/pubspec.yaml | 2 +- examples/protobuf_firestore/pubspec.yaml | 2 +- examples/raw_cloudevent/pubspec.yaml | 2 +- functions_framework/pubspec.yaml | 2 +- functions_framework_builder/pubspec.yaml | 2 +- google_cloud/pubspec.yaml | 2 +- integration_test/pubspec.yaml | 2 +- pubspec.yaml | 2 +- tool/ci.sh | 2 +- 19 files changed, 50 insertions(+), 50 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 66e6ee24..ba399e1a 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1,4 +1,4 @@ -# Created with package:mono_repo v6.6.2 +# Created with package:mono_repo v6.6.3 name: Dart Lint CI on: push: @@ -16,23 +16,23 @@ permissions: read-all jobs: job_001: - name: "analyze_format; Dart 3.6.0; PKGS: dartfn, dartfn/templates/cloudevent, dartfn/templates/helloworld, dartfn/templates/json, examples/fullstack/backend, examples/fullstack/frontend-cli, examples/hello, examples/json, examples/protobuf_firestore, examples/raw_cloudevent, functions_framework, functions_framework_builder, google_cloud; `dart analyze`" + name: "analyze_format; Dart 3.8.0; PKGS: dartfn, dartfn/templates/cloudevent, dartfn/templates/helloworld, dartfn/templates/json, examples/fullstack/backend, examples/fullstack/frontend-cli, examples/hello, examples/json, examples/protobuf_firestore, examples/raw_cloudevent, functions_framework, functions_framework_builder, google_cloud; `dart analyze`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/fullstack/frontend-cli-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework-functions_framework_builder-google_cloud;commands:analyze_1" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/fullstack/frontend-cli-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework-functions_framework_builder-google_cloud;commands:analyze_1" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/fullstack/frontend-cli-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework-functions_framework_builder-google_cloud - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/fullstack/frontend-cli-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework-functions_framework_builder-google_cloud + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.8.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -158,7 +158,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/fullstack/frontend-cli-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework-functions_framework_builder-google_cloud-integration_test;commands:format-analyze_0" @@ -361,7 +361,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:integration_test;commands:analyze_1" @@ -391,7 +391,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:ubuntu-latest;pub-cache-hosted;sdk:stable;packages:examples/fullstack/frontend;commands:format-analyze_2" @@ -401,7 +401,7 @@ jobs: os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Flutter SDK - uses: subosito/flutter-action@fd55f4c5af5b953cc57a2be44cb082c8f6635e8e + uses: subosito/flutter-action@f2c4f6686ca8e8d6e6d0f28410eeef506ed66aff with: channel: stable - id: checkout diff --git a/.github/workflows/unit.yml b/.github/workflows/unit.yml index b43a3f55..dbf48e4a 100644 --- a/.github/workflows/unit.yml +++ b/.github/workflows/unit.yml @@ -1,4 +1,4 @@ -# Created with package:mono_repo v6.6.2 +# Created with package:mono_repo v6.6.3 name: Dart Unit CI on: push: @@ -16,23 +16,23 @@ permissions: read-all jobs: job_001: - name: "unit_test; linux; Dart 3.6.0; PKGS: dartfn, functions_framework_builder, google_cloud, integration_test; `dart test`" + name: "unit_test; linux; Dart 3.8.0; PKGS: dartfn, functions_framework_builder, google_cloud, integration_test; `dart test`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:dartfn-functions_framework_builder-google_cloud-integration_test;commands:test_0" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:dartfn-functions_framework_builder-google_cloud-integration_test;commands:test_0" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:dartfn-functions_framework_builder-google_cloud-integration_test - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:dartfn-functions_framework_builder-google_cloud-integration_test + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.8.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -73,23 +73,23 @@ jobs: if: "always() && steps.integration_test_pub_upgrade.conclusion == 'success'" working-directory: integration_test job_002: - name: "unit_test; linux; Dart 3.6.0; PKG: google_cloud; `./tool/docker_test_script.sh`" + name: "unit_test; linux; Dart 3.8.0; PKG: google_cloud; `./tool/docker_test_script.sh`" runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" - key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:google_cloud;commands:command" + key: "os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:google_cloud;commands:command" restore-keys: | - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0;packages:google_cloud - os:ubuntu-latest;pub-cache-hosted;sdk:3.6.0 + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0;packages:google_cloud + os:ubuntu-latest;pub-cache-hosted;sdk:3.8.0 os:ubuntu-latest;pub-cache-hosted os:ubuntu-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.8.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -107,7 +107,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:dartfn-dartfn/templates/cloudevent-dartfn/templates/helloworld-dartfn/templates/json-examples/fullstack/backend-examples/hello-examples/json-examples/protobuf_firestore-examples/raw_cloudevent-functions_framework_builder-google_cloud-integration_test;commands:test_0" @@ -236,7 +236,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:ubuntu-latest;pub-cache-hosted;sdk:dev;packages:dartfn-functions_framework-integration_test;commands:test_1" @@ -280,23 +280,23 @@ jobs: if: "always() && steps.integration_test_pub_upgrade.conclusion == 'success'" working-directory: integration_test job_005: - name: "unit_test; macos; Dart 3.6.0; PKG: google_cloud; `dart test`" + name: "unit_test; macos; Dart 3.8.0; PKG: google_cloud; `dart test`" runs-on: macos-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" - key: "os:macos-latest;pub-cache-hosted;sdk:3.6.0;packages:google_cloud;commands:test_0" + key: "os:macos-latest;pub-cache-hosted;sdk:3.8.0;packages:google_cloud;commands:test_0" restore-keys: | - os:macos-latest;pub-cache-hosted;sdk:3.6.0;packages:google_cloud - os:macos-latest;pub-cache-hosted;sdk:3.6.0 + os:macos-latest;pub-cache-hosted;sdk:3.8.0;packages:google_cloud + os:macos-latest;pub-cache-hosted;sdk:3.8.0 os:macos-latest;pub-cache-hosted os:macos-latest - name: Setup Dart SDK uses: dart-lang/setup-dart@e51d8e571e22473a2ddebf0ef8a2123f0ab2c02c with: - sdk: "3.6.0" + sdk: "3.8.0" - id: checkout name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 @@ -314,7 +314,7 @@ jobs: runs-on: macos-latest steps: - name: Cache Pub hosted dependencies - uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 + uses: actions/cache@d4323d4df104b026a6aa633fdb11d772146be0bf with: path: "~/.pub-cache/hosted" key: "os:macos-latest;pub-cache-hosted;sdk:dev;packages:google_cloud;commands:test_0" diff --git a/dartfn/pubspec.yaml b/dartfn/pubspec.yaml index 6846bd10..40b2b7c7 100644 --- a/dartfn/pubspec.yaml +++ b/dartfn/pubspec.yaml @@ -7,7 +7,7 @@ homepage: https://github.com/GoogleCloudPlatform/functions-framework-dart resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 executables: dartfn: diff --git a/dartfn/templates/cloudevent/pubspec.yaml b/dartfn/templates/cloudevent/pubspec.yaml index dd66aa0f..412164d6 100644 --- a/dartfn/templates/cloudevent/pubspec.yaml +++ b/dartfn/templates/cloudevent/pubspec.yaml @@ -5,7 +5,7 @@ description: A sample Functions Framework project for handling a cloudevent. publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/dartfn/templates/helloworld/pubspec.yaml b/dartfn/templates/helloworld/pubspec.yaml index 97b61139..68ade074 100644 --- a/dartfn/templates/helloworld/pubspec.yaml +++ b/dartfn/templates/helloworld/pubspec.yaml @@ -5,7 +5,7 @@ description: A sample "Hello, World!" Functions Framework project. publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/dartfn/templates/json/pubspec.yaml b/dartfn/templates/json/pubspec.yaml index 207d3473..34485e9e 100644 --- a/dartfn/templates/json/pubspec.yaml +++ b/dartfn/templates/json/pubspec.yaml @@ -5,7 +5,7 @@ description: A sample Functions Framework project for handling JSON. publish_to: none environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/examples/fullstack/backend/pubspec.yaml b/examples/fullstack/backend/pubspec.yaml index 4a0eb53b..6f826d6c 100644 --- a/examples/fullstack/backend/pubspec.yaml +++ b/examples/fullstack/backend/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/examples/fullstack/frontend-cli/pubspec.yaml b/examples/fullstack/frontend-cli/pubspec.yaml index e6d84b13..057b0540 100644 --- a/examples/fullstack/frontend-cli/pubspec.yaml +++ b/examples/fullstack/frontend-cli/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 executables: greet: diff --git a/examples/fullstack/frontend/pubspec.yaml b/examples/fullstack/frontend/pubspec.yaml index d4a2b5c7..274993b5 100644 --- a/examples/fullstack/frontend/pubspec.yaml +++ b/examples/fullstack/frontend/pubspec.yaml @@ -2,7 +2,7 @@ name: fullstack_demo_frontend publish_to: 'none' environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: cupertino_icons: ^1.0.2 diff --git a/examples/hello/pubspec.yaml b/examples/hello/pubspec.yaml index 43f7d21f..41f049ce 100644 --- a/examples/hello/pubspec.yaml +++ b/examples/hello/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/examples/json/pubspec.yaml b/examples/json/pubspec.yaml index 6eb0cb10..9c4d477d 100644 --- a/examples/json/pubspec.yaml +++ b/examples/json/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/examples/protobuf_firestore/pubspec.yaml b/examples/protobuf_firestore/pubspec.yaml index a19ab3fc..e70e60c1 100644 --- a/examples/protobuf_firestore/pubspec.yaml +++ b/examples/protobuf_firestore/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.3 diff --git a/examples/raw_cloudevent/pubspec.yaml b/examples/raw_cloudevent/pubspec.yaml index a1772395..393d7378 100644 --- a/examples/raw_cloudevent/pubspec.yaml +++ b/examples/raw_cloudevent/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.0 diff --git a/functions_framework/pubspec.yaml b/functions_framework/pubspec.yaml index 39d47cc6..247d0ee9 100644 --- a/functions_framework/pubspec.yaml +++ b/functions_framework/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/GoogleCloudPlatform/functions-framework-dart resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: args: ^2.0.0 diff --git a/functions_framework_builder/pubspec.yaml b/functions_framework_builder/pubspec.yaml index 7ca28016..3e660589 100644 --- a/functions_framework_builder/pubspec.yaml +++ b/functions_framework_builder/pubspec.yaml @@ -5,7 +5,7 @@ repository: https://github.com/GoogleCloudPlatform/functions-framework-dart resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: analyzer: '>=6.9.0 <8.0.0' diff --git a/google_cloud/pubspec.yaml b/google_cloud/pubspec.yaml index 5849f69a..4c9f81d1 100644 --- a/google_cloud/pubspec.yaml +++ b/google_cloud/pubspec.yaml @@ -6,7 +6,7 @@ repository: https://github.com/GoogleCloudPlatform/functions-framework-dart/tree resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: collection: ^1.17.0 diff --git a/integration_test/pubspec.yaml b/integration_test/pubspec.yaml index e07b4211..8ca3cac8 100644 --- a/integration_test/pubspec.yaml +++ b/integration_test/pubspec.yaml @@ -3,7 +3,7 @@ publish_to: none resolution: workspace environment: - sdk: ^3.6.0 + sdk: ^3.8.0 dependencies: functions_framework: ^0.4.3+1 diff --git a/pubspec.yaml b/pubspec.yaml index 8e3d8f2f..8cf13cc0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: ffd_workspace # Can be anything environment: - sdk: ^3.6.0 + sdk: ^3.8.0 publish_to: none diff --git a/tool/ci.sh b/tool/ci.sh index f622b21f..f752f0bc 100755 --- a/tool/ci.sh +++ b/tool/ci.sh @@ -1,5 +1,5 @@ #!/bin/bash -# Created with package:mono_repo v6.6.2 +# Created with package:mono_repo v6.6.3 # Support built in commands on windows out of the box. From 25780b220a7fcd16e7a456bcb59327f97a3c7f97 Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Fri, 1 Aug 2025 14:31:19 -0700 Subject: [PATCH 3/5] format --- dartfn/lib/src/cli/app.dart | 2 +- dartfn/lib/src/cli/command/generate.dart | 14 +- dartfn/lib/src/cli/command/version.dart | 10 +- dartfn/lib/src/generators/cloudevent.dart | 10 +- dartfn/lib/src/generators/cloudevent.g.dart | 2 +- dartfn/lib/src/generators/helloworld.dart | 10 +- dartfn/lib/src/generators/helloworld.g.dart | 2 +- dartfn/lib/src/generators/json.dart | 10 +- dartfn/lib/src/generators/json.g.dart | 2 +- dartfn/lib/src/printer.dart | 8 +- dartfn/test/common_test.dart | 9 +- dartfn/test/validate_templates.dart | 28 +-- dartfn/tool/builder/builder.dart | 8 +- dartfn/tool/builder/src/code_generator.dart | 49 +++--- examples/fullstack/backend/bin/server.dart | 47 +++-- .../fullstack/backend/lib/api_types.g.dart | 13 +- examples/fullstack/backend/lib/functions.dart | 6 +- .../fullstack/backend/test/function_test.dart | 11 +- .../fullstack/frontend-cli/bin/greet.dart | 5 +- .../frontend-cli/lib/api_types.g.dart | 13 +- examples/hello/bin/server.dart | 8 +- examples/hello/test/function_test.dart | 10 +- examples/json/bin/server.dart | 45 +++-- examples/json/lib/functions.g.dart | 13 +- examples/json/test/function_test.dart | 11 +- examples/protobuf_firestore/bin/server.dart | 8 +- .../protobuf_firestore/lib/functions.dart | 4 +- .../test/function_test.dart | 59 +++---- examples/raw_cloudevent/bin/server.dart | 8 +- examples/raw_cloudevent/lib/functions.dart | 5 +- .../raw_cloudevent/test/function_test.dart | 62 +++---- .../tool/binary_mode_request.dart | 7 +- .../tool/structured_mode_request.dart | 11 +- functions_framework/lib/serve.dart | 5 +- .../lib/src/cloud_event.g.dart | 83 ++++----- .../lib/src/function_config.dart | 43 ++--- .../lib/src/function_target.dart | 10 +- .../lib/src/json_request_utils.dart | 3 +- functions_framework/lib/src/run.dart | 10 +- .../lib/src/targets/cloud_event_targets.dart | 14 +- .../lib/src/targets/json_targets.dart | 32 +--- functions_framework/lib/src/typedefs.dart | 26 ++- functions_framework_builder/lib/builder.dart | 17 +- .../lib/src/function_type_validator.dart | 65 ++++--- .../lib/src/generic_function_type.dart | 16 +- .../lib/src/supported_function_type.dart | 4 +- .../lib/src/valid_json_utils.dart | 6 +- .../test/builder_test.dart | 156 ++++++++--------- google_cloud/example/example.dart | 51 +++--- google_cloud/lib/src/gcp_project.dart | 7 +- google_cloud/lib/src/logging.dart | 165 ++++++++---------- google_cloud/test/gcp_test.dart | 44 +++-- integration_test/lib/functions.dart | 16 +- .../lib/src/conformance_handlers.dart | 8 +- integration_test/lib/src/pub_sub_types.g.dart | 12 +- integration_test/test/cli_test.dart | 30 +--- .../test/cloud_behavior_test.dart | 46 ++--- integration_test/test/cloud_event_test.dart | 156 ++++++----------- integration_test/test/custom_type_test.dart | 31 +--- integration_test/test/function_test.dart | 18 +- integration_test/test/logging_test.dart | 35 ++-- integration_test/test/src/test_utils.dart | 21 ++- 62 files changed, 707 insertions(+), 933 deletions(-) diff --git a/dartfn/lib/src/cli/app.dart b/dartfn/lib/src/cli/app.dart index af7b624a..17da2011 100644 --- a/dartfn/lib/src/cli/app.dart +++ b/dartfn/lib/src/cli/app.dart @@ -38,7 +38,7 @@ class App extends Console { late final CommandRunner _runner; App(List generators, [Printer? out, GeneratorTarget? target]) - : super(out) { + : super(out) { generators.sort(); _context = CommandContext( diff --git a/dartfn/lib/src/cli/command/generate.dart b/dartfn/lib/src/cli/command/generate.dart index 488afb32..d5ed9714 100644 --- a/dartfn/lib/src/cli/command/generate.dart +++ b/dartfn/lib/src/cli/command/generate.dart @@ -33,12 +33,10 @@ class GenerateCommand extends Command { GenerateCommand(super.context) { argParser ..addFlag('list', negatable: false, help: 'List available generators.') - // Hidden option to list available projects as JSON to stdout. // This is useful for tools that don't want to have to parse the output of // `--help`. ..addFlag('machine', negatable: false, hide: true) - // Hidden option to generate into the current directory. ..addFlag('force', abbr: 'f', negatable: false, hide: true); } @@ -72,10 +70,11 @@ class GenerateCommand extends Command { final generatorName = options.rest.first; if (!(options['force'] as bool) && !await context.generator.cwd.isEmpty()) { return error( - 'The current directory is not empty. Overwritting an exising project ' - 'is NOT recommended.\n' - 'Create a new (empty) project directory, or use --force to override ' - "this safeguard if you know what you're doing."); + 'The current directory is not empty. Overwritting an exising project ' + 'is NOT recommended.\n' + 'Create a new (empty) project directory, or use --force to override ' + "this safeguard if you know what you're doing.", + ); } return await _generate(generatorName); @@ -92,7 +91,8 @@ class GenerateCommand extends Command { write('project: $projectName'); - final target = context.generator.target ?? + final target = + context.generator.target ?? DirectoryGeneratorTarget(context.console.out, context.generator.cwd); write('Creating $generatorName application `$projectName`:'); diff --git a/dartfn/lib/src/cli/command/version.dart b/dartfn/lib/src/cli/command/version.dart index faa99632..ef91bac2 100644 --- a/dartfn/lib/src/cli/command/version.dart +++ b/dartfn/lib/src/cli/command/version.dart @@ -59,8 +59,9 @@ Future printVersion( return context.console.write(version); } - context.console - .write('Functions Framework for Dart CLI ($name) version: $version'); + context.console.write( + 'Functions Framework for Dart CLI ($name) version: $version', + ); if (!checkUpdates) return; @@ -71,8 +72,9 @@ Future printVersion( final latest = await checkPubForLaterVersion(name, version); if (latest != null) { context.console.write( - 'Version $latest is available! To update to this version, run: ' - '`pub global activate $name`.'); + 'Version $latest is available! To update to this version, run: ' + '`pub global activate $name`.', + ); } }); } diff --git a/dartfn/lib/src/generators/cloudevent.dart b/dartfn/lib/src/generators/cloudevent.dart index 277273e0..9563f6c9 100644 --- a/dartfn/lib/src/generators/cloudevent.dart +++ b/dartfn/lib/src/generators/cloudevent.dart @@ -19,9 +19,9 @@ part 'cloudevent.g.dart'; /// A generator for a pub library. class CloudEventFunctionGenerator extends common.DefaultGenerator { CloudEventFunctionGenerator() - : super( - 'cloudevent', - 'A sample Functions Framework project for handling a cloudevent.', - _data, - ); + : super( + 'cloudevent', + 'A sample Functions Framework project for handling a cloudevent.', + _data, + ); } diff --git a/dartfn/lib/src/generators/cloudevent.g.dart b/dartfn/lib/src/generators/cloudevent.g.dart index f42b1a53..163b0c70 100644 --- a/dartfn/lib/src/generators/cloudevent.g.dart +++ b/dartfn/lib/src/generators/cloudevent.g.dart @@ -318,5 +318,5 @@ Yk1lc3NhZ2UiLAogICAgICAiYXR0cmlidXRlcyI6IHsKICAgICAgICAiYXR0cjEiOiJhdHRyMS12 YWx1ZSIKICAgICAgfSwKICAgICAgImRhdGEiOiAiZEdWemRDQnRaWE56WVdkbElETT0iCiAgICB9 CiAgfQp9JycnOwoKICBmaW5hbCByZXNwb25zZSA9CiAgICAgIGF3YWl0IHBvc3QoVXJpLnBhcnNl KHJlcXVlc3RVcmwpLCBoZWFkZXJzOiBoZWFkZXJzLCBib2R5OiBib2R5KTsKICBwcmludCgncmVz -cG9uc2Uuc3RhdHVzQ29kZTogJHtyZXNwb25zZS5zdGF0dXNDb2RlfScpOwp9Cg==''' +cG9uc2Uuc3RhdHVzQ29kZTogJHtyZXNwb25zZS5zdGF0dXNDb2RlfScpOwp9Cg==''', ]; diff --git a/dartfn/lib/src/generators/helloworld.dart b/dartfn/lib/src/generators/helloworld.dart index 5e50646a..09477a79 100644 --- a/dartfn/lib/src/generators/helloworld.dart +++ b/dartfn/lib/src/generators/helloworld.dart @@ -19,9 +19,9 @@ part 'helloworld.g.dart'; /// A generator for a pub library. class HelloWorldGenerator extends common.DefaultGenerator { HelloWorldGenerator() - : super( - 'helloworld', - 'A sample "Hello, World!" Functions Framework project.', - _data, - ); + : super( + 'helloworld', + 'A sample "Hello, World!" Functions Framework project.', + _data, + ); } diff --git a/dartfn/lib/src/generators/helloworld.g.dart b/dartfn/lib/src/generators/helloworld.g.dart index 4e60efbe..e669f9ca 100644 --- a/dartfn/lib/src/generators/helloworld.g.dart +++ b/dartfn/lib/src/generators/helloworld.g.dart @@ -174,5 +174,5 @@ IFsyMDBdIC8nKSksCiAgICApOwoKICAgIHByb2Muc2lnbmFsKFByb2Nlc3NTaWduYWwuc2lndGVy bSk7CiAgICBhd2FpdCBwcm9jLnNob3VsZEV4aXQoMCk7CgogICAgYXdhaXQgZXhwZWN0TGF0ZXIo CiAgICAgIHByb2Muc3Rkb3V0LAogICAgICBlbWl0c1Rocm91Z2goJ1JlY2VpdmVkIHNpZ25hbCBT SUdURVJNIC0gY2xvc2luZycpLAogICAgKTsKICB9LCB0aW1lb3V0OiBkZWZhdWx0VGltZW91dCk7 -Cn0K''' +Cn0K''', ]; diff --git a/dartfn/lib/src/generators/json.dart b/dartfn/lib/src/generators/json.dart index 9f341daf..d408af8e 100644 --- a/dartfn/lib/src/generators/json.dart +++ b/dartfn/lib/src/generators/json.dart @@ -19,9 +19,9 @@ part 'json.g.dart'; /// A generator for a pub library. class JsonFunctionGenerator extends common.DefaultGenerator { JsonFunctionGenerator() - : super( - 'json', - 'A sample Functions Framework project for handling JSON.', - _data, - ); + : super( + 'json', + 'A sample Functions Framework project for handling JSON.', + _data, + ); } diff --git a/dartfn/lib/src/generators/json.g.dart b/dartfn/lib/src/generators/json.g.dart index b811367c..f24bc900 100644 --- a/dartfn/lib/src/generators/json.g.dart +++ b/dartfn/lib/src/generators/json.g.dart @@ -273,5 +273,5 @@ ZCcpOwoKICAgIGV4cGVjdChhY3R1YWxSZXNwb25zZSwgZXhwZWN0ZWRSZXNwb25zZSk7CgogICAg cHJvYy5zaWduYWwoUHJvY2Vzc1NpZ25hbC5zaWd0ZXJtKTsKICAgIGF3YWl0IHByb2Muc2hvdWxk RXhpdCgwKTsKCiAgICBhd2FpdCBleHBlY3RMYXRlcigKICAgICAgcHJvYy5zdGRvdXQsCiAgICAg IGVtaXRzVGhyb3VnaCgnUmVjZWl2ZWQgc2lnbmFsIFNJR1RFUk0gLSBjbG9zaW5nJyksCiAgICAp -OwogIH0sIHRpbWVvdXQ6IGRlZmF1bHRUaW1lb3V0KTsKfQo=''' +OwogIH0sIHRpbWVvdXQ6IGRlZmF1bHRUaW1lb3V0KTsKfQo=''', ]; diff --git a/dartfn/lib/src/printer.dart b/dartfn/lib/src/printer.dart index bd4718ce..78f2281b 100644 --- a/dartfn/lib/src/printer.dart +++ b/dartfn/lib/src/printer.dart @@ -20,12 +20,12 @@ class Printer { final PrintFunc stderr; Printer([PrintFunc? stdout, PrintFunc? stderr]) - : stdout = stdout ?? print, - stderr = stderr ?? stdout ?? print; + : stdout = stdout ?? print, + stderr = stderr ?? stdout ?? print; Printer.fromPrinter(Printer printer) - : stdout = printer.stdout, - stderr = printer.stderr; + : stdout = printer.stdout, + stderr = printer.stderr; void write([Object? obj]) { stdout(obj ?? ''); diff --git a/dartfn/test/common_test.dart b/dartfn/test/common_test.dart index 2168763c..f55a6755 100644 --- a/dartfn/test/common_test.dart +++ b/dartfn/test/common_test.dart @@ -32,11 +32,10 @@ void main() { }); test('matching input', () { - _expect( - 'foo __bar__ baz', - {'bar': '__baz__', 'baz': 'foo'}, - 'foo __baz__ baz', - ); + _expect('foo __bar__ baz', { + 'bar': '__baz__', + 'baz': 'foo', + }, 'foo __baz__ baz'); }); test('vars must be alpha + numeric', () { diff --git a/dartfn/test/validate_templates.dart b/dartfn/test/validate_templates.dart index 92f80655..b5776cd6 100644 --- a/dartfn/test/validate_templates.dart +++ b/dartfn/test/validate_templates.dart @@ -37,12 +37,14 @@ const _pubspecOrder = [ 'dev_dependencies', ]; -final List _pubspecOrderRegexps = - _pubspecOrder.map((s) => RegExp('^(# *)?$s:', multiLine: true)).toList(); +final List _pubspecOrderRegexps = _pubspecOrder + .map((s) => RegExp('^(# *)?$s:', multiLine: true)) + .toList(); final String _expectedGitIgnore = _getMetaTemplateFile('.gitignore'); -final String _expectedAnalysisOptions = - _getMetaTemplateFile('templates/analysis_options.yaml'); +final String _expectedAnalysisOptions = _getMetaTemplateFile( + 'templates/analysis_options.yaml', +); void main() { late Directory dir; @@ -64,8 +66,9 @@ void main() { ); test('Validate pkg/stagehand pubspec', () { - final pubspecContent = - File(path.join(path.current, 'pubspec.yaml')).readAsStringSync(); + final pubspecContent = File( + path.join(path.current, 'pubspec.yaml'), + ).readAsStringSync(); _validatePubspec(pubspecContent); }); @@ -110,8 +113,9 @@ void _testGenerator(stagehand.Generator generator, Directory tempDir) { !FileSystemEntity.isFileSync(filePath)) { final parent = Directory(path.dirname(filePath)); - final file = - _listSync(parent).firstWhereOrNull((f) => f.path.endsWith('.dart')); + final file = _listSync( + parent, + ).firstWhereOrNull((f) => f.path.endsWith('.dart')); if (file == null) { filePath = null; @@ -158,10 +162,7 @@ void _testGenerator(stagehand.Generator generator, Directory tempDir) { runOptions: RunOptions(workingDirectory: tempDir.path), ); } else { - Pub.run( - 'test', - runOptions: RunOptions(workingDirectory: tempDir.path), - ); + Pub.run('test', runOptions: RunOptions(workingDirectory: tempDir.path)); } } } @@ -178,7 +179,8 @@ void _validatePubspec(String pubspecContentString) { expect( orders, orderedEquals(orders.toList()..sort()), - reason: 'Top-level keys in the pubspec were not in the expected order: ' + reason: + 'Top-level keys in the pubspec were not in the expected order: ' "${_pubspecOrder.join(',')}", ); } diff --git a/dartfn/tool/builder/builder.dart b/dartfn/tool/builder/builder.dart index 642edf78..35ae5928 100644 --- a/dartfn/tool/builder/builder.dart +++ b/dartfn/tool/builder/builder.dart @@ -17,9 +17,5 @@ import 'package:source_gen/source_gen.dart'; import 'src/code_generator.dart'; -Builder builder([BuilderOptions? _]) => PartBuilder( - [ - DataGenerator(), - ], - '.g.dart', - ); +Builder builder([BuilderOptions? _]) => + PartBuilder([DataGenerator()], '.g.dart'); diff --git a/dartfn/tool/builder/src/code_generator.dart b/dartfn/tool/builder/src/code_generator.dart index 43e3e72a..b42f4ac5 100644 --- a/dartfn/tool/builder/src/code_generator.dart +++ b/dartfn/tool/builder/src/code_generator.dart @@ -35,33 +35,34 @@ class DataGenerator extends Generator { return null; } - final name = - p.basenameWithoutExtension(buildStep.inputId.path).replaceAll('_', '-'); + final name = p + .basenameWithoutExtension(buildStep.inputId.path) + .replaceAll('_', '-'); final filteredAssets = - await buildStep.findAssets(Glob('templates/$name/**')).where( - (asset) { - final rootSegment = asset.pathSegments[2]; + await buildStep.findAssets(Glob('templates/$name/**')).where((asset) { + final rootSegment = asset.pathSegments[2]; - if (_excludedRootFiles.contains(rootSegment)) { - return false; - } + if (_excludedRootFiles.contains(rootSegment)) { + return false; + } - if (_allowedDotFiles.contains(rootSegment)) { - return true; - } + if (_allowedDotFiles.contains(rootSegment)) { + return true; + } - return !rootSegment.startsWith('.'); - }, - ).toList() + return !rootSegment.startsWith('.'); + }).toList() ..sort(); - final items = await _getLines(filteredAssets, buildStep).map((item) { - if (item.contains('\n')) { - return "'''\n$item'''"; - } - return "'$item'"; - }).join(','); + final items = await _getLines(filteredAssets, buildStep) + .map((item) { + if (item.contains('\n')) { + return "'''\n$item'''"; + } + return "'$item'"; + }) + .join(','); return 'const _data = [$items];'; } @@ -98,10 +99,10 @@ linter: String _base64encode(List bytes) { final encoded = base64.encode(bytes); -// -// Logic to cut lines into 76-character chunks -// – makes for prettier source code -// + // + // Logic to cut lines into 76-character chunks + // – makes for prettier source code + // final lines = []; var index = 0; diff --git a/examples/fullstack/backend/bin/server.dart b/examples/fullstack/backend/bin/server.dart index 090451b9..4a211d07 100644 --- a/examples/fullstack/backend/bin/server.dart +++ b/examples/fullstack/backend/bin/server.dart @@ -21,27 +21,26 @@ Future main(List args) async { } FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { - 'function' => JsonWithContextFunctionTarget( - function_library.function, - (json) { - if (json is Map) { - try { - return function_library.GreetingRequest.fromJson(json); - } catch (e, stack) { - throw BadRequestException( - 400, - 'There was an error parsing the provided JSON data.', - innerError: e, - innerStack: stack, - ); - } - } - throw BadRequestException( - 400, - 'The provided JSON is not the expected type ' - '`Map`.', - ); - }, - ), - _ => null - }; + 'function' => JsonWithContextFunctionTarget(function_library.function, ( + json, + ) { + if (json is Map) { + try { + return function_library.GreetingRequest.fromJson(json); + } catch (e, stack) { + throw BadRequestException( + 400, + 'There was an error parsing the provided JSON data.', + innerError: e, + innerStack: stack, + ); + } + } + throw BadRequestException( + 400, + 'The provided JSON is not the expected type ' + '`Map`.', + ); + }), + _ => null, +}; diff --git a/examples/fullstack/backend/lib/api_types.g.dart b/examples/fullstack/backend/lib/api_types.g.dart index 8abdf063..0aa8c5e2 100644 --- a/examples/fullstack/backend/lib/api_types.g.dart +++ b/examples/fullstack/backend/lib/api_types.g.dart @@ -7,14 +7,10 @@ part of 'api_types.dart'; // ************************************************************************** GreetingRequest _$GreetingRequestFromJson(Map json) => - GreetingRequest( - name: json['name'] as String?, - ); + GreetingRequest(name: json['name'] as String?); Map _$GreetingRequestToJson(GreetingRequest instance) => - { - 'name': instance.name, - }; + {'name': instance.name}; GreetingResponse _$GreetingResponseFromJson(Map json) => GreetingResponse( @@ -23,7 +19,4 @@ GreetingResponse _$GreetingResponseFromJson(Map json) => ); Map _$GreetingResponseToJson(GreetingResponse instance) => - { - 'salutation': instance.salutation, - 'name': instance.name, - }; + {'salutation': instance.salutation, 'name': instance.name}; diff --git a/examples/fullstack/backend/lib/functions.dart b/examples/fullstack/backend/lib/functions.dart index c3f05f5f..8ff298bd 100644 --- a/examples/fullstack/backend/lib/functions.dart +++ b/examples/fullstack/backend/lib/functions.dart @@ -24,8 +24,10 @@ export 'api_types.dart'; @CloudFunction() GreetingResponse function(GreetingRequest request, RequestContext context) { final name = request.name ?? 'World'; - final response = - GreetingResponse(salutation: _randomSalutation(), name: name); + final response = GreetingResponse( + salutation: _randomSalutation(), + name: name, + ); context.logger.info('greetingResponse: ${response.toJson()}'); return response; } diff --git a/examples/fullstack/backend/test/function_test.dart b/examples/fullstack/backend/test/function_test.dart index 62395eaa..bf9e8674 100644 --- a/examples/fullstack/backend/test/function_test.dart +++ b/examples/fullstack/backend/test/function_test.dart @@ -12,10 +12,7 @@ void main() { test('defaults', timeout: defaultTimeout, () async { final proc = await TestProcess.start('dart', ['bin/server.dart']); - await expectLater( - proc.stdout, - emitsThrough('Listening on :8080'), - ); + await expectLater(proc.stdout, emitsThrough('Listening on :8080')); const body = ''' { @@ -35,8 +32,10 @@ void main() { final actualResponse = GreetingResponse.fromJson(data); // Use any salutation from the list of salutations - final expectedResponse = - GreetingResponse(salutation: salutations[0], name: 'World'); + final expectedResponse = GreetingResponse( + salutation: salutations[0], + name: 'World', + ); expect(salutations, contains(actualResponse.salutation)); expect(actualResponse.name, expectedResponse.name); diff --git a/examples/fullstack/frontend-cli/bin/greet.dart b/examples/fullstack/frontend-cli/bin/greet.dart index 9245474e..1222ef35 100644 --- a/examples/fullstack/frontend-cli/bin/greet.dart +++ b/examples/fullstack/frontend-cli/bin/greet.dart @@ -62,8 +62,9 @@ FutureOr main(List args) async { // (3) display the response // - final greetingResponse = - GreetingResponse.fromJson(jsonDecode(res.body) as Map); + final greetingResponse = GreetingResponse.fromJson( + jsonDecode(res.body) as Map, + ); print('response: ${sw.elapsedMilliseconds} ms'); print(greetingResponse.toJson()); diff --git a/examples/fullstack/frontend-cli/lib/api_types.g.dart b/examples/fullstack/frontend-cli/lib/api_types.g.dart index 8abdf063..0aa8c5e2 100644 --- a/examples/fullstack/frontend-cli/lib/api_types.g.dart +++ b/examples/fullstack/frontend-cli/lib/api_types.g.dart @@ -7,14 +7,10 @@ part of 'api_types.dart'; // ************************************************************************** GreetingRequest _$GreetingRequestFromJson(Map json) => - GreetingRequest( - name: json['name'] as String?, - ); + GreetingRequest(name: json['name'] as String?); Map _$GreetingRequestToJson(GreetingRequest instance) => - { - 'name': instance.name, - }; + {'name': instance.name}; GreetingResponse _$GreetingResponseFromJson(Map json) => GreetingResponse( @@ -23,7 +19,4 @@ GreetingResponse _$GreetingResponseFromJson(Map json) => ); Map _$GreetingResponseToJson(GreetingResponse instance) => - { - 'salutation': instance.salutation, - 'name': instance.name, - }; + {'salutation': instance.salutation, 'name': instance.name}; diff --git a/examples/hello/bin/server.dart b/examples/hello/bin/server.dart index a0f3390b..760c6bc3 100644 --- a/examples/hello/bin/server.dart +++ b/examples/hello/bin/server.dart @@ -21,8 +21,6 @@ Future main(List args) async { } FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { - 'function' => FunctionTarget.http( - function_library.function, - ), - _ => null - }; + 'function' => FunctionTarget.http(function_library.function), + _ => null, +}; diff --git a/examples/hello/test/function_test.dart b/examples/hello/test/function_test.dart index b8c310a5..4b1a1756 100644 --- a/examples/hello/test/function_test.dart +++ b/examples/hello/test/function_test.dart @@ -24,19 +24,13 @@ void main() { test('defaults', timeout: defaultTimeout, () async { final proc = await TestProcess.start('dart', ['bin/server.dart']); - await expectLater( - proc.stdout, - emitsThrough('Listening on :8080'), - ); + await expectLater(proc.stdout, emitsThrough('Listening on :8080')); final response = await get(Uri.parse('http://localhost:8080')); expect(response.statusCode, 200); expect(response.body, 'Hello, World!'); - await expectLater( - proc.stdout, - emitsThrough(endsWith('GET [200] /')), - ); + await expectLater(proc.stdout, emitsThrough(endsWith('GET [200] /'))); proc.signal(ProcessSignal.sigterm); await proc.shouldExit(0); diff --git a/examples/json/bin/server.dart b/examples/json/bin/server.dart index 36062b9a..f6d8b9a4 100644 --- a/examples/json/bin/server.dart +++ b/examples/json/bin/server.dart @@ -21,27 +21,24 @@ Future main(List args) async { } FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { - 'function' => JsonFunctionTarget( - function_library.function, - (json) { - if (json is Map) { - try { - return function_library.GreetingRequest.fromJson(json); - } catch (e, stack) { - throw BadRequestException( - 400, - 'There was an error parsing the provided JSON data.', - innerError: e, - innerStack: stack, - ); - } - } - throw BadRequestException( - 400, - 'The provided JSON is not the expected type ' - '`Map`.', - ); - }, - ), - _ => null - }; + 'function' => JsonFunctionTarget(function_library.function, (json) { + if (json is Map) { + try { + return function_library.GreetingRequest.fromJson(json); + } catch (e, stack) { + throw BadRequestException( + 400, + 'There was an error parsing the provided JSON data.', + innerError: e, + innerStack: stack, + ); + } + } + throw BadRequestException( + 400, + 'The provided JSON is not the expected type ' + '`Map`.', + ); + }), + _ => null, +}; diff --git a/examples/json/lib/functions.g.dart b/examples/json/lib/functions.g.dart index cfae8cc9..4c2bba87 100644 --- a/examples/json/lib/functions.g.dart +++ b/examples/json/lib/functions.g.dart @@ -7,14 +7,10 @@ part of 'functions.dart'; // ************************************************************************** GreetingRequest _$GreetingRequestFromJson(Map json) => - GreetingRequest( - name: json['name'] as String?, - ); + GreetingRequest(name: json['name'] as String?); Map _$GreetingRequestToJson(GreetingRequest instance) => - { - 'name': instance.name, - }; + {'name': instance.name}; GreetingResponse _$GreetingResponseFromJson(Map json) => GreetingResponse( @@ -23,7 +19,4 @@ GreetingResponse _$GreetingResponseFromJson(Map json) => ); Map _$GreetingResponseToJson(GreetingResponse instance) => - { - 'salutation': instance.salutation, - 'name': instance.name, - }; + {'salutation': instance.salutation, 'name': instance.name}; diff --git a/examples/json/test/function_test.dart b/examples/json/test/function_test.dart index 622c153b..91177ecb 100644 --- a/examples/json/test/function_test.dart +++ b/examples/json/test/function_test.dart @@ -26,10 +26,7 @@ void main() { test('defaults', timeout: defaultTimeout, () async { final proc = await TestProcess.start('dart', ['bin/server.dart']); - await expectLater( - proc.stdout, - emitsThrough('Listening on :8080'), - ); + await expectLater(proc.stdout, emitsThrough('Listening on :8080')); const body = ''' { @@ -48,8 +45,10 @@ void main() { final data = json.decode(response.body) as Map; final actualResponse = GreetingResponse.fromJson(data); - final expectedResponse = - GreetingResponse(salutation: 'Hello', name: 'World'); + final expectedResponse = GreetingResponse( + salutation: 'Hello', + name: 'World', + ); expect(actualResponse, expectedResponse); diff --git a/examples/protobuf_firestore/bin/server.dart b/examples/protobuf_firestore/bin/server.dart index b333b468..9ebee381 100644 --- a/examples/protobuf_firestore/bin/server.dart +++ b/examples/protobuf_firestore/bin/server.dart @@ -21,8 +21,6 @@ Future main(List args) async { } FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { - 'function' => FunctionTarget.cloudEventWithContext( - function_library.function, - ), - _ => null - }; + 'function' => FunctionTarget.cloudEventWithContext(function_library.function), + _ => null, +}; diff --git a/examples/protobuf_firestore/lib/functions.dart b/examples/protobuf_firestore/lib/functions.dart index 08ca9f57..d4253f8e 100644 --- a/examples/protobuf_firestore/lib/functions.dart +++ b/examples/protobuf_firestore/lib/functions.dart @@ -23,8 +23,8 @@ import 'src/function_types.dart'; void function(CloudEvent event, RequestContext context) { context.logger.info('event subject: ${event.subject}'); context.logger.debug(jsonEncode(context.request.headers)); - context.responseHeaders['x-data-runtime-types'] = - event.data.runtimeType.toString(); + context.responseHeaders['x-data-runtime-types'] = event.data.runtimeType + .toString(); final instance = DocumentEventData.fromBuffer(event.data as List); stderr.writeln(jsonEncode(instance.toProto3Json())); diff --git a/examples/protobuf_firestore/test/function_test.dart b/examples/protobuf_firestore/test/function_test.dart index ce2e816f..182bbe1a 100644 --- a/examples/protobuf_firestore/test/function_test.dart +++ b/examples/protobuf_firestore/test/function_test.dart @@ -29,21 +29,18 @@ void main() { final proc = await _hostCloudEventHandler(); const subject = 'documents/users/ghXNtePIFmdDOBH3iEMH'; - final response = await _makeRequest( - protobytes, - { - 'ce-id': '785865c0-2b16-439b-ad68-f9672343863a', - 'ce-source': - '//firestore.googleapis.com/projects/dart-redirector/databases/(default)', - 'ce-specversion': '1.0', - 'ce-type': 'google.cloud.firestore.document.v1.updated', - 'Content-Type': 'application/protobuf', - 'ce-dataschema': - 'https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/firestore/v1/data.proto', - 'ce-subject': subject, - 'ce-time': '2023-06-21T12:21:25.413855Z', - }, - ); + final response = await _makeRequest(protobytes, { + 'ce-id': '785865c0-2b16-439b-ad68-f9672343863a', + 'ce-source': + '//firestore.googleapis.com/projects/dart-redirector/databases/(default)', + 'ce-specversion': '1.0', + 'ce-type': 'google.cloud.firestore.document.v1.updated', + 'Content-Type': 'application/protobuf', + 'ce-dataschema': + 'https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/firestore/v1/data.proto', + 'ce-subject': subject, + 'ce-time': '2023-06-21T12:21:25.413855Z', + }); expect(response.statusCode, 200); expect(response.body, isEmpty); expect( @@ -55,18 +52,13 @@ void main() { ); await expectLater( proc.stdout, - emitsInOrder( - [ - startsWith('INFO: event subject: $subject'), - startsWith('DEBUG:'), - ], - ), + emitsInOrder([ + startsWith('INFO: event subject: $subject'), + startsWith('DEBUG:'), + ]), ); - await finishServerTest( - proc, - requestOutput: endsWith('POST [200] /'), - ); + await finishServerTest(proc, requestOutput: endsWith('POST [200] /')); final stderrOutput = await proc.stderrStream().join('\n'); final json = jsonDecode(stderrOutput) as Map; @@ -78,24 +70,19 @@ void main() { Future _makeRequest(Object? body, Map headers) async { final requestUrl = Uri.parse('http://localhost:$autoPort/'); - final response = await post( - requestUrl, - body: body, - headers: headers, - ); + final response = await post(requestUrl, body: body, headers: headers); return response; } Future _hostCloudEventHandler() async { final proc = await startServerTest( - arguments: [ - '--signature-type', - 'cloudevent', - ], + arguments: ['--signature-type', 'cloudevent'], expectedListeningPort: 0, ); return proc; } -final containsTextPlainHeader = - containsPair('content-type', 'text/plain; charset=utf-8'); +final containsTextPlainHeader = containsPair( + 'content-type', + 'text/plain; charset=utf-8', +); diff --git a/examples/raw_cloudevent/bin/server.dart b/examples/raw_cloudevent/bin/server.dart index ab6a3a78..e8d4a0d8 100644 --- a/examples/raw_cloudevent/bin/server.dart +++ b/examples/raw_cloudevent/bin/server.dart @@ -22,8 +22,6 @@ Future main(List args) async { } FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { - 'function' => FunctionTarget.cloudEventWithContext( - function_library.function, - ), - _ => null - }; + 'function' => FunctionTarget.cloudEventWithContext(function_library.function), + _ => null, +}; diff --git a/examples/raw_cloudevent/lib/functions.dart b/examples/raw_cloudevent/lib/functions.dart index 1fd90b03..a1180a34 100644 --- a/examples/raw_cloudevent/lib/functions.dart +++ b/examples/raw_cloudevent/lib/functions.dart @@ -21,7 +21,8 @@ const _encoder = JsonEncoder.withIndent(' '); @CloudFunction() void function(CloudEvent event, RequestContext context) { - context.logger - .info('[CloudEvent] source: ${event.source}, subject: ${event.subject}'); + context.logger.info( + '[CloudEvent] source: ${event.source}, subject: ${event.subject}', + ); stderr.writeln(_encoder.convert(event)); } diff --git a/examples/raw_cloudevent/test/function_test.dart b/examples/raw_cloudevent/test/function_test.dart index 797f54b9..f5b2316a 100644 --- a/examples/raw_cloudevent/test/function_test.dart +++ b/examples/raw_cloudevent/test/function_test.dart @@ -40,17 +40,14 @@ void main() { } }'''; - final response = await _makeRequest( - body, - { - 'Content-Type': 'application/json; charset=utf-8', - 'ce-specversion': '1.0', - 'ce-type': 'google.cloud.pubsub.topic.publish', - 'ce-time': '2020-09-05T03:56:24Z', - 'ce-id': '1234-1234-1234', - 'ce-source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', - }, - ); + final response = await _makeRequest(body, { + 'Content-Type': 'application/json; charset=utf-8', + 'ce-specversion': '1.0', + 'ce-type': 'google.cloud.pubsub.topic.publish', + 'ce-time': '2020-09-05T03:56:24Z', + 'ce-id': '1234-1234-1234', + 'ce-source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', + }); expect(response.statusCode, 200); expect(response.body, isEmpty); @@ -62,18 +59,15 @@ void main() { final stderrOutput = await proc.stderrStream().join('\n'); final json = jsonDecode(stderrOutput) as Map; - expect( - json, - { - 'id': '1234-1234-1234', - 'specversion': '1.0', - 'type': 'google.cloud.pubsub.topic.publish', - 'datacontenttype': 'application/json; charset=utf-8', - 'time': '2020-09-05T03:56:24.000Z', - 'source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', - 'data': jsonDecode(body), - }, - ); + expect(json, { + 'id': '1234-1234-1234', + 'specversion': '1.0', + 'type': 'google.cloud.pubsub.topic.publish', + 'datacontenttype': 'application/json; charset=utf-8', + 'time': '2020-09-05T03:56:24.000Z', + 'source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', + 'data': jsonDecode(body), + }); }); }); @@ -114,13 +108,10 @@ void main() { final json = jsonDecode(stderrOutput) as Map; - expect( - json, - { - ...jsonDecode(body) as Map, - 'datacontenttype': 'application/json; charset=utf-8', - }, - ); + expect(json, { + ...jsonDecode(body) as Map, + 'datacontenttype': 'application/json; charset=utf-8', + }); }); }); } @@ -128,20 +119,13 @@ void main() { Future _makeRequest(String body, Map headers) async { final requestUrl = Uri.parse('http://localhost:$autoPort/'); - final response = await post( - requestUrl, - body: body, - headers: headers, - ); + final response = await post(requestUrl, body: body, headers: headers); return response; } Future _hostCloudEventHandler() async { final proc = await startServerTest( - arguments: [ - '--signature-type', - 'cloudevent', - ], + arguments: ['--signature-type', 'cloudevent'], expectedListeningPort: 0, ); return proc; diff --git a/examples/raw_cloudevent/tool/binary_mode_request.dart b/examples/raw_cloudevent/tool/binary_mode_request.dart index 9deccaca..93e025fe 100644 --- a/examples/raw_cloudevent/tool/binary_mode_request.dart +++ b/examples/raw_cloudevent/tool/binary_mode_request.dart @@ -41,7 +41,10 @@ FutureOr main() async { } }'''; - final response = - await post(Uri.parse(requestUrl), headers: headers, body: body); + final response = await post( + Uri.parse(requestUrl), + headers: headers, + body: body, + ); print('response.statusCode: ${response.statusCode}'); } diff --git a/examples/raw_cloudevent/tool/structured_mode_request.dart b/examples/raw_cloudevent/tool/structured_mode_request.dart index 5aa9c5b0..841811fd 100644 --- a/examples/raw_cloudevent/tool/structured_mode_request.dart +++ b/examples/raw_cloudevent/tool/structured_mode_request.dart @@ -19,9 +19,7 @@ import 'package:http/http.dart'; FutureOr main() async { const requestUrl = 'http://localhost:8080'; - const headers = { - 'content-type': 'application/json', - }; + const headers = {'content-type': 'application/json'}; const body = r''' { @@ -43,7 +41,10 @@ FutureOr main() async { } }'''; - final response = - await post(Uri.parse(requestUrl), headers: headers, body: body); + final response = await post( + Uri.parse(requestUrl), + headers: headers, + body: body, + ); print('response.statusCode: ${response.statusCode}'); } diff --git a/functions_framework/lib/serve.dart b/functions_framework/lib/serve.dart index 6d05e869..65a057b0 100644 --- a/functions_framework/lib/serve.dart +++ b/functions_framework/lib/serve.dart @@ -65,10 +65,7 @@ Future _serve( ) async { final configFromEnvironment = FunctionConfig.fromEnv(); - final config = FunctionConfig.fromArgs( - args, - defaults: configFromEnvironment, - ); + final config = FunctionConfig.fromArgs(args, defaults: configFromEnvironment); final functionTarget = nameToFunctionTarget(config.target); if (functionTarget == null) { diff --git a/functions_framework/lib/src/cloud_event.g.dart b/functions_framework/lib/src/cloud_event.g.dart index 5a531802..eca8d61d 100644 --- a/functions_framework/lib/src/cloud_event.g.dart +++ b/functions_framework/lib/src/cloud_event.g.dart @@ -9,46 +9,49 @@ part of 'cloud_event.dart'; // ************************************************************************** CloudEvent _$CloudEventFromJson(Map json) => $checkedCreate( - 'CloudEvent', + 'CloudEvent', + json, + ($checkedConvert) { + $checkKeys( json, - ($checkedConvert) { - $checkKeys( - json, - requiredKeys: const ['id', 'source', 'specversion', 'type'], - ); - final val = CloudEvent( - id: $checkedConvert('id', (v) => v as String), - source: $checkedConvert('source', (v) => Uri.parse(v as String)), - specVersion: $checkedConvert('specversion', (v) => v as String), - type: $checkedConvert('type', (v) => v as String), - data: $checkedConvert('data', (v) => v), - dataContentType: - $checkedConvert('datacontenttype', (v) => v as String?), - dataSchema: $checkedConvert( - 'dataschema', (v) => v == null ? null : Uri.parse(v as String)), - subject: $checkedConvert('subject', (v) => v as String?), - time: $checkedConvert( - 'time', (v) => v == null ? null : DateTime.parse(v as String)), - ); - return val; - }, - fieldKeyMap: const { - 'specVersion': 'specversion', - 'dataContentType': 'datacontenttype', - 'dataSchema': 'dataschema' - }, + requiredKeys: const ['id', 'source', 'specversion', 'type'], ); + final val = CloudEvent( + id: $checkedConvert('id', (v) => v as String), + source: $checkedConvert('source', (v) => Uri.parse(v as String)), + specVersion: $checkedConvert('specversion', (v) => v as String), + type: $checkedConvert('type', (v) => v as String), + data: $checkedConvert('data', (v) => v), + dataContentType: $checkedConvert('datacontenttype', (v) => v as String?), + dataSchema: $checkedConvert( + 'dataschema', + (v) => v == null ? null : Uri.parse(v as String), + ), + subject: $checkedConvert('subject', (v) => v as String?), + time: $checkedConvert( + 'time', + (v) => v == null ? null : DateTime.parse(v as String), + ), + ); + return val; + }, + fieldKeyMap: const { + 'specVersion': 'specversion', + 'dataContentType': 'datacontenttype', + 'dataSchema': 'dataschema', + }, +); -Map _$CloudEventToJson(CloudEvent instance) => - { - 'id': instance.id, - 'source': instance.source.toString(), - 'specversion': instance.specVersion, - 'type': instance.type, - if (instance.dataContentType case final value?) 'datacontenttype': value, - if (instance.data case final value?) 'data': value, - if (instance.dataSchema?.toString() case final value?) - 'dataschema': value, - if (instance.subject case final value?) 'subject': value, - if (instance.time?.toIso8601String() case final value?) 'time': value, - }; +Map _$CloudEventToJson( + CloudEvent instance, +) => { + 'id': instance.id, + 'source': instance.source.toString(), + 'specversion': instance.specVersion, + 'type': instance.type, + if (instance.dataContentType case final value?) 'datacontenttype': value, + if (instance.data case final value?) 'data': value, + if (instance.dataSchema?.toString() case final value?) 'dataschema': value, + if (instance.subject case final value?) 'subject': value, + if (instance.time?.toIso8601String() case final value?) 'time': value, +}; diff --git a/functions_framework/lib/src/function_config.dart b/functions_framework/lib/src/function_config.dart index 2d00e336..1aad445f 100644 --- a/functions_framework/lib/src/function_config.dart +++ b/functions_framework/lib/src/function_config.dart @@ -27,10 +27,7 @@ const _portOpt = 'port'; const _targetOpt = 'target'; const _functionTypeOpt = 'signature-type'; -enum FunctionType { - http, - cloudevent, -} +enum FunctionType { http, cloudevent } class FunctionConfig { final int port; @@ -46,14 +43,15 @@ class FunctionConfig { // Required per spec: // https://github.com/GoogleCloudPlatform/functions-framework#specification-summary factory FunctionConfig.fromEnv() => FunctionConfig( - port: listenPort(), - target: Platform.environment[environmentKeyFunctionTarget] ?? - defaultFunctionTarget, - functionType: _parseFunctionType( - Platform.environment['FUNCTION_SIGNATURE_TYPE'] ?? - _enumValue(FunctionType.http), - ), - ); + port: listenPort(), + target: + Platform.environment[environmentKeyFunctionTarget] ?? + defaultFunctionTarget, + functionType: _parseFunctionType( + Platform.environment['FUNCTION_SIGNATURE_TYPE'] ?? + _enumValue(FunctionType.http), + ), + ); // Optional per spec: // https://github.com/GoogleCloudPlatform/functions-framework#specification-summary @@ -70,14 +68,16 @@ class FunctionConfig { ) ..addOption( _targetOpt, - help: 'The name of the exported function to be invoked in response to ' + help: + 'The name of the exported function to be invoked in response to ' 'requests.\n' 'Overrides the $environmentKeyFunctionTarget environment variable.', ) ..addOption( _functionTypeOpt, allowed: FunctionType.values.map(_enumValue), - help: 'The signature used when writing your function. ' + help: + 'The signature used when writing your function. ' 'Controls unmarshalling rules and determines which arguments are ' 'used to invoke your function.\n' 'Overrides the FUNCTION_SIGNATURE_TYPE environment variable.', @@ -109,7 +109,8 @@ class FunctionConfig { return FunctionConfig( port: port, - target: options[_targetOpt] as String? ?? + target: + options[_targetOpt] as String? ?? defaults?.target ?? defaultFunctionTarget, functionType: functionTypeOptionValue == null @@ -120,12 +121,12 @@ class FunctionConfig { } FunctionType _parseFunctionType(String type) => FunctionType.values.singleWhere( - (element) => type == _enumValue(element), - orElse: () => throw BadConfigurationException( - 'FUNCTION_SIGNATURE_TYPE environment variable "$type" is not a valid ' - 'option (must be "http" or "cloudevent")', - ), - ); + (element) => type == _enumValue(element), + orElse: () => throw BadConfigurationException( + 'FUNCTION_SIGNATURE_TYPE environment variable "$type" is not a valid ' + 'option (must be "http" or "cloudevent")', + ), +); String _enumValue(FunctionType enumEntry) { final v = enumEntry.toString(); diff --git a/functions_framework/lib/src/function_target.dart b/functions_framework/lib/src/function_target.dart index e294bddc..672e1db8 100644 --- a/functions_framework/lib/src/function_target.dart +++ b/functions_framework/lib/src/function_target.dart @@ -30,13 +30,11 @@ abstract class FunctionTarget { factory FunctionTarget.http(Handler function) = HttpFunctionTarget; - factory FunctionTarget.httpWithLogger( - HandlerWithLogger function, - ) = HttpWithLoggerFunctionTarget; + factory FunctionTarget.httpWithLogger(HandlerWithLogger function) = + HttpWithLoggerFunctionTarget; - factory FunctionTarget.cloudEvent( - CloudEventHandler function, - ) = CloudEventFunctionTarget; + factory FunctionTarget.cloudEvent(CloudEventHandler function) = + CloudEventFunctionTarget; factory FunctionTarget.cloudEventWithContext( CloudEventWithContextHandler function, diff --git a/functions_framework/lib/src/json_request_utils.dart b/functions_framework/lib/src/json_request_utils.dart index 178a5fc8..4ff0184f 100644 --- a/functions_framework/lib/src/json_request_utils.dart +++ b/functions_framework/lib/src/json_request_utils.dart @@ -69,8 +69,7 @@ extension RequestExt on Request { Future decodeJson() async { try { - final value = await (encoding ?? utf8) - .decoder + final value = await (encoding ?? utf8).decoder .bind(read()) .transform(json.decoder) .single; diff --git a/functions_framework/lib/src/run.dart b/functions_framework/lib/src/run.dart index 7ecfced6..893529cd 100644 --- a/functions_framework/lib/src/run.dart +++ b/functions_framework/lib/src/run.dart @@ -40,8 +40,8 @@ Future run( const _forbiddenAssets = {'robots.txt', 'favicon.ico'}; Handler _forbiddenAssetMiddleware(Handler innerHandler) => (Request request) { - if (_forbiddenAssets.contains(request.url.path)) { - return Response.notFound('Not found.'); - } - return innerHandler(request); - }; + if (_forbiddenAssets.contains(request.url.path)) { + return Response.notFound('Not found.'); + } + return innerHandler(request); +}; diff --git a/functions_framework/lib/src/targets/cloud_event_targets.dart b/functions_framework/lib/src/targets/cloud_event_targets.dart index 7ed44911..bbe79f15 100644 --- a/functions_framework/lib/src/targets/cloud_event_targets.dart +++ b/functions_framework/lib/src/targets/cloud_event_targets.dart @@ -63,18 +63,15 @@ class CloudEventWithContextFunctionTarget extends FunctionTarget { Future _eventFromRequest(Request request) => _requiredBinaryHeader.every(request.headers.containsKey) - ? _decodeBinary(request) - : _decodeStructured(request); + ? _decodeBinary(request) + : _decodeStructured(request); Future _decodeStructured(Request request) async { final type = mediaTypeFromRequest(request, requiredMimeType: jsonContentType); var jsonObject = await request.decodeJson() as Map; if (!jsonObject.containsKey('datacontenttype')) { - jsonObject = { - ...jsonObject, - 'datacontenttype': type.toString(), - }; + jsonObject = {...jsonObject, 'datacontenttype': type.toString()}; } return _decodeValidCloudEvent(jsonObject, 'structured-mode message'); @@ -87,8 +84,9 @@ Future _decodeBinary(Request request) async { final data = await request.decode(); final map = { - for (var e in request.headers.entries - .where((element) => element.key.startsWith(_cloudEventPrefix))) + for (var e in request.headers.entries.where( + (element) => element.key.startsWith(_cloudEventPrefix), + )) e.key.substring(_clientEventPrefixLength): e.value, 'datacontenttype': data.mimeType.toString(), 'data': data.data, diff --git a/functions_framework/lib/src/targets/json_targets.dart b/functions_framework/lib/src/targets/json_targets.dart index 9addf52c..1a7ebe80 100644 --- a/functions_framework/lib/src/targets/json_targets.dart +++ b/functions_framework/lib/src/targets/json_targets.dart @@ -38,10 +38,8 @@ abstract class JsonFunctionTarget extends _JsonFunctionTargetBase { final JsonHandler _function; - JsonFunctionTarget._( - this._function, - RequestType Function(Object?) fromJson, - ) : super(fromJson); + JsonFunctionTarget._(this._function, RequestType Function(Object?) fromJson) + : super(fromJson); factory JsonFunctionTarget( JsonHandler function, @@ -56,10 +54,7 @@ abstract class JsonFunctionTarget class _JsonFunctionTarget extends JsonFunctionTarget { - _JsonFunctionTarget( - super.function, - super.fromJson, - ) : super._(); + _JsonFunctionTarget(super.function, super.fromJson) : super._(); @override FutureOr handler(Request request) async { @@ -76,10 +71,7 @@ class _JsonFunctionTarget class _VoidJsonFunctionTarget extends JsonFunctionTarget { - _VoidJsonFunctionTarget( - super.function, - super.fromJson, - ) : super._(); + _VoidJsonFunctionTarget(super.function, super.fromJson) : super._(); @override FutureOr handler(Request request) async { @@ -111,10 +103,7 @@ abstract class JsonWithContextFunctionTarget class _JsonWithContextFunctionTarget extends JsonWithContextFunctionTarget { - _JsonWithContextFunctionTarget( - super.function, - super.fromJson, - ) : super._(); + _JsonWithContextFunctionTarget(super.function, super.fromJson) : super._(); @override FutureOr handler(Request request) async { @@ -127,20 +116,15 @@ class _JsonWithContextFunctionTarget responseJson, headers: context.responseHeaders.isEmpty ? const {contentTypeHeader: jsonContentType} - : { - contentTypeHeader: jsonContentType, - ...context.responseHeaders, - }, + : {contentTypeHeader: jsonContentType, ...context.responseHeaders}, ); } } class _VoidJsonWithContextFunctionTarget extends JsonWithContextFunctionTarget { - _VoidJsonWithContextFunctionTarget( - super.function, - super.fromJson, - ) : super._(); + _VoidJsonWithContextFunctionTarget(super.function, super.fromJson) + : super._(); @override FutureOr handler(Request request) async { diff --git a/functions_framework/lib/src/typedefs.dart b/functions_framework/lib/src/typedefs.dart index 9dc7ea0c..e5d78e25 100644 --- a/functions_framework/lib/src/typedefs.dart +++ b/functions_framework/lib/src/typedefs.dart @@ -25,10 +25,8 @@ typedef CloudEventHandler = FutureOr Function(CloudEvent request); /// The shape of a handler for [CloudEvent] types while also providing a /// [RequestContext]. -typedef CloudEventWithContextHandler = FutureOr Function( - CloudEvent request, - RequestContext context, -); +typedef CloudEventWithContextHandler = + FutureOr Function(CloudEvent request, RequestContext context); /// The shape of a handler that supports a custom [RequestType] and /// [ResponseType]. @@ -40,24 +38,22 @@ typedef CloudEventWithContextHandler = FutureOr Function( /// The [ResponseType] must be either a type compatible with a JSON literal or /// have a `toJson()` function with a returns type compatible with a JSON /// literal. -typedef JsonHandler = FutureOr - Function(RequestType request); +typedef JsonHandler = + FutureOr Function(RequestType request); /// The shape of a handler that supports a custom [RequestType] and /// [ResponseType] and while also providing a [RequestContext]. /// /// See [JsonHandler] for the type requirements for [RequestType] and /// [ResponseType]. -typedef JsonWithContextHandler - = FutureOr Function( - RequestType request, - RequestContext context, -); +typedef JsonWithContextHandler = + FutureOr Function( + RequestType request, + RequestContext context, + ); /// The shape of a basic handler that follows the /// [package:shelf](https://pub.dev/packages/shelf) [Handler] pattern while also /// providing a [RequestLogger]. -typedef HandlerWithLogger = FutureOr Function( - Request request, - RequestLogger logger, -); +typedef HandlerWithLogger = + FutureOr Function(Request request, RequestLogger logger); diff --git a/functions_framework_builder/lib/builder.dart b/functions_framework_builder/lib/builder.dart index a2a3f239..f7ec63e2 100644 --- a/functions_framework_builder/lib/builder.dart +++ b/functions_framework_builder/lib/builder.dart @@ -41,8 +41,8 @@ class _FunctionsFrameworkBuilder implements Builder { @override Map> get buildExtensions => const { - r'lib/functions.dart': ['bin/server.dart'], - }; + r'lib/functions.dart': ['bin/server.dart'], + }; @override Future build(BuildStep buildStep) async { @@ -62,8 +62,9 @@ class _FunctionsFrameworkBuilder implements Builder { final targetReader = annotatedElement.annotation.read('target'); - final targetName = - targetReader.isNull ? element.name : targetReader.stringValue; + final targetName = targetReader.isNull + ? element.name + : targetReader.stringValue; if (entries.containsKey(targetName)) { throw InvalidGenerationSourceError( @@ -90,7 +91,8 @@ class _FunctionsFrameworkBuilder implements Builder { "'${buildStep.inputId.uri}' as $functionsLibraryPrefix", ]..sort(); - var output = ''' + var output = + ''' // GENERATED CODE - DO NOT MODIFY BY HAND // Copyright 2021 Google LLC // @@ -130,10 +132,7 @@ ${cases.join('\n')} } await buildStep.writeAsString( - AssetId( - buildStep.inputId.package, - path.join('bin', 'server.dart'), - ), + AssetId(buildStep.inputId.package, path.join('bin', 'server.dart')), output, ); } diff --git a/functions_framework_builder/lib/src/function_type_validator.dart b/functions_framework_builder/lib/src/function_type_validator.dart index 584ace92..84ce2518 100644 --- a/functions_framework_builder/lib/src/function_type_validator.dart +++ b/functions_framework_builder/lib/src/function_type_validator.dart @@ -35,44 +35,39 @@ class FunctionTypeValidator { return reference; } } - throw InvalidGenerationSourceError( - ''' + throw InvalidGenerationSourceError(''' Not compatible with a supported function shape: ${_types.map((e) => ' ${e.typedefName} [${e.typeDescription}] from ${e.libraryUri}').join('\n')} -''', - element: element, - ); +''', element: element); } static Future create(Resolver resolver) async => - FunctionTypeValidator._( - [ - await SupportedFunctionType.create( - resolver, - 'package:functions_framework/functions_framework.dart', - 'HandlerWithLogger', - 'FunctionTarget.httpWithLogger', - ), - await SupportedFunctionType.create( - resolver, - 'package:shelf/shelf.dart', - 'Handler', - 'FunctionTarget.http', - ), - await SupportedFunctionType.create( - resolver, - 'package:functions_framework/functions_framework.dart', - 'CloudEventWithContextHandler', - 'FunctionTarget.cloudEventWithContext', - ), - await SupportedFunctionType.create( - resolver, - 'package:functions_framework/functions_framework.dart', - 'CloudEventHandler', - 'FunctionTarget.cloudEvent', - ), - await GenericFunctionType.createWithContext(resolver), - await GenericFunctionType.create(resolver), - ], - ); + FunctionTypeValidator._([ + await SupportedFunctionType.create( + resolver, + 'package:functions_framework/functions_framework.dart', + 'HandlerWithLogger', + 'FunctionTarget.httpWithLogger', + ), + await SupportedFunctionType.create( + resolver, + 'package:shelf/shelf.dart', + 'Handler', + 'FunctionTarget.http', + ), + await SupportedFunctionType.create( + resolver, + 'package:functions_framework/functions_framework.dart', + 'CloudEventWithContextHandler', + 'FunctionTarget.cloudEventWithContext', + ), + await SupportedFunctionType.create( + resolver, + 'package:functions_framework/functions_framework.dart', + 'CloudEventHandler', + 'FunctionTarget.cloudEvent', + ), + await GenericFunctionType.createWithContext(resolver), + await GenericFunctionType.create(resolver), + ]); } diff --git a/functions_framework_builder/lib/src/generic_function_type.dart b/functions_framework_builder/lib/src/generic_function_type.dart index 90ab26be..ec3a6cf7 100644 --- a/functions_framework_builder/lib/src/generic_function_type.dart +++ b/functions_framework_builder/lib/src/generic_function_type.dart @@ -151,7 +151,7 @@ class _GenericFactoryData implements FactoryData { final typeDisplayName = info.paramType == null ? jsonTypeDisplay : '$functionsLibraryPrefix.' - '${info.paramType!.toStringNonNullable()}'; + '${info.paramType!.toStringNonNullable()}'; final returnBlock = info.paramType == null ? 'return $_jsonParamName;' @@ -168,7 +168,8 @@ class _GenericFactoryData implements FactoryData { } '''; - final body = ''' + final body = + ''' if ($_jsonParamName is $jsonTypeDisplay) { $returnBlock } @@ -182,11 +183,11 @@ class _GenericFactoryData implements FactoryData { return _GenericFactoryData._( isVoid ? withContext - ? _voidWithContextConstructorName - : _voidConstructorName + ? _voidWithContextConstructorName + : _voidConstructorName : withContext - ? _withContextConstructorName - : _constructorName, + ? _withContextConstructorName + : _constructorName, target, function, typeDisplayName, @@ -195,7 +196,8 @@ class _GenericFactoryData implements FactoryData { } @override - String get expression => ''' + String get expression => + ''' $_endpointConstructorName($function, ($_jsonParamName) { $factoryBody },) diff --git a/functions_framework_builder/lib/src/supported_function_type.dart b/functions_framework_builder/lib/src/supported_function_type.dart index d3a071f1..55faba4f 100644 --- a/functions_framework_builder/lib/src/supported_function_type.dart +++ b/functions_framework_builder/lib/src/supported_function_type.dart @@ -34,8 +34,8 @@ class SupportedFunctionType { this.typedefName, this._type, { String? constructor, - }) : _constructor = constructor, - typeDescription = _type.toStringNonNullable(); + }) : _constructor = constructor, + typeDescription = _type.toStringNonNullable(); static Future create( Resolver resolver, diff --git a/functions_framework_builder/lib/src/valid_json_utils.dart b/functions_framework_builder/lib/src/valid_json_utils.dart index 5119a84b..b666173a 100644 --- a/functions_framework_builder/lib/src/valid_json_utils.dart +++ b/functions_framework_builder/lib/src/valid_json_utils.dart @@ -95,8 +95,10 @@ JsonReturnKind _validJsonReturnTypeCore(DartType type) { // Look for a `toJson` function that returns a JSON-able type if (type is InterfaceType) { - final toJsonMethod = type.element.augmented - .lookUpMethod(name: 'toJson', library: type.element.library); + final toJsonMethod = type.element.augmented.lookUpMethod( + name: 'toJson', + library: type.element.library, + ); if (toJsonMethod != null && toJsonMethod.parameters.every((element) => element.isOptional)) { type = toJsonMethod.returnType; diff --git a/functions_framework_builder/test/builder_test.dart b/functions_framework_builder/test/builder_test.dart index 4a1484b6..e2f0d94a 100644 --- a/functions_framework_builder/test/builder_test.dart +++ b/functions_framework_builder/test/builder_test.dart @@ -71,68 +71,66 @@ FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { test('Valid shelf function shapes are supported', () async { final file = File('test/test_examples/valid_shelf_handlers.dart'); - final lines = [ - 'syncFunction', - 'asyncFunction', - 'futureOrFunction', - 'extraParam', - 'optionalParam', - 'customResponse', - 'customResponseAsync', - 'customResponseFutureOr', - ] - .map( - (e) => """ + final lines = + [ + 'syncFunction', + 'asyncFunction', + 'futureOrFunction', + 'extraParam', + 'optionalParam', + 'customResponse', + 'customResponseAsync', + 'customResponseFutureOr', + ] + .map( + (e) => + """ '$e' => FunctionTarget.http( function_library.$e, ),""", - ) - .join('\n'); - await _generateTest( - file.readAsStringSync(), - ''' + ) + .join('\n'); + await _generateTest(file.readAsStringSync(), ''' $_outputHeader FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { $lines _ => null }; -''', - ); +'''); }); test('Valid CloudEvent function shapes are supported', () async { final file = File('test/test_examples/valid_cloud_event_handlers.dart'); - final lines = [ - 'syncFunction', - 'asyncFunction', - 'futureOrFunction', - 'optionalParam', - 'objectParam', - ] - .map( - (e) => """ + final lines = + [ + 'syncFunction', + 'asyncFunction', + 'futureOrFunction', + 'optionalParam', + 'objectParam', + ] + .map( + (e) => + """ '$e' => FunctionTarget.cloudEvent( function_library.$e, ),""", - ) - .join('\n'); - await _generateTest( - file.readAsStringSync(), - ''' + ) + .join('\n'); + await _generateTest(file.readAsStringSync(), ''' $_outputHeader FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { $lines _ => null }; -''', - ); +'''); }); group('Valid custom type function shapes are supported', () { - final inputContent = - File('test/test_examples/valid_custom_type_handlers.dart') - .readAsStringSync(); + final inputContent = File( + 'test/test_examples/valid_custom_type_handlers.dart', + ).readAsStringSync(); test('void return type', () async { await _testItems( @@ -144,7 +142,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget.voidResult( function_library.$e, (json) { @@ -176,10 +175,7 @@ $lines '(JsonType request) ', '(JsonType request, RequestContext context)', ) - .replaceAll( - 'int? other', - 'RequestContext context, int? other', - ); + .replaceAll('int? other', 'RequestContext context, int? other'); await _testItems( newInputContent, @@ -190,7 +186,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonWithContextFunctionTarget.voidResult( function_library.$e, (json) { @@ -230,7 +227,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget( function_library.$e, (json) { @@ -270,7 +268,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget( function_library.$e, (json) { @@ -310,7 +309,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget( function_library.$e, (json) { @@ -338,9 +338,9 @@ $lines }); group('Valid JSON type function shapes are supported', () { - final inputContent = - File('test/test_examples/valid_json_type_handlers.dart') - .readAsStringSync(); + final inputContent = File( + 'test/test_examples/valid_json_type_handlers.dart', + ).readAsStringSync(); test('void return type', () async { await _testItems( @@ -352,7 +352,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget.voidResult( function_library.$e, (json) { @@ -382,7 +383,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget( function_library.$e, (json) { @@ -413,7 +415,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonFunctionTarget( function_library.$e, (json) { @@ -432,14 +435,8 @@ $lines test('void with context', () async { final newInputContent = inputContent - .replaceAll( - '(num request)', - '(num request, RequestContext context)', - ) - .replaceAll( - 'int? other', - 'RequestContext context, int? other', - ); + .replaceAll('(num request)', '(num request, RequestContext context)') + .replaceAll('int? other', 'RequestContext context, int? other'); await _testItems( newInputContent, @@ -450,7 +447,8 @@ $lines 'extraParam', 'optionalParam', ], - (e) => """ + (e) => + """ '$e' => JsonWithContextFunctionTarget.voidResult( function_library.$e, (json) { @@ -495,9 +493,9 @@ package:$_pkgName/functions.dart:8:10 }); test('freezed style mixed in json types are allowed', () async { - final inputContent = - File('test/test_examples/freezed_style_json_mixin_handler.dart') - .readAsStringSync(); + final inputContent = File( + 'test/test_examples/freezed_style_json_mixin_handler.dart', + ).readAsStringSync(); final srcs = {'$_pkgName|lib/functions.dart': inputContent}; @@ -509,8 +507,9 @@ package:$_pkgName/functions.dart:8:10 }); group('invalid function shapes are not allowed', () { - final onlyFunctionMatcher = - startsWith('Only top-level, public functions are supported.'); + final onlyFunctionMatcher = startsWith( + 'Only top-level, public functions are supported.', + ); final notCompatibleMatcher = startsWith( 'Not compatible with a supported function shape:', ); @@ -527,8 +526,8 @@ package:$_pkgName/functions.dart:8:10 // '@CloudFunction() Response function(Request request) => null;': startsWith( - 'Cannot be annotated with `CloudFunction` more than once.', - ), + 'Cannot be annotated with `CloudFunction` more than once.', + ), // // pkg:shelf handlers @@ -601,16 +600,13 @@ Future _testItems( ) async { final entries = functions.map((e) => entryFactory(e)).join('\n'); - await _generateTest( - inputContent, - ''' + await _generateTest(inputContent, ''' $_outputHeader FunctionTarget? _nameToFunctionTarget(String name) => switch (name) { $entries _ => null }; -''', - ); +'''); } Future _generateTest( @@ -623,15 +619,10 @@ Future _generateTest( await testBuilder( functionsFrameworkBuilder(), srcs, - generateFor: { - ...srcs.keys, - '$_pkgName|\$package\$', - }, + generateFor: {...srcs.keys, '$_pkgName|\$package\$'}, outputs: expectedContent == null ? null - : { - '$_pkgName|bin/server.dart': decodedMatches(expectedContent), - }, + : {'$_pkgName|bin/server.dart': decodedMatches(expectedContent)}, onLog: (log) { if (!validateLog) { return; @@ -661,7 +652,8 @@ const _ignoredLogMessages = { String get _pkgName => 'pkg$_pkgCacheCount'; int _pkgCacheCount = 1; -String get _outputHeader => ''' +String get _outputHeader => + ''' // GENERATED CODE - DO NOT MODIFY BY HAND // Copyright 2021 Google LLC // diff --git a/google_cloud/example/example.dart b/google_cloud/example/example.dart index 5c913005..f8c72e62 100644 --- a/google_cloud/example/example.dart +++ b/google_cloud/example/example.dart @@ -39,12 +39,10 @@ class _Server { } if (projectId == null) { - throw BadConfigurationException( - ''' + throw BadConfigurationException(''' Could not contact GCP metadata server or find the project-id in one of these environment variables: - ${gcpProjectIdEnvironmentVariables.join('\n ')}''', - ); + ${gcpProjectIdEnvironmentVariables.join('\n ')}'''); } print('Current GCP project id: $projectId'); @@ -61,10 +59,9 @@ environment variables: final bool hosted; late final FirestoreApi api = FirestoreApi(client); - late final handler = - createLoggingMiddleware(projectId: hosted ? projectId : null) - .addMiddleware(_onlyGetRootMiddleware) - .addHandler(_incrementHandler); + late final handler = createLoggingMiddleware( + projectId: hosted ? projectId : null, + ).addMiddleware(_onlyGetRootMiddleware).addHandler(_incrementHandler); Future _incrementHandler(Request request) async { final result = await api.projects.databases.documents.commit( @@ -85,26 +82,26 @@ environment variables: /// For `GET` `request` objects to [handler], otherwise sends a 404. Handler _onlyGetRootMiddleware(Handler handler) => (Request request) async { - if (request.method == 'GET' && request.url.pathSegments.isEmpty) { - return await handler(request); - } + if (request.method == 'GET' && request.url.pathSegments.isEmpty) { + return await handler(request); + } - throw BadRequestException(404, 'Not found'); - }; + throw BadRequestException(404, 'Not found'); +}; CommitRequest _incrementRequest(String projectId) => CommitRequest( - writes: [ - Write( - transform: DocumentTransform( - document: - 'projects/$projectId/databases/(default)/documents/settings/count', - fieldTransforms: [ - FieldTransform( - fieldPath: 'count', - increment: Value(integerValue: '1'), - ), - ], + writes: [ + Write( + transform: DocumentTransform( + document: + 'projects/$projectId/databases/(default)/documents/settings/count', + fieldTransforms: [ + FieldTransform( + fieldPath: 'count', + increment: Value(integerValue: '1'), ), - ), - ], - ); + ], + ), + ), + ], +); diff --git a/google_cloud/lib/src/gcp_project.dart b/google_cloud/lib/src/gcp_project.dart index ef92a9cc..525eba59 100644 --- a/google_cloud/lib/src/gcp_project.dart +++ b/google_cloud/lib/src/gcp_project.dart @@ -76,15 +76,12 @@ Future projectIdFromMetadataServer() async { return response.body; } on SocketException catch (e) { - throw BadConfigurationException( - ''' + throw BadConfigurationException(''' Could not connect to $host. If not running on Google Cloud, one of these environment variables must be set to the target Google Project ID: ${gcpProjectIdEnvironmentVariables.join('\n')} -''', - details: e.toString(), - ); +''', details: e.toString()); } } diff --git a/google_cloud/lib/src/logging.dart b/google_cloud/lib/src/logging.dart index 21a78528..d666d4f2 100644 --- a/google_cloud/lib/src/logging.dart +++ b/google_cloud/lib/src/logging.dart @@ -52,45 +52,43 @@ Middleware createLoggingMiddleware({String? projectId}) => projectId == null Middleware get badRequestMiddleware => _handleBadRequest; Handler _handleBadRequest(Handler innerHandler) => (request) async { - try { - final response = await innerHandler(request); - return response; - } on BadRequestException catch (error, stack) { - return _responseFromBadRequest(error, stack); - } - }; + try { + final response = await innerHandler(request); + return response; + } on BadRequestException catch (error, stack) { + return _responseFromBadRequest(error, stack); + } +}; Handler _errorWriter(Handler innerHandler) => (request) async { - final response = await innerHandler(request); + final response = await innerHandler(request); - final error = - response.context['bad_request_exception'] as BadRequestException?; + final error = + response.context['bad_request_exception'] as BadRequestException?; - if (error != null) { - final stack = response.context['bad_stack_trace'] as StackTrace?; - final output = [ - error, - if (error.innerError != null) - '${error.innerError} (${error.innerError.runtimeType})', - _fromStackTrace(error.innerStack ?? stack), - ]; + if (error != null) { + final stack = response.context['bad_stack_trace'] as StackTrace?; + final output = [ + error, + if (error.innerError != null) + '${error.innerError} (${error.innerError.runtimeType})', + _fromStackTrace(error.innerStack ?? stack), + ]; - final bob = - output.expand((e) => LineSplitter.split('$e'.trim())).join('\n'); + final bob = output + .expand((e) => LineSplitter.split('$e'.trim())) + .join('\n'); - stderr.writeln(lightRed.wrap(bob)); - } - return response; - }; + stderr.writeln(lightRed.wrap(bob)); + } + return response; +}; Response _responseFromBadRequest(BadRequestException e, StackTrace stack) => Response( e.statusCode, body: 'Bad request. ${e.message}', - context: { - 'bad_request_exception': e, - 'bad_stack_trace': stack, - }, + context: {'bad_request_exception': e, 'bad_stack_trace': stack}, ); /// Used to represent the [RequestLogger] in [Zone] values. @@ -102,42 +100,42 @@ final _loggerKey = Object(); /// All other logs messages are logged as text logs (`textPayload`). Middleware cloudLoggingMiddleware(String projectId) { Handler hostedLoggingMiddleware(Handler innerHandler) => (request) async { - // Add log correlation to nest all log messages beneath request log in - // Log Viewer. + // Add log correlation to nest all log messages beneath request log in + // Log Viewer. - String? traceValue; + String? traceValue; - final traceHeader = request.headers[cloudTraceContextHeader]; - if (traceHeader != null) { - traceValue = - 'projects/$projectId/traces/${traceHeader.split('/')[0]}'; - } + final traceHeader = request.headers[cloudTraceContextHeader]; + if (traceHeader != null) { + traceValue = 'projects/$projectId/traces/${traceHeader.split('/')[0]}'; + } - String createErrorLogEntry( - Object error, - StackTrace? stackTrace, - LogSeverity logSeverity, - ) { - // Collect and format error information as described here - // https://cloud.google.com/functions/docs/monitoring/logging#writing_structured_logs + String createErrorLogEntry( + Object error, + StackTrace? stackTrace, + LogSeverity logSeverity, + ) { + // Collect and format error information as described here + // https://cloud.google.com/functions/docs/monitoring/logging#writing_structured_logs - final chain = _fromStackTrace(stackTrace); + final chain = _fromStackTrace(stackTrace); - final stackFrame = chain.traces.firstOrNull?.frames.firstOrNull; + final stackFrame = chain.traces.firstOrNull?.frames.firstOrNull; - return _createLogEntry( - traceValue, - '$error\n$chain'.trim(), - logSeverity, - stackFrame: stackFrame, - ); - } + return _createLogEntry( + traceValue, + '$error\n$chain'.trim(), + logSeverity, + stackFrame: stackFrame, + ); + } - final completer = Completer.sync(); + final completer = Completer.sync(); - final currentZone = Zone.current; + final currentZone = Zone.current; - Zone.current.fork( + Zone.current + .fork( zoneValues: {_loggerKey: _CloudLogger(currentZone, traceValue)}, specification: ZoneSpecification( handleUncaughtError: (self, parent, zone, error, stackTrace) { @@ -151,11 +149,7 @@ Middleware cloudLoggingMiddleware(String projectId) { error.innerStack ?? stackTrace, LogSeverity.warning, ) - : createErrorLogEntry( - error, - stackTrace, - LogSeverity.error, - ); + : createErrorLogEntry(error, stackTrace, LogSeverity.error); // Serialize to a JSON string and output. parent.print(self, logContentString); @@ -181,29 +175,28 @@ Middleware cloudLoggingMiddleware(String projectId) { parent.print(self, logContent); }, ), - ).runGuarded( - () async { - final response = await innerHandler(request); - if (!completer.isCompleted) { - completer.complete(response); - } - }, - ); - - return completer.future; - }; + ) + .runGuarded(() async { + final response = await innerHandler(request); + if (!completer.isCompleted) { + completer.complete(response); + } + }); + + return completer.future; + }; return hostedLoggingMiddleware; } // https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogEntrySourceLocation Map _sourceLocation(Frame frame) => { - // TODO: Will need to fix `package:` URIs to file paths when possible - // GoogleCloudPlatform/functions-framework-dart#40 - 'file': frame.library, - if (frame.line != null) 'line': frame.line.toString(), - 'function': frame.member, - }; + // TODO: Will need to fix `package:` URIs to file paths when possible + // GoogleCloudPlatform/functions-framework-dart#40 + 'file': frame.library, + if (frame.line != null) 'line': frame.line.toString(), + 'function': frame.member, +}; /// A [RequestLogger] that prints messages normally. /// @@ -232,12 +225,8 @@ class _CloudLogger extends RequestLogger { @override void log(Object message, LogSeverity severity) => _zone.print( - _createLogEntry( - _traceId, - message is Map ? message : '$message', - severity, - ), - ); + _createLogEntry(_traceId, message is Map ? message : '$message', severity), + ); } String _createLogEntry( @@ -258,11 +247,9 @@ String _createLogEntry( return jsonEncode(logContent); } -Chain _fromStackTrace( - StackTrace? stackTrace, -) => +Chain _fromStackTrace(StackTrace? stackTrace) => (stackTrace == null ? Chain.current() : Chain.forTrace(stackTrace)) .foldFrames( - (f) => f.isCore || f.package == 'gcp' || f.package == 'shelf', - terse: true, - ); + (f) => f.isCore || f.package == 'gcp' || f.package == 'shelf', + terse: true, + ); diff --git a/google_cloud/test/gcp_test.dart b/google_cloud/test/gcp_test.dart index dd8f65c3..ac84942d 100644 --- a/google_cloud/test/gcp_test.dart +++ b/google_cloud/test/gcp_test.dart @@ -22,21 +22,23 @@ void main() { group('currentProjectId', () { const projectIdPrint = 'test/src/project_id_print.dart'; - test('not environment', onPlatform: { - 'windows': const Skip('Cannot validate tests on windows.'), - }, () async { - final proc = await _run(projectIdPrint); + test( + 'not environment', + onPlatform: {'windows': const Skip('Cannot validate tests on windows.')}, + () async { + final proc = await _run(projectIdPrint); - final errorOut = await proc.stderrStream().toList(); + final errorOut = await proc.stderrStream().toList(); - await expectLater( - errorOut, - containsAll(gcpProjectIdEnvironmentVariables), - ); - await expectLater(proc.stdout, emitsDone); + await expectLater( + errorOut, + containsAll(gcpProjectIdEnvironmentVariables), + ); + await expectLater(proc.stdout, emitsDone); - await proc.shouldExit(255); - }); + await proc.shouldExit(255); + }, + ); test('environment set', () async { final proc = await _run( @@ -74,10 +76,7 @@ void main() { ); test('environment set', () async { - final proc = await _run( - listenPortPrint, - environment: {'PORT': '8123'}, - ); + final proc = await _run(listenPortPrint, environment: {'PORT': '8123'}); await expectLater(proc.stderr, emitsDone); await expectLater(proc.stdout, emits('8123')); @@ -138,10 +137,9 @@ void main() { Future _run( String dartScript, { Map? environment, -}) => - TestProcess.start( - Platform.resolvedExecutable, - [dartScript], - environment: environment, - includeParentEnvironment: false, - ); +}) => TestProcess.start( + Platform.resolvedExecutable, + [dartScript], + environment: environment, + includeParentEnvironment: false, +); diff --git a/integration_test/lib/functions.dart b/integration_test/lib/functions.dart index 5d64a2c9..a3d245f8 100644 --- a/integration_test/lib/functions.dart +++ b/integration_test/lib/functions.dart @@ -73,10 +73,7 @@ Future function(Request request) async { 'environment': Platform.environment, }; - return Response.ok( - encodeJsonPretty(output), - headers: _jsonHeaders, - ); + return Response.ok(encodeJsonPretty(output), headers: _jsonHeaders); } if (urlPath.startsWith('exception')) { @@ -133,8 +130,11 @@ void basicCloudEventHandler(CloudEvent event, RequestContext context) { final pubSub = PubSub.fromJson(event.data as Map); - context.responseHeaders['x-attribute_count'] = - pubSub.message.attributes.length.toString(); + context.responseHeaders['x-attribute_count'] = pubSub + .message + .attributes + .length + .toString(); stderr.writeln(encodeJsonPretty(event)); } @@ -145,8 +145,8 @@ void protoEventHandler(CloudEvent event, RequestContext context) { context.logger.debug(context.request.headers); - context.responseHeaders['x-data-runtime-types'] = - event.data.runtimeType.toString(); + context.responseHeaders['x-data-runtime-types'] = event.data.runtimeType + .toString(); stderr.writeln(encodeJsonPretty(event)); } diff --git a/integration_test/lib/src/conformance_handlers.dart b/integration_test/lib/src/conformance_handlers.dart index 85617de8..64a19f17 100644 --- a/integration_test/lib/src/conformance_handlers.dart +++ b/integration_test/lib/src/conformance_handlers.dart @@ -22,9 +22,7 @@ import 'utils.dart'; Future conformanceHttp(Request request) async { final content = await request.readAsString(); - File('function_output.json').writeAsStringSync( - content, - ); + File('function_output.json').writeAsStringSync(content); final buffer = StringBuffer() ..writeln('Hello, conformance test!') @@ -41,9 +39,7 @@ Future conformanceHttp(Request request) async { @CloudFunction() void conformanceCloudEvent(CloudEvent event) { final eventEncoded = encodeJsonPretty(event); - File('function_output.json').writeAsStringSync( - eventEncoded, - ); + File('function_output.json').writeAsStringSync(eventEncoded); final buffer = StringBuffer() ..writeln('Hello, conformance test!') diff --git a/integration_test/lib/src/pub_sub_types.g.dart b/integration_test/lib/src/pub_sub_types.g.dart index 52d80a17..b88bfd4c 100644 --- a/integration_test/lib/src/pub_sub_types.g.dart +++ b/integration_test/lib/src/pub_sub_types.g.dart @@ -7,14 +7,14 @@ part of 'pub_sub_types.dart'; // ************************************************************************** PubSub _$PubSubFromJson(Map json) => PubSub( - PubSubMessage.fromJson(json['message'] as Map), - json['subscription'] as String, - ); + PubSubMessage.fromJson(json['message'] as Map), + json['subscription'] as String, +); Map _$PubSubToJson(PubSub instance) => { - 'message': instance.message, - 'subscription': instance.subscription, - }; + 'message': instance.message, + 'subscription': instance.subscription, +}; PubSubMessage _$PubSubMessageFromJson(Map json) => PubSubMessage( diff --git a/integration_test/test/cli_test.dart b/integration_test/test/cli_test.dart index 6a82a8f4..ea4afa23 100644 --- a/integration_test/test/cli_test.dart +++ b/integration_test/test/cli_test.dart @@ -76,9 +76,7 @@ void main() { const port = 8888; final proc = await startServerTest( expectedListeningPort: port, - env: { - 'PORT': port.toString(), - }, + env: {'PORT': port.toString()}, ); final response = await get('http://localhost:$port'); @@ -91,9 +89,7 @@ void main() { test('bad FUNCTION_TARGET', () async { final proc = await startServerTest( shouldFail: true, - env: { - 'FUNCTION_TARGET': 'bob', - }, + env: {'FUNCTION_TARGET': 'bob'}, ); await expectLater( @@ -109,9 +105,7 @@ void main() { test('bad FUNCTION_SIGNATURE_TYPE', () async { final proc = await startServerTest( shouldFail: true, - env: { - 'FUNCTION_SIGNATURE_TYPE': 'bob', - }, + env: {'FUNCTION_SIGNATURE_TYPE': 'bob'}, ); await expectLater( @@ -128,9 +122,7 @@ void main() { test('bad PORT', () async { final proc = await startServerTest( shouldFail: true, - env: { - 'PORT': 'bob', - }, + env: {'PORT': 'bob'}, ); await expectLater( @@ -149,9 +141,7 @@ void main() { test('unsupported option', () async { final proc = await startServerTest( shouldFail: true, - arguments: [ - '--bob', - ], + arguments: ['--bob'], ); await expectLater( @@ -168,10 +158,7 @@ void main() { test('bad target', () async { final proc = await startServerTest( shouldFail: true, - arguments: [ - '--target', - 'bob', - ], + arguments: ['--target', 'bob'], ); await expectLater( @@ -230,10 +217,7 @@ void main() { ], ); - await expectLater( - proc.stdout, - emitsInOrder([emitsDone]), - ); + await expectLater(proc.stdout, emitsInOrder([emitsDone])); await expectLater( proc.stderr, emitsInOrder([ diff --git a/integration_test/test/cloud_behavior_test.dart b/integration_test/test/cloud_behavior_test.dart index 9c2d08cd..6ad0392e 100644 --- a/integration_test/test/cloud_behavior_test.dart +++ b/integration_test/test/cloud_behavior_test.dart @@ -90,15 +90,12 @@ void main() { }) { final map = jsonDecode(entry) as Map; - expect( - map, - { - 'message': message, - 'severity': severity.name, - 'logging.googleapis.com/trace': - 'projects/test_project_id/traces/$traceStart', - }, - ); + expect(map, { + 'message': message, + 'severity': severity.name, + 'logging.googleapis.com/trace': + 'projects/test_project_id/traces/$traceStart', + }); } void validateCloudErrorOutput( @@ -111,13 +108,7 @@ void main() { }) { expect(map, hasLength(4)); expect(map, containsPair('severity', severity)); - expect( - map, - containsPair( - 'message', - messageMatcher, - ), - ); + expect(map, containsPair('message', messageMatcher)); expect( map, containsPair( @@ -129,13 +120,7 @@ void main() { final sourceLocation = map['logging.googleapis.com/sourceLocation'] as Map; - expect( - sourceLocation, - containsPair( - 'file', - fileMatcher, - ), - ); + expect(sourceLocation, containsPair('file', fileMatcher)); if (containsLine) { expect( @@ -154,9 +139,7 @@ void main() { group('cloud event', () { setUp(() async { await doSetup( - FunctionTarget.cloudEventWithContext( - basicCloudEventHandler, - ), + FunctionTarget.cloudEventWithContext(basicCloudEventHandler), ); }); @@ -221,7 +204,8 @@ void main() { } } }''', - expectedBody: 'Bad request. Could not decode the request as a ' + expectedBody: + 'Bad request. Could not decode the request as a ' 'structured-mode message.', ); @@ -315,9 +299,7 @@ void main() { validateCloudErrorOutput( jsonDecode(lines[1]) as Map, - startsWith( - 'Bad state: async error', - ), + startsWith('Bad state: async error'), 'package:hello_world_function_test/functions.dart', 'function.', ); @@ -328,9 +310,7 @@ void main() { group('logging', () { setUp(() async { - await doSetup( - FunctionTarget.httpWithLogger(loggingHandler), - ); + await doSetup(FunctionTarget.httpWithLogger(loggingHandler)); }); Future doGet( diff --git a/integration_test/test/cloud_event_test.dart b/integration_test/test/cloud_event_test.dart index d2f26bc6..70d055ee 100644 --- a/integration_test/test/cloud_event_test.dart +++ b/integration_test/test/cloud_event_test.dart @@ -36,7 +36,8 @@ const _pubSubJsonString = r''' } }'''; -final _realHeaders = (jsonDecode(r''' +final _realHeaders = + (jsonDecode(r''' { "accept": "application/json", "accept-encoding": "gzip,deflate,br", @@ -53,7 +54,9 @@ final _realHeaders = (jsonDecode(r''' "x-cloud-trace-context": "99f400597336e627f680986c0835f115/10739301396915309367;o=1", "x-forwarded-for": "66.102.6.169", "x-forwarded-proto": "https" -}''') as Map).cast(); +}''') + as Map) + .cast(); void main() { // TODO: non-JSON body @@ -69,54 +72,42 @@ void main() { expect(response.body, isEmpty); expect( response.headers, - allOf( - containsTextPlainHeader, - containsPair('x-attribute_count', '1'), - ), + allOf(containsTextPlainHeader, containsPair('x-attribute_count', '1')), ); - await finishServerTest( - proc, - requestOutput: endsWith('POST [200] /'), - ); + await finishServerTest(proc, requestOutput: endsWith('POST [200] /')); final stderrOutput = await proc.stderrStream().join('\n'); final json = jsonDecode(stderrOutput) as Map; - expect( - json, - { - 'id': '1999507485604232', - 'specversion': '1.0', - 'type': 'google.cloud.pubsub.topic.v1.messagePublished', - 'datacontenttype': 'application/json; charset=utf-8', - 'time': '2021-02-10T18:13:19.698Z', - 'source': - '//pubsub.googleapis.com/projects/redacted/topics/eventarc-us-central1-events-pubsub-trigger-072', - 'data': jsonDecode(_pubSubJsonString), - }, - ); + expect(json, { + 'id': '1999507485604232', + 'specversion': '1.0', + 'type': 'google.cloud.pubsub.topic.v1.messagePublished', + 'datacontenttype': 'application/json; charset=utf-8', + 'time': '2021-02-10T18:13:19.698Z', + 'source': + '//pubsub.googleapis.com/projects/redacted/topics/eventarc-us-central1-events-pubsub-trigger-072', + 'data': jsonDecode(_pubSubJsonString), + }); }); test('valid proto input', () async { final proc = await _hostBasicEventHandler('protoEventHandler'); const subject = 'documents/users/ghXNtePIFmdDOBH3iEMH'; - final response = await _makeRequest( - _protobytes, - { - 'ce-id': '785865c0-2b16-439b-ad68-f9672343863a', - 'ce-source': - '//firestore.googleapis.com/projects/dart-redirector/databases/(default)', - 'ce-specversion': '1.0', - 'ce-type': 'google.cloud.firestore.document.v1.updated', - 'Content-Type': 'application/protobuf', - 'ce-dataschema': - 'https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/firestore/v1/data.proto', - 'ce-subject': subject, - 'ce-time': '2023-06-21T12:21:25.413855Z', - }, - ); + final response = await _makeRequest(_protobytes, { + 'ce-id': '785865c0-2b16-439b-ad68-f9672343863a', + 'ce-source': + '//firestore.googleapis.com/projects/dart-redirector/databases/(default)', + 'ce-specversion': '1.0', + 'ce-type': 'google.cloud.firestore.document.v1.updated', + 'Content-Type': 'application/protobuf', + 'ce-dataschema': + 'https://github.com/googleapis/google-cloudevents/blob/main/proto/google/events/cloud/firestore/v1/data.proto', + 'ce-subject': subject, + 'ce-time': '2023-06-21T12:21:25.413855Z', + }); expect(response.statusCode, 200); expect(response.body, isEmpty); expect( @@ -128,18 +119,13 @@ void main() { ); await expectLater( proc.stdout, - emitsInOrder( - [ - startsWith('INFO: event subject: $subject'), - startsWith('DEBUG:'), - ], - ), + emitsInOrder([ + startsWith('INFO: event subject: $subject'), + startsWith('DEBUG:'), + ]), ); - await finishServerTest( - proc, - requestOutput: endsWith('POST [200] /'), - ); + await finishServerTest(proc, requestOutput: endsWith('POST [200] /')); final stderrOutput = await proc.stderrStream().join('\n'); final json = jsonDecode(stderrOutput) as Map; @@ -160,18 +146,14 @@ void main() { }); test('bad format of core header: time', () async { - final stderrOutput = await _makeBadRequest( - _pubSubJsonString, - { - ...jsonContentType, - 'ce-specversion': '1.0', - 'ce-type': 'google.cloud.pubsub.topic.publish', - 'ce-time': 'bad time!', - 'ce-id': '1234-1234-1234', - 'ce-source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', - }, - 'binary-mode message', - ); + final stderrOutput = await _makeBadRequest(_pubSubJsonString, { + ...jsonContentType, + 'ce-specversion': '1.0', + 'ce-type': 'google.cloud.pubsub.topic.publish', + 'ce-time': 'bad time!', + 'ce-id': '1234-1234-1234', + 'ce-source': 'urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66', + }, 'binary-mode message'); expect( stderrOutput, startsWith( @@ -209,14 +191,15 @@ void main() { expect( stderrOutput, startsWith( - // NOTE! Since binary-mode failed, we fallback to structured mode! - ''' + // NOTE! Since binary-mode failed, we fallback to structured mode! + ''' Could not decode the request as a structured-mode message. (400) CheckedFromJsonException Could not create `CloudEvent`. There is a problem with "id". Required keys are missing: id, source, specversion, type. (CheckedFromJsonException) -'''), +''', + ), ); }); }); @@ -250,28 +233,19 @@ Required keys are missing: id, source, specversion, type. (CheckedFromJsonExcept expect(response.body, isEmpty); expect( response.headers, - allOf( - containsTextPlainHeader, - containsPair('x-attribute_count', '1'), - ), + allOf(containsTextPlainHeader, containsPair('x-attribute_count', '1')), ); - await finishServerTest( - proc, - requestOutput: endsWith('POST [200] /'), - ); + await finishServerTest(proc, requestOutput: endsWith('POST [200] /')); final stderrOutput = await proc.stderrStream().join('\n'); final json = jsonDecode(stderrOutput) as Map; - expect( - json, - { - ...jsonDecode(body) as Map, - 'datacontenttype': 'application/json; charset=utf-8', - }, - ); + expect(json, { + ...jsonDecode(body) as Map, + 'datacontenttype': 'application/json; charset=utf-8', + }); }); test('bad format of core header: time', () async { @@ -294,9 +268,7 @@ Required keys are missing: id, source, specversion, type. (CheckedFromJsonExcept } } }''', - { - 'Content-Type': 'application/json; charset=utf-8', - }, + {'Content-Type': 'application/json; charset=utf-8'}, 'structured-mode message', ); expect( @@ -330,9 +302,7 @@ Required keys are missing: id, source, specversion, type. (CheckedFromJsonExcept } } }''', - { - 'Content-Type': 'application/json; charset=utf-8', - }, + {'Content-Type': 'application/json; charset=utf-8'}, 'structured-mode message', ); expect( @@ -363,10 +333,7 @@ Future _makeBadRequest( reason: 'response.body', ); - await finishServerTest( - proc, - requestOutput: endsWith('POST [400] /'), - ); + await finishServerTest(proc, requestOutput: endsWith('POST [400] /')); final stderrOutput = await proc.stderrStream().join('\n'); return stderrOutput; @@ -375,11 +342,7 @@ Future _makeBadRequest( Future _makeRequest(Object? body, Map headers) async { final requestUrl = 'http://localhost:$autoPort/'; - final response = await post( - requestUrl, - body: body, - headers: headers, - ); + final response = await post(requestUrl, body: body, headers: headers); return response; } @@ -387,12 +350,7 @@ Future _hostBasicEventHandler([ String name = 'basicCloudEventHandler', ]) async { final proc = await startServerTest( - arguments: [ - '--target', - name, - '--signature-type', - 'cloudevent', - ], + arguments: ['--target', name, '--signature-type', 'cloudevent'], expectedListeningPort: 0, ); return proc; diff --git a/integration_test/test/custom_type_test.dart b/integration_test/test/custom_type_test.dart index 8c7ce7c5..cf64722d 100644 --- a/integration_test/test/custom_type_test.dart +++ b/integration_test/test/custom_type_test.dart @@ -33,14 +33,8 @@ void main() { Object? extraPrintMatcher, }) async { expect(response.statusCode, 400); - expect( - response.headers, - containsTextPlainHeader, - ); - expect( - response.body, - 'Bad request. $errorMessage', - ); + expect(response.headers, containsTextPlainHeader); + expect(response.body, 'Bad request. $errorMessage'); await expectLater( testProcess.stderr, @@ -61,9 +55,7 @@ void main() { final requestUrl = 'http://localhost:$autoPort/'; final response = await post( requestUrl, - headers: { - 'Content-Type': 'application/text', - }, + headers: {'Content-Type': 'application/text'}, body: '{"a":1}', ); await expectInvalid( @@ -121,12 +113,7 @@ void main() { headers: jsonContentType, body: jsonEncode( PubSub( - PubSubMessage( - 'data', - 'messageId', - DateTime.now(), - {}, - ), + PubSubMessage('data', 'messageId', DateTime.now(), {}), subscription, ), ), @@ -205,10 +192,7 @@ void main() { await finishServerTest( testProcess, - requestOutput: emitsInOrder([ - 'Keys: a', - endsWith('POST [200] /'), - ]), + requestOutput: emitsInOrder(['Keys: a', endsWith('POST [200] /')]), ); }); @@ -233,10 +217,7 @@ void main() { await finishServerTest( testProcess, - requestOutput: emitsInOrder([ - 'Keys: ', - endsWith('POST [200] /'), - ]), + requestOutput: emitsInOrder(['Keys: ', endsWith('POST [200] /')]), ); }); }); diff --git a/integration_test/test/function_test.dart b/integration_test/test/function_test.dart index b96bb14f..d6e48927 100644 --- a/integration_test/test/function_test.dart +++ b/integration_test/test/function_test.dart @@ -75,14 +75,12 @@ void main() { await finishServerTest( proc, - requestOutput: emitsInOrder( - [ - 'print', - 'something', - 'here', - endsWith('GET [200] /$requestedPath'), - ], - ), + requestOutput: emitsInOrder([ + 'print', + 'something', + 'here', + endsWith('GET [200] /$requestedPath'), + ]), ); }); @@ -123,9 +121,7 @@ void main() { await finishServerTest( proc, - requestOutput: emitsInOrder([ - endsWith('GET [400] /exception'), - ]), + requestOutput: emitsInOrder([endsWith('GET [400] /exception')]), ); }); diff --git a/integration_test/test/logging_test.dart b/integration_test/test/logging_test.dart index 2993e854..4939b58a 100644 --- a/integration_test/test/logging_test.dart +++ b/integration_test/test/logging_test.dart @@ -18,12 +18,9 @@ import 'package:test_process/test_process.dart'; import 'src/test_utils.dart'; Future _startServerTest() => startServerTest( - arguments: [ - '--target', - 'loggingHandler', - ], - expectedListeningPort: 0, - ); + arguments: ['--target', 'loggingHandler'], + expectedListeningPort: 0, +); void main() { test('test all log severities', () async { @@ -36,20 +33,18 @@ void main() { await finishServerTest( proc, - requestOutput: emitsInOrder( - [ - 'default', - 'DEBUG: debug', - 'INFO: info', - 'NOTICE: notice', - 'WARNING: warning', - 'ERROR: error', - 'CRITICAL: critical', - 'ALERT: alert', - 'EMERGENCY: emergency', - endsWith('GET [200] /'), - ], - ), + requestOutput: emitsInOrder([ + 'default', + 'DEBUG: debug', + 'INFO: info', + 'NOTICE: notice', + 'WARNING: warning', + 'ERROR: error', + 'CRITICAL: critical', + 'ALERT: alert', + 'EMERGENCY: emergency', + endsWith('GET [200] /'), + ]), ); }); } diff --git a/integration_test/test/src/test_utils.dart b/integration_test/test/src/test_utils.dart index 776720fb..4313ac55 100644 --- a/integration_test/test/src/test_utils.dart +++ b/integration_test/test/src/test_utils.dart @@ -18,9 +18,7 @@ import 'package:http/http.dart' as http; import 'package:test/test.dart'; import 'package:test_process/test_process.dart'; -const jsonContentType = { - 'Content-Type': 'application/json; charset=utf-8', -}; +const jsonContentType = {'Content-Type': 'application/json; charset=utf-8'}; Future get(Object url, {Map? headers}) => http.get(url is String ? Uri.parse(url) : url as Uri, headers: headers); @@ -29,12 +27,11 @@ Future post( Object url, { Map? headers, Object? body, -}) => - http.post( - url is String ? Uri.parse(url) : url as Uri, - headers: headers, - body: body, - ); +}) => http.post( + url is String ? Uri.parse(url) : url as Uri, + headers: headers, + body: body, +); const defaultPort = 8080; @@ -103,5 +100,7 @@ Future finishServerTest( ); } -final containsTextPlainHeader = - containsPair('content-type', 'text/plain; charset=utf-8'); +final containsTextPlainHeader = containsPair( + 'content-type', + 'text/plain; charset=utf-8', +); From e89175a652cc95a8ed949cc21c0fadf8e35b3914 Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Fri, 1 Aug 2025 14:32:48 -0700 Subject: [PATCH 4/5] generate --- dartfn/lib/src/generators/cloudevent.g.dart | 2 +- dartfn/lib/src/generators/helloworld.g.dart | 2 +- dartfn/lib/src/generators/json.g.dart | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dartfn/lib/src/generators/cloudevent.g.dart b/dartfn/lib/src/generators/cloudevent.g.dart index 163b0c70..ec9bdda2 100644 --- a/dartfn/lib/src/generators/cloudevent.g.dart +++ b/dartfn/lib/src/generators/cloudevent.g.dart @@ -163,7 +163,7 @@ aXR5JzogTG9nU2V2ZXJpdHkuaW5mbywKICAgICAgfSwKICAgICksCiAgKTsKfQo=''', bmFtZTogX19wcm9qZWN0TmFtZV9fCmRlc2NyaXB0aW9uOiBBIHNhbXBsZSBGdW5jdGlvbnMgRnJh bWV3b3JrIHByb2plY3QgZm9yIGhhbmRsaW5nIGEgY2xvdWRldmVudC4KIyB2ZXJzaW9uOiAwLjEu MAojIGhvbWVwYWdlOiBodHRwczovL3d3dy5leGFtcGxlLmNvbQpwdWJsaXNoX3RvOiBub25lCgpl -bnZpcm9ubWVudDoKICBzZGs6IF4zLjYuMAoKZGVwZW5kZW5jaWVzOgogIGZ1bmN0aW9uc19mcmFt +bnZpcm9ubWVudDoKICBzZGs6IF4zLjguMAoKZGVwZW5kZW5jaWVzOgogIGZ1bmN0aW9uc19mcmFt ZXdvcms6IF4wLjQuMAogIHNoZWxmOiBeMS4wLjAKCmRldl9kZXBlbmRlbmNpZXM6CiAgYnVpbGRf cnVubmVyOiBeMi4wLjAKICBmdW5jdGlvbnNfZnJhbWV3b3JrX2J1aWxkZXI6IF4wLjQuMQogIGh0 dHA6IF4xLjAuMAogIGRhcnRfZmx1dHRlcl90ZWFtX2xpbnRzOiBeMy4wLjAKICB0ZXN0OiBeMS4x diff --git a/dartfn/lib/src/generators/helloworld.g.dart b/dartfn/lib/src/generators/helloworld.g.dart index e669f9ca..996866c3 100644 --- a/dartfn/lib/src/generators/helloworld.g.dart +++ b/dartfn/lib/src/generators/helloworld.g.dart @@ -151,7 +151,7 @@ bywgV29ybGQhJyk7Cg==''', bmFtZTogX19wcm9qZWN0TmFtZV9fCmRlc2NyaXB0aW9uOiBBIHNhbXBsZSAiSGVsbG8sIFdvcmxk ISIgRnVuY3Rpb25zIEZyYW1ld29yayBwcm9qZWN0LgojIHZlcnNpb246IDAuMS4wCiMgaG9tZXBh Z2U6IGh0dHBzOi8vd3d3LmV4YW1wbGUuY29tCnB1Ymxpc2hfdG86IG5vbmUKCmVudmlyb25tZW50 -OgogIHNkazogXjMuNi4wCgpkZXBlbmRlbmNpZXM6CiAgZnVuY3Rpb25zX2ZyYW1ld29yazogXjAu +OgogIHNkazogXjMuOC4wCgpkZXBlbmRlbmNpZXM6CiAgZnVuY3Rpb25zX2ZyYW1ld29yazogXjAu NC4wCiAgc2hlbGY6IF4xLjAuMAoKZGV2X2RlcGVuZGVuY2llczoKICBidWlsZF9ydW5uZXI6IF4y LjAuMAogIGZ1bmN0aW9uc19mcmFtZXdvcmtfYnVpbGRlcjogXjAuNC4xCiAgaHR0cDogXjEuMC4w CiAgZGFydF9mbHV0dGVyX3RlYW1fbGludHM6IF4zLjAuMAogIHRlc3Q6IF4xLjE2LjYKICB0ZXN0 diff --git a/dartfn/lib/src/generators/json.g.dart b/dartfn/lib/src/generators/json.g.dart index f24bc900..25f90037 100644 --- a/dartfn/lib/src/generators/json.g.dart +++ b/dartfn/lib/src/generators/json.g.dart @@ -243,7 +243,7 @@ CiAgICAgICduYW1lJzogaW5zdGFuY2UubmFtZSwKICAgIH07Cg==''', bmFtZTogX19wcm9qZWN0TmFtZV9fCmRlc2NyaXB0aW9uOiBBIHNhbXBsZSBGdW5jdGlvbnMgRnJh bWV3b3JrIHByb2plY3QgZm9yIGhhbmRsaW5nIEpTT04uCiMgdmVyc2lvbjogMC4xLjAKIyBob21l cGFnZTogaHR0cHM6Ly93d3cuZXhhbXBsZS5jb20KcHVibGlzaF90bzogbm9uZQoKZW52aXJvbm1l -bnQ6CiAgc2RrOiBeMy42LjAKCmRlcGVuZGVuY2llczoKICBmdW5jdGlvbnNfZnJhbWV3b3JrOiBe +bnQ6CiAgc2RrOiBeMy44LjAKCmRlcGVuZGVuY2llczoKICBmdW5jdGlvbnNfZnJhbWV3b3JrOiBe MC40LjAKICBqc29uX2Fubm90YXRpb246IF40LjkuMAogIHNoZWxmOiBeMS4wLjAKCmRldl9kZXBl bmRlbmNpZXM6CiAgYnVpbGRfcnVubmVyOiBeMi4yLjEKICBmdW5jdGlvbnNfZnJhbWV3b3JrX2J1 aWxkZXI6IF4wLjQuNwogIGh0dHA6IF4xLjAuMAogIGpzb25fc2VyaWFsaXphYmxlOiBeNi42LjAK From 1d0f34befb975b7ada21e4ce6d065bf290a7ee7c Mon Sep 17 00:00:00 2001 From: Kevin Moore Date: Fri, 1 Aug 2025 14:41:21 -0700 Subject: [PATCH 5/5] closer --- functions_framework_builder/lib/builder.dart | 15 ++++++++------- .../lib/src/function_type_validator.dart | 6 +++--- .../lib/src/generic_function_type.dart | 15 ++++++++------- .../lib/src/supported_function_type.dart | 9 +++++---- functions_framework_builder/pubspec.yaml | 2 +- integration_test/test/cloud_behavior_test.dart | 2 +- 6 files changed, 26 insertions(+), 23 deletions(-) diff --git a/functions_framework_builder/lib/builder.dart b/functions_framework_builder/lib/builder.dart index f7ec63e2..5ab20396 100644 --- a/functions_framework_builder/lib/builder.dart +++ b/functions_framework_builder/lib/builder.dart @@ -22,7 +22,7 @@ /// details, and `build.yaml` for how this builder is configured by default. library; -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:build/build.dart'; import 'package:dart_style/dart_style.dart'; import 'package:functions_framework/functions_framework.dart'; @@ -53,7 +53,7 @@ class _FunctionsFrameworkBuilder implements Builder { for (var annotatedElement in _fromLibrary(libraryElement)) { final element = annotatedElement.element; - if (element is! FunctionElement || element.isPrivate) { + if (element is! TopLevelFunctionElement || element.isPrivate) { throw InvalidGenerationSourceError( 'Only top-level, public functions are supported.', element: element, @@ -63,7 +63,7 @@ class _FunctionsFrameworkBuilder implements Builder { final targetReader = annotatedElement.annotation.read('target'); final targetName = targetReader.isNull - ? element.name + ? element.name3! : targetReader.stringValue; if (entries.containsKey(targetName)) { @@ -138,13 +138,14 @@ ${cases.join('\n')} } } -Iterable _fromLibrary(LibraryElement library) sync* { +Iterable _fromLibrary(LibraryElement2 library) sync* { // Merging the `topLevelElements` picks up private elements and fields. // While neither is supported, it allows us to provide helpful errors if devs // are using the annotations incorrectly. - final mergedElements = { - ...library.topLevelElements, - ...library.exportNamespace.definedNames.values, + final mergedElements = { + ...library.topLevelFunctions, + ...library.topLevelVariables, + ...library.exportNamespace.definedNames2.values, }; for (var element in mergedElements) { diff --git a/functions_framework_builder/lib/src/function_type_validator.dart b/functions_framework_builder/lib/src/function_type_validator.dart index 84ce2518..c7390c43 100644 --- a/functions_framework_builder/lib/src/function_type_validator.dart +++ b/functions_framework_builder/lib/src/function_type_validator.dart @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:build/build.dart'; import 'package:source_gen/source_gen.dart'; @@ -25,9 +25,9 @@ class FunctionTypeValidator { FunctionTypeValidator._(this._types); FactoryData validate( - LibraryElement library, + LibraryElement2 library, String targetName, - FunctionElement element, + TopLevelFunctionElement element, ) { for (var type in _types) { final reference = type.createReference(library, targetName, element); diff --git a/functions_framework_builder/lib/src/generic_function_type.dart b/functions_framework_builder/lib/src/generic_function_type.dart index ec3a6cf7..7de6ac1d 100644 --- a/functions_framework_builder/lib/src/generic_function_type.dart +++ b/functions_framework_builder/lib/src/generic_function_type.dart @@ -13,6 +13,7 @@ // limitations under the License. import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:build/build.dart'; import 'package:source_gen/source_gen.dart'; @@ -72,15 +73,15 @@ class GenericFunctionType implements SupportedFunctionType { @override FactoryData? createReference( - LibraryElement library, + LibraryElement2 library, String targetName, - FunctionElement element, + TopLevelFunctionElement element, ) { - if (element.parameters.isEmpty) { + if (element.formalParameters.isEmpty) { return null; } - final firstParamType = element.parameters.first.type; + final firstParamType = element.formalParameters.first.type; final paramInfo = validJsonParamType(firstParamType); @@ -106,8 +107,8 @@ class GenericFunctionType implements SupportedFunctionType { // TODO: add a test for this! throw InvalidGenerationSourceError( 'The type `${paramInfo.paramType!.element.name}` is not exposed ' - 'by the function library `${library.source.uri}` so it cannot ' - 'be used.', + 'by the function library `${library.firstFragment.source.uri}` so ' + 'it cannot be used.', ); } } @@ -117,7 +118,7 @@ class GenericFunctionType implements SupportedFunctionType { returnKind == JsonReturnKind.isVoid, paramInfo, escapeDartString(targetName), - '$functionsLibraryPrefix.${element.name}', + '$functionsLibraryPrefix.${element.name3}', ); } return null; diff --git a/functions_framework_builder/lib/src/supported_function_type.dart b/functions_framework_builder/lib/src/supported_function_type.dart index 55faba4f..b364aae0 100644 --- a/functions_framework_builder/lib/src/supported_function_type.dart +++ b/functions_framework_builder/lib/src/supported_function_type.dart @@ -13,6 +13,7 @@ // limitations under the License. import 'package:analyzer/dart/element/element.dart'; +import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:build/build.dart'; @@ -64,15 +65,15 @@ class SupportedFunctionType { } FactoryData? createReference( - LibraryElement library, + LibraryElement2 library, String targetName, - FunctionElement element, + TopLevelFunctionElement element, ) { - if (element.library.typeSystem.isSubtypeOf(element.type, _type)) { + if (element.library2.typeSystem.isSubtypeOf(element.type, _type)) { return _TrivialFactoryData( escapeDartString(targetName), '$_constructor(' - '$functionsLibraryPrefix.${element.name},)', + '$functionsLibraryPrefix.${element.name3},)', ); } return null; diff --git a/functions_framework_builder/pubspec.yaml b/functions_framework_builder/pubspec.yaml index 3e660589..51670b0a 100644 --- a/functions_framework_builder/pubspec.yaml +++ b/functions_framework_builder/pubspec.yaml @@ -8,7 +8,7 @@ environment: sdk: ^3.8.0 dependencies: - analyzer: '>=6.9.0 <8.0.0' + analyzer: ^7.5.0 build: ^3.0.0 build_config: ^1.0.0 collection: ^1.17.0 diff --git a/integration_test/test/cloud_behavior_test.dart b/integration_test/test/cloud_behavior_test.dart index 6ad0392e..93698760 100644 --- a/integration_test/test/cloud_behavior_test.dart +++ b/integration_test/test/cloud_behavior_test.dart @@ -58,7 +58,7 @@ void main() { cloudLoggingMiddleware(_projectId), ), zoneSpecification: ZoneSpecification( - print: (_, __, ___, line) => lines.add(line), + print: (_, _, _, line) => lines.add(line), ), );