Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,11 @@ jobs:
# The runner's request validation is the code that rejected
# flutter_web_plugins and failed every deploy for months, and its tests only
# ran on a developer's machine - so nothing stopped that regression returning.
# The image is built only at deploy time, so this is also the only place the
# runner is compiled before it ships.
# Also build and smoke the actual image: source-only tests cannot detect
# CLI/signed SDK incompatibility, missing image files, or Dart toolchain drift.
runner:
runs-on: ubuntu-latest
timeout-minutes: 30

steps:
- name: Checkout
Expand All @@ -81,3 +82,12 @@ jobs:
- name: Test the runner
working-directory: cloud-run/ffai-runner
run: dart test

- name: Build runner image
run: docker build --tag ccc-ffai-runner:ci cloud-run/ffai-runner

- name: Smoke runner image and current SDK (no credentials)
run: |
docker run --rm --entrypoint dart \
--volume "$PWD/cloud-run/ffai-runner/tool:/smoke:ro" \
ccc-ffai-runner:ci /smoke/smoke.dart
33 changes: 33 additions & 0 deletions DEPLOYMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,39 @@ changes will deploy nothing:
GitHub does not expose organisation secrets to private repositories on the
free plan.

#### Runner CLI/SDK compatibility

The image pins FlutterFlow CLI **0.0.43** and workspace init explicitly selects
`--interface sdk`: this runner executes Dart DSL, not the CLI's newer `fft`
workspace format. CLI and SDK version numbers are independent. The signed SDK
manifest's `min_router_version`, not the SDK's own version, sets the CLI floor.

CI now builds the actual runner image, starts its health route, fetches the
current signed production SDK, and compiles representative deployment DSL.
This catches image/toolchain failures, a raised SDK minimum, and changed SDK
APIs before review. It uses no credentials and does not deploy or access a
project. It does **not** prove authenticated `ai init` or project validation;
those still need the canary below.

For future upgrades:

1. Keep an exact CLI pin, not `latest`. Review the CLI release notes and signed
SDK manifest when upgrading or investigating a compatibility alert.
2. Update `FLUTTERFLOW_CLI_VERSION` in the Dockerfile and `minCliVersion` in
`bin/server.dart` together in one PR. Tests reject version drift and require
explicit SDK initialization. Keep the compile-smoke fixture aligned with
the generated deployment DSL if its API calls change.
3. Require green CI, then validate authenticated initialization and a dry-run
against an approved non-production runner/project before rollout. The daily
canary continues to catch upstream changes between repository commits.
4. After an approved rollout, check `/runnerHealth` for the expected SHA and
CLI version, and check the canary result.

The production SDK remains a moving upstream dependency: an exact CLI pin alone
does not freeze it. A new incompatible snapshot needs a reviewed upgrade, not
an automatic CLI update. Deployment triggers are unchanged: merging runner
changes to `main` still deploys production; a PR's image smoke never does.

#### Runner canary (scheduled)

The workflow `.github/workflows/canary.yml` runs daily (07:21 UTC) and on demand
Expand Down
2 changes: 1 addition & 1 deletion cloud-run/ffai-runner/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ENV PATH="/root/.pub-cache/bin:${PATH}"
ENV PORT=8080
ENV FFAI_WORKSPACE=/workspace/custom_code_connect

ARG FLUTTERFLOW_CLI_VERSION=0.0.41
ARG FLUTTERFLOW_CLI_VERSION=0.0.43
RUN dart pub global activate flutterflow_cli "$FLUTTERFLOW_CLI_VERSION" \
&& dart pub global list | grep -F "flutterflow_cli $FLUTTERFLOW_CLI_VERSION"

Expand Down
6 changes: 4 additions & 2 deletions cloud-run/ffai-runner/bin/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import 'package:ccc_ffai_runner/sha256.dart';
// The lowest flutterflow_cli the vendored FlutterFlow AI snapshot accepts. The
// image pins FLUTTERFLOW_CLI_VERSION to this (see Dockerfile); it must be kept
// in lockstep there, and it is what the health route reports as the required minimum.
const minCliVersion = '0.0.41';
const minCliVersion = '0.0.43';

/// The liveness/version route the container actually serves. Must not be a
/// path Google's front end reserves ('/healthz'), or Cloud Run answers it and
Expand Down Expand Up @@ -368,7 +368,9 @@ Future<_RunOutcome?> _ensureWorkspace(
// that came from the environment to its credential store - which is what we
// want here, because the workspace below is shared across requests.
final result = await _runFlutterFlow(
['ai', 'init', workspaceName, '--yes'],
// Newer CLIs default to an fft workspace. This runner writes Dart DSL
// scripts and imports flutterflow_ai, so it requires the SDK interface.
['ai', 'init', workspaceName, '--yes', '--interface', 'sdk'],
workingDirectory: parent.path,
apiKey: apiKey,
channel: channel,
Expand Down
121 changes: 121 additions & 0 deletions cloud-run/ffai-runner/tool/smoke.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Run inside the built image. Downloads public packages, never authenticates
// or executes the DSL: full workspace init and project validation need a canary.
import 'dart:async';
import 'dart:convert';
import 'dart:io';

Future<void> main() async {
final server = await Process.start('dart', ['run', 'bin/server.dart'],
workingDirectory: '/app');
final stdoutDone = server.stdout.transform(utf8.decoder).forEach(stdout.write);
final stderrDone = server.stderr.transform(utf8.decoder).forEach(stderr.write);
final scratch = await Directory.systemTemp.createTemp('ffai-smoke-');
try {
final health = await _waitForHealth();
if (health['flutterflowCli'] == null ||
health['flutterflowCli'] == '' ||
health['flutterflowCli'] != health['minFlutterflowCli']) {
throw StateError('Installed CLI does not match the runner: $health');
}
stdout.writeln('Runner health: ${jsonEncode(health)}');

// This public command verifies the signed latest manifest, including its
// min_router_version. A pinned CLI can become too old as upstream evolves.
final report = await _run('flutterflow', ['ai', 'fetch-sdk', '--env', 'prod'],
workingDirectory: scratch.path);
final sdkPath = RegExp(r'^path: (.+)$', multiLine: true)
.firstMatch(report)?.group(1)?.trim();
if (sdkPath == null || !File('$sdkPath/pubspec.yaml').existsSync()) {
throw StateError('fetch-sdk did not return an SDK package directory');
}
await File('${scratch.path}/pubspec.yaml').writeAsString('''
name: runner_sdk_smoke
environment:
sdk: ">=3.7.0 <4.0.0"
dependencies:
flutterflow_ai:
path: ${jsonEncode(sdkPath)}
''');
await File('${scratch.path}/smoke.dart').writeAsString(_dslContract);
await _run('dart', ['pub', 'get'], workingDirectory: scratch.path);
// Type-check the SDK APIs the generated deployment script relies on, but
// do not run main (even validate/dry-run would require a real API key).
await _run('dart', ['compile', 'kernel', 'smoke.dart', '-o', 'smoke.dill'],
workingDirectory: scratch.path);
stdout.writeln('Runner image and SDK compile smoke passed. No project accessed.');
} finally {
server.kill();
await server.exitCode;
await Future.wait([stdoutDone, stderrDone]);
await scratch.delete(recursive: true);
}
}

Future<Map<String, dynamic>> _waitForHealth() async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 2);
try {
for (var attempt = 0; attempt < 60; attempt++) {
try {
final request = await client.getUrl(Uri.parse('http://127.0.0.1:8080/runnerHealth'));
final response = await request.close().timeout(const Duration(seconds: 10));
if (response.statusCode == HttpStatus.ok) {
return jsonDecode(await response.transform(utf8.decoder).join())
as Map<String, dynamic>;
}
await response.drain<void>();
} on SocketException {
// The real entrypoint is still starting.
}
await Future<void>.delayed(const Duration(seconds: 1));
}
throw StateError('Runner did not become healthy');
} finally {
client.close(force: true);
}
}

Future<String> _run(String executable, List<String> args,
{required String workingDirectory}) async {
final result = await Process.run(executable, args,
workingDirectory: workingDirectory);
stdout.write(result.stdout);
stderr.write(result.stderr);
if (result.exitCode != 0) {
throw StateError('$executable ${args.join(' ')} failed (${result.exitCode})');
}
return result.stdout as String;
}

// Keep this representative of _writeDeployScript in bin/server.dart. Compiling
// it catches SDK API/schema changes without calling FlutterFlow or needing keys.
const _dslContract = r'''
import 'package:flutterflow_ai/flutterflow_ai.dart';

Future<void> main() async {
try {
await flutterFlowAI((app) {
app.raw((project) {
if (findCustomClass(project, name: 'RunnerSmoke') == null) {
addCustomClass(project, name: 'RunnerSmoke', code: 'class RunnerSmoke {}');
} else {
updateCustomClass(project, name: 'RunnerSmoke', code: 'class RunnerSmoke {}');
}
ensureFileName(project);
});
}, apiKey: null, baseUrl: null, projectId: null, dryRun: true,
commitMessage: 'Compile-only runner smoke');
} catch (error) {
throw StateError(formatFlutterFlowAIError(error));
}
}

void ensureFileName(FFProject project) {
for (final file in project.customCode.customCodeFiles.customCodeFiles) {
final holdsClass = file.customCodeEntities.any((entity) =>
entity.hasInterface() && entity.interface.identifier.name == 'RunnerSmoke');
if (holdsClass && !file.identifier.name.endsWith('.dart')) {
file.identifier.name = '${file.identifier.name}.dart';
}
}
}
''';
26 changes: 22 additions & 4 deletions src/cloudRunRunner.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ test("Cloud Run pins a snapshot-compatible FlutterFlow CLI", () => {

assert.ok(version, "Dockerfile must explicitly pin FLUTTERFLOW_CLI_VERSION");
assert.ok(
compareVersions(version, "0.0.39") >= 0,
`FlutterFlow CLI ${version} is older than the snapshot minimum 0.0.39`,
compareVersions(version, "0.0.43") >= 0,
`FlutterFlow CLI ${version} is older than the snapshot minimum 0.0.43`,
);
assert.match(
dockerfile,
Expand All @@ -51,6 +51,24 @@ test("Cloud Run pins a snapshot-compatible FlutterFlow CLI", () => {
);
});

test("Cloud Run explicitly initializes an SDK workspace", () => {
assert.match(
runnerSource,
/\['ai', 'init', workspaceName, '--yes', '--interface', 'sdk'\]/,
"the CLI default can change; Dart DSL deploys require the SDK interface",
);
});

test("CI builds and smokes the real runner image without project credentials", () => {
const ci = readFileSync(new URL("../.github/workflows/ci.yml", import.meta.url), "utf8");
const smoke = readFileSync(new URL("../cloud-run/ffai-runner/tool/smoke.dart", import.meta.url), "utf8");
assert.match(ci, /docker build --tag ccc-ffai-runner:ci cloud-run\/ffai-runner/);
assert.match(ci, /ccc-ffai-runner:ci \/smoke\/smoke\.dart/);
assert.match(smoke, /\['ai', 'fetch-sdk', '--env', 'prod'\]/);
assert.match(smoke, /\['compile', 'kernel', 'smoke\.dart'/);
assert.match(smoke, /http:\/\/127\.0\.0\.1:8080\/runnerHealth/);
});

test("Cloud Run upserts custom classes in one authoritative write", () => {
assert.match(
runnerSource,
Expand Down Expand Up @@ -174,8 +192,8 @@ test("Cloud Run deployment reserves enough memory and serializes provisioning",
assert.match(deployScript, /--concurrency "\$CONCURRENCY"/);
});

// The image is only exercised at deploy time and nothing builds it in CI, so a
// missing COPY is invisible until a real deploy fails. It already happened once:
// Keep a fast contract guard alongside the real image smoke in CI. A missing
// COPY already caused a production failure once:
// request validation moved to lib/, the Dockerfile still copied only bin/, and
// the container could not start at all.
test("the image copies every directory the entrypoint imports", () => {
Expand Down
Loading