flutterflow_cloud_emulator 0.3.0-dev.2
flutterflow_cloud_emulator: ^0.3.0-dev.2 copied to clipboard
The offline FlutterFlow Cloud emulator — the full client data plane (records, queries, batch, auth, files) as one self-contained binary that live-watches .ffx/ and seeds from committable .ffx/emulator [...]
flutterflow_cloud_emulator #
The offline emulator has no authoritative cloud project identity. It accepts the structural configuration envelope and retains 100 active realtime subscriptions / 4,096 lifetime IDs; deployed publication and realtime admission enforce the project's limit cohort.
Rule expressions allow up to 4,096 source characters, 1,024 AST nodes and depth/nesting 256, matching the config schema and platform parser. Structural limits are checked before recursive type checking and evaluation.
The FlutterFlow Cloud emulator: one self-contained binary that serves the entire client-facing data plane — records, named queries, batch, auth, files, idempotency, concurrency, permission rules, and the RFC 9457 error taxonomy — with no cloud project, provisioning or network egress. It runs no function code: with a local Functions host attached, it forwards the Functions routes to that host and serves it the data plane through a private socket (below).
An app built on flutterflow_cloud or
@flutterflow/cloud runs against it with one flag.
ffx-emulator # in a project directory containing .ffx/
# or: dart run flutterflow_cloud_emulator:ffx_emulator
await FlutterFlowCloud.initialize(
options: FFXDefaultOptions.current,
useEmulator: true, // → http://<host>:8790
);
| Workspace | backend/packages/dart_flutterflow_cloud_emulator — member of the pub workspace rooted at backend/pubspec.yaml |
| Package | flutterflow_cloud_emulator — pure Dart, no Flutter dependency (it must compile with dart compile exe) |
| Binary | ffx-emulator (entry bin/ffx_emulator.dart) |
| Embeddable | FFXEmulator.start() from lib/emulator.dart, for tests |
| Defaults | Binds 0.0.0.0:8790 — 0.0.0.0 so Android emulators reach it via 10.0.2.2. --project-dir, --host, --port, --quiet, --runtime-state-dir <dir> (private checkpoints below), --functions-connection-stdin (attached Functions host), --max-upload-bytes <n> and --max-uploaded-bytes <n> (or FFX_EMULATOR_MAX_UPLOAD_BYTES / FFX_EMULATOR_MAX_UPLOADED_BYTES: one upload's largest declared size, refused at the grant, and the most bytes uploaded files may hold altogether, counting what each has received (seed and deleted files aside), refused at the grant and at the transfer; each as 413 fileTooLarge, after the collection's create rule; unset, only the collection's cap applies; a thread's preview sets both, specs/26 §10) |
| Runs in | Developer laptops and the agent container — an agent can build and exercise an app end-to-end with no credentials |
| Spec | 26 — Emulator — the normative contract |
Google sign-in simulation requires emulator 0.2.0 or newer and app SDK 0.7.0 or newer. The local consent page uses test identities without contacting Google. A passing local test does not prove deployed Google credentials are configured.
What it solves #
Model unique tuples are checked for record/admin writes, seeds and final
batch images. A caseFold member is keyed exactly as the cloud keys it, from
the same generated Unicode 15.1 tables (unique_normalization.g.dart; no
package dependency) and shared test vectors. Collisions return 409 uniqueConstraintViolation and a failed
batch applies nothing; swaps are supported. A seed row a constraint refuses
is skipped and logged; the rest of the seed loads, rows that point at it
included (the cloud's sample data leaves those out). Existing data is verified
synchronously on config reload and checkpoint restore: records that share a
tuple or hold a value the layout cannot encode are reported (log and the
/emulator/v1/state uniqueConstraints list, with their record IDs) and put
the constraint in the cloud's conflict state instead of stopping the
emulator: new or changed tuple claims return 503 uniqueConstraintBuilding
(unstored, Retry-After: 5) until deleting a record or clearing an optional
member repairs them (a changed tuple is a new claim, refused too), and the
constraint is ready again at once. Accepted
constraints retain their original scalar layouts and exact serving-key size
limit across omission, field-type changes and private runtime checkpoints.
A field-name-only checkpoint preserves its records and equality constraints,
but refuses new or changed populated tuples because the original types cannot
be verified; unchanged tuples, optional clearing and deletion remain allowed.
This emulator does not simulate cloud backfill latency or operator activation. See
config contract.
Two audiences, one problem: neither a developer on a plane nor an agent inside a credential-free sandbox can provision a cloud project. Both still need a real backend to build against. The emulator gives them the same wire surface the platform serves, generated from the same schemas — so code that works here works deployed.
Three properties make it usable rather than a toy:
- Live config. It watches
./.ffx/and re-appliesproject.json— models, queries, permissions, storage, auth — on edit, with no restart. Invalid JSON is retried gracefully rather than crashing the process. Schema-owned descriptions enforce the compiler's 10–500 character bound, counted as the compiler counts it in UTF-16 code units (an emoji is two); an invalid description keeps the last accepted config serving. - Committable seed state. Initial data lives in
./.ffx/emulator/{auth,database,storage}.json, written by humans or agents (and the app's sample data in./.ffx/seed.json), written by humans or agents and checked into the project repo. The emulator sources these files and live-reingests them on change; it writes them only when asked: an internal export of the whole state, or the per-item seed writes that keep a thread's own records and accounts for new threads. Runtime mutations are in memory, carried across restarts only by the private runtime checkpoint. - Contract coupling. Its wire models are generated by
@flutterflow/codegenfrom@flutterflow/schema, the same pipeline the real surface uses. A schema change that is not reflected here failsbun run codegen:checkin CI.
Structure #
| Path | Role |
|---|---|
lib/src/server.dart |
dart:io HTTP server, router, CORS. Serves the emulated data plane (/v1/…) and the internal control API (/emulator/v1/…) |
lib/src/dynamic_links_host.dart |
The Dynamic Links link host's public wire, in memory (Dynamic Links) |
lib/src/problems.dart |
RFC 9457 emission and the error taxonomy (18 §5) |
lib/src/seed_files.dart |
What the current seed files name (provenance index) and the seed writes: keep, unkeep, three-way update |
lib/src/engine/config_state.dart |
Parsed config, derived plans, versioning |
lib/src/engine/validate_input.dart |
Field-spec validation — the Dart mirror of @flutterflow/schema's records/validate.ts |
lib/src/engine/size_limits.dart |
Actual-stream JSON body caps and exact final-record byte validation (04 §8) |
lib/src/engine/rules.dart |
Permission evaluation, current-config record projection before rules, and response redaction (05 §2.2) |
lib/src/engine/query_engine.dart |
where/orderBy/paging/aggregates and page tokens |
lib/src/store/ |
database_store (records, seed vs live provenance), auth_store (users, credentials, sessions, tokens, password-reset codes and the email outbox), file_store (records, blob bytes, grants, signed URLs), idempotency_store |
lib/src/watch/ |
ffx_watcher (debounced .ffx/ watching) and seed_loader (ingestion + merge) |
lib/src/http_ingress.dart |
The listener's framing observer: each request's original method, target and fields, before dart:io normalizes the URI; a connection that asks to upgrade (the realtime WebSocket) is not read as HTTP after its request |
lib/src/functions_host.dart |
Forwarding of the Functions routes to the attached host, the internal API it calls (test principals and their session leases included), and the reset signal it receives |
lib/src/functions_contract.dart |
The contract's paths (the reset signal's included), backend-call fields and bounds (retained generations, upload handles, test session leases, the reset wait), which the shared conformance fixture pins |
lib/src/functions_connection.dart |
The host's connection line and its socket-directory checks |
lib/src/functions_relay.dart |
Framing of the host's answer, streamed to the client |
lib/src/util/canonical_json.dart |
The config digest: the schema package's canonicalJson, byte for byte |
lib/src/runtime_checkpoint.dart |
Private runtime checkpoints, separate from seed exports |
lib/src/wire_models.g.dart |
Generated. The client-facing wire models and config document. Never hand-edit |
lib/src/wire_schemas.g.dart |
Generated. The schema table of the internal API's shapes (FunctionBackendCall, FunctionBackendResult, FunctionBackendProblem, the principal, test-principal and test-session requests and answers, and the host's reset answer) and the state route's Functions availability, which the emulator checks at runtime. Never hand-edit |
The HTTP server stamps success and problem responses with standard Date
and exposes it through CORS, giving browser SDKs a server response timestamp
(18 §4.2).
Rules receive a separate fixed request.time, captured when the HTTP handler
starts, before body reads or other awaits. Point reads, create/write checks,
post-filter rows and batch operations reuse that request's value; concurrent
requests cannot overwrite it. Client-supplied internal time headers are ignored.
EmulatorServer accepts an optional receive-clock function for deterministic
embedded tests and defaults to the host clock.
Model rules evaluate projected candidates, fetched records and write pre-images, including query post-filters and batches. The projection mirrors the platform's shared schema helper: defaults and unknown-field stripping precede evaluation, protected fields remain available to rules, and response redaction follows it. Writes retain the raw image, preserving unknown fields without storing virtual defaults (05 §2.2).
Byte serving checks the current collection and ready file state on every
request, including private download tokens. Renames update the next response's
Content-Disposition; removed collections, tombstones and missing bytes return
404. Both public and private byte routes support HEAD and content-safety
headers. Public responses use public, max-age=0, must-revalidate; private
responses retain the token-lifetime cache cap of 900 seconds. A public/private
visibility change applies to retained bytes without another upload. The
emulator remains one project/environment per process, with its own opaque
local grant URLs rather than production JWT/address multiplexing.
DELETE /v1/auth/me implements the self-service lifecycle: bodyless,
authenticated, stable-key deletion of the current full or guest identity,
profile and all sessions. Exact receipt retries work after revocation while
the original access token remains unexpired. Customer records/files retain
their owners; ordinary reads retain the token TTL window, while new mutations
reject. A hot seed reload cannot recreate a deleted identity/profile in that
process; an explicit reset starts fresh disposable state. The production
all-environment durable workflow is documented in 06 §5.10;
the emulator has one project/environment and memory-only state.
Identity administration, claims and auth events #
Custom profiles support bounded scalar lists with the same element validation
as model fields. Lists replace atomically when patched. The endUser record
projection honors serverOnly on email, phone and other auth-owned readable
fields, so named people queries can expose profiles without contact details.
auth.me() retains the signed-in user's own identity; built-ins stay immutable.
Sign-up's profile and PATCH /v1/auth/me refuse every readOnly/serverOnly
endUser field with the platform's fieldReadOnly/fieldServerOnly codes, and
sign-up requires only the declared fields the client may write.
The trusted local /emulator/v1/auth/users collection provides list/create,
and /{id} provides get/update/bodyless delete; /{id}/revokeSessions takes
{}. They use the canonical identity fields, explicit mutation keys, complete
guest credential conversion, unique normalized email, the list's order
(oldest or newest first) and typed acknowledgements
of 12 §10.
Creation has no implicit profile; sign-in materializes one. Auth-owned fields
are projected into profile reads and named queries, without physical mirrors.
GET/PATCH/DELETE /v1/records/endUser/{id} addresses that same profile with
the configured endUser rules, field markers, record envelopes and ETags.
The record its rules evaluate carries the claims map, as the platform's
does, so the rule input matches; no rule the compiler accepts can read it
(it is server-only and not addressable).
The default owner can read and patch their profile; deletion is denied by
default and an explicitly permitted record deletion removes only the profile,
not the account: GET/PATCH /v1/auth/me then answer recordNotFound, as
the platform does, until the next sign-in makes a new profile. Use
auth.deleteAccount() for account deletion. A profile write through either
route, deletion included, makes a seeded account live, so an auth.json
reingest neither reverts the edit nor brings the profile back. An entry's
hasProfile: false means no profile until a sign-in makes one; a reingest
never takes a profile away.
Disable/update/revoke reject old sessions and cached refresh replays immediately;
re-enable permits fresh sessions only. Deletion retains customer records/files.
This is one in-memory project/environment, with no external delivery queue,
admin credentials, provider calls or general admin-plane emulation.
A thread's data: provenance, admin edits and seed writes #
A thread's preview runs on the thread's own emulator, and the stage's Data tab
edits it through the supervisor's /v1/data routes, which call this internal
surface (26 §3, §5.2):
- Every record and account has an
origin—sample(the seed owns it),changed(edited here; the seed names it) ornew— inGET state'sprovenance,GET records/{model}'sorigins, and every account answer (withhandle,profile,builderand the plaintextpasswordwhen known). A deleted seed record is tombstoned (deletedSampleIds) so no reingest brings it back; the runtime checkpoint keeps tombstones andresetclears them. An item edited back to its seed entry is the seed's again at the next reingest. POST|PATCH|DELETE records/{model}[/{id}]write records with rules bypassed and values validated;PATCH auth/users/{id}takesprofile;POST auth/users/{id}/sessionmints a sign-in without a password; the builder cannot be deleted (409builderAccount). Admin edits turn a seed item live, so a reingest never overwrites it.POST seed/keep,seed/unkeepandseed/updateedit the thread's.ffx/seed.json(oremulator/database.json) andemulator/auth.jsonentry by entry, then reingest at once.
The trusted local control route
PUT /emulator/v1/auth/users/{endUserId}/customClaims takes {claims} and
Idempotency-Key; {} revokes the whole map. It validates the current
registry, 32 scalar values and 1,000 compact UTF-8 bytes, returns
{data:{id,claims,revision}}, and preserves exact mutation replay. It is not a
fake admin-key API and is not exposed by ticketed preview proxies.
GET /v1/auth/events serves the same bounded revision invalidation and session
lifecycle as 06 §7.1.
It also emits terminal auth.sessionRevoked, bound to the required,
CORS-exposed FFX-Auth-Session-Id header. Opaque tokens need no client parsing.
Five-second coalesced heartbeat comments detect disconnected Dart HTTP
sockets; no slow reader accumulates an unbounded heartbeat queue. Existing
access tokens keep their immutable claims until expiry; fresh refresh projects
the latest source through the current registry. Named end-user list/aggregate
queries use that same source. Seed/export auth.json carries the raw claims
map and canonical identity fields separately from each user's physical profile;
tokens and streams are not exported. Live-session exact refresh replay retains
the original tokens; revoked or expired sessions cannot replay success.
26 §5 states the local-control,
retention and single-config limits.
Password reset #
POST /v1/auth/password/sendReset and POST /v1/auth/password/completeReset
serve 06 §5.8
with the platform's answers. sendReset returns 202 {"data": {"accepted": true}} whether or not an account uses the email. For an email/password
account that may sign in, it mints a single-use code that works for 60 minutes
and only while the account keeps the address it was sent to. completeReset
answers {"data": {"email"}}, rewrites the password and revokes every session
of the account (reason passwordReset, also on its auth.sessionRevoked
notices). An unknown, malformed or used code is 400 oobCodeInvalid, an
expired one 400 oobCodeExpired, a disabled account 403 userDisabled, and a
short password 422 weakPassword, which leaves the code usable. Both routes
need the emailPassword provider (400 providerNotEnabled). A bad body, a
missing provider, a malformed code or a short password releases the
Idempotency-Key; every other answer, the 202 included, is stored under it,
so one key sends one email.
Nothing is delivered. The email lands in an in-memory outbox instead, read with the trusted local control route:
curl 'http://127.0.0.1:8790/emulator/v1/auth/outbox?email=ada@example.com'
# {"data": [{"kind": "passwordReset", "to": "ada@example.com",
# "oobCode": "emu_oob_…", "createdAt": "…", "expiresAt": "…"}]}
Entries are newest first; email (optional) keeps those to one address. Like
the rest of /emulator/v1/auth/… it takes no API key and preview proxies do
not expose it, so a test or a tool in the container reads the code and calls
completeReset (or an SDK's completePasswordReset) with it. Codes and the
outbox are memory-only: a restart or POST /emulator/v1/reset empties them,
and neither is exported or checkpointed.
test/password_reset_test.dart covers the flow.
Resources it uses #
No database, no object store, no credentials — memory plus the project's
.ffx/ directory. That is the point: it is the one FFX component that runs
with nothing attached. --runtime-state-dir names a private directory for
supervisor checkpoints (POST /emulator/v1/checkpoint writes one; startup
restores the current one), never the project's seeds. Checkpoints from retained
guests may omit record file-reference provenance. Their records and sessions
still restore; every scalar value naming a file in that checkpoint is retained
as a dependency, including fields absent from the current schema. This can
conservatively retain a file named by an ordinary string until that field is
changed or its record deleted. Present provenance, including an empty list,
remains authoritative; malformed metadata refuses restoration. The next
checkpoint records the recovered provenance explicitly.
An attached Functions host
adds two Unix sockets in the private directory its parent created: the host's
host.sock, which the emulator connects to, and the emulator's own emulator.sock.
The emulator's one network egress is the connectors provider:
| Variable | Default | Holds |
|---|---|---|
FFX_CONNECTORS_URL |
unset | Where POST /v1/connectors/{connector}/{operation} is forwarded for the door to admit (see Connectors). In the chat runtime the supervisor sets it to its door's emulator route, which carries the call to the platform; FFXEmulator.start(connectorsUrl:) overrides it in-process |
FFX_CONNECTORS_TOKEN |
unset | Sent as Authorization: Bearer on the forward: the host's credential for this emulator, set by the supervisor; FFXEmulator.start(connectorsToken:) overrides it |
FFX_CONNECTORS_CATALOG |
unset | The connector catalog's view, as JSON, set by the supervisor (emulatorConnectorEnv()): {"operations": {"<id>.<operation>": {"acts": bool}}}, which decides what a call lost after it left is. A malformed value refuses every connector call, and the rest of the emulator serves. FFXEmulator.start(connectorCatalog:) overrides it, and FFXEmulator.start(environment:) replaces the environment all four are read from |
FFX_EMULATOR_CONNECTORS_SECRET |
unset | A random secret the supervisor mints each boot. A connector call must carry it as FFX-Connectors-Secret, which only the preview's backend proxy adds (see Connectors). FFXEmulator.start(connectorsSecret:) overrides it |
The emulator carries no catalog of its own. With any of these unset but
FFX_CONNECTORS_TOKEN (a standalone emulator, the lab's) it makes no
connector calls at all: each is refused 403 permissionDenied, naming the
unset variables, rather than forwarded unheld. retry is never, because
no retry sets them.
Connectors #
Providers cannot be emulated, and the rules are not this package's: a
POST /v1/connectors/{connector}/{operation} is admitted by the supervisor's
door with the data plane's own admission (admitAppCall,
connector-catalog), against the
declaration this emulator serves, so a preview refuses what a release would
in the same words (connectors §5.1).
What the emulator does:
- The door comes first. Before the body is read or any key looked at,
FFX-Connectors-Secretmust equalFFX_EMULATOR_CONNECTORS_SECRET(constant-time), and the variables above must be set; otherwise403 permissionDenied. Only the preview's backend proxy adds the secret, so code in the container that dials the emulator directly (an auto-screenshot, a test run) never posts for real. - The catalog is
FFX_CONNECTORS_CATALOG. A value that does not parse refuses every connector call (403 permissionDenied, naming it malformed) and is logged; records, auth and files still serve. The supervisor writes it withemulatorConnectorEnv(); its test pins that output totest/fixtures/connectors_catalog.json, whichconnectors_test.dartparses. An operation it does not name is taken to act. - An expression that does not parse rejects the config at load, as a model rule's does.
Then the call leaves: to FFX_CONNECTORS_URL as
POST …/v1/connectors/{connector}/{operation} with
{body, declaration, claims, caller, configVersion, requestTimeMicros} —
the app's body as sent (an empty one as {}; one that is not a JSON object is
400 malformedRequest here), the served config's connectors entry for the
connector or null, its auth.claims, the signed-in end user (id,
accountType, claims) or null, the served config version and the request
time — and, when FFX_CONNECTORS_TOKEN is set, that token as the bearer. The
caller's Authorization, FFX-Api-Key and Idempotency-Key headers do not
leave the emulator.
The host's answer is read by its problem code:
| The host answered | The app gets | Under its Idempotency-Key |
|---|---|---|
a success, or a platform problem in full (type, status, retry, …: the door's admission refusal, the api's, and the agent Worker's own: connectorUpstreamFailed and connectorOutcomeUnknown when it cannot read or record the api's answer, 503 serviceUnavailable when the call failed there before it was sent) |
it verbatim: status, body, content type and Retry-After |
stored when it is a success, connectorUpstreamFailed or connectorOutcomeUnknown; any other (the door's refusal, 429 rateLimited, connectionNotLinked, the Worker's 503 serviceUnavailable) is released, so a retry with the key is carried again |
connectorUpstreamFailed or connectorOutcomeUnknown as {code, detail, fix} alone |
that problem, completed with the platform's fields, upstream kept |
stored |
| any other 5xx (the supervisor door's own failure, a bare 5xx from further on), after an operation that acts left | 500 connectorOutcomeUnknown in the host's words |
stored |
any other refusal (the supervisor door's {code, message, fix}, such as its 401 or previewConnectorCallInvalid; a bare 5xx after a read) |
503 connectorUpstreamFailed in the host's words |
released |
| no answer: the host could not be reached, or stopped answering | 503 connectorUpstreamFailed, detail the transport error; 500 connectorOutcomeUnknown once an operation that acts left |
released when the request never left, else stored |
The SDK mints one key per call and retries with it, so only a new call after
a stored answer reaches the provider again
(Mutation replay).
test/connectors_test.dart drives it against a
local HttpServer.
File transfers #
Upload grants carry the same gcsResumable/PUT instructions as production.
The local session supports whole-body PUT, 256 KiB-aligned chunks, partial
308 acknowledgments with Range, and empty status probes. Overlapping
retries preserve received bytes; a partial session cannot finalize and a
completed byte object cannot be mutated through an old grant, even before
metadata finalization. These routes transfer
binary bytes independently of the data-plane JSON request limits.
TypeScript's storage.publicUrl({fileId}) in emulator mode constructs
http://{host}:{port}/emulator/v1/public/{fileId} locally. GET/HEAD serves
only ready files in public collections; private files require signed URLs.
Permissive CORS exposes upload response headers, including Range.
Dynamic Links #
The emulator is an app's link host when the app talks to it (cloud.dynamicLinks,
specs/34 §7, §11). It serves the host's public wire
with no API key, as the host takes none, from memory:
| Route | Answer |
|---|---|
POST /v1/links |
201 {linkUrl, shortCode}: a seven-character base62 code, linkUrl on the address the caller used; validationFailed for a bad route path, a utm_* route parameter or a non-https image |
GET/HEAD /v1/links/{code} |
{link}, the link as the host shows it; routeNotFound (404) when unknown |
POST /v1/events |
{accepted}: one to five events, each code once, else validationFailed; events for unknown codes are dropped |
GET/HEAD /{code} |
a plain page naming the route the link opens; 404 when unknown |
There is no registration, so every create succeeds. It doesn't classify user agents,
redirect, show the iOS or Android pages, or serve the verification files: those are the
deployed link host's. Links and the counted events live as long as the process;
POST /emulator/v1/reset drops them, and neither the runtime checkpoint nor export
keeps them. The SDK takes it for the link host only when the app was pointed at it
(useEmulator, emulatorUrl); behind a preview's injected backend it makes no links.
test/dynamic_links_test.dart covers the routes.
Dependencies #
The runtime uses Dart SDK libraries, package:crypto for SHA-256 mutation
request fingerprints and the Functions config and credential digests, and
flutterflow_cloud_core's
validateFunctionSchema, the strict validator that checks the internal API's
requests and answers against the generated schema table. Generated wire models and the
table are part of this package. The
local seed-password digest remains eight rounds of salted FNV-1a, deliberately
noncryptographic: seed files contain plaintext test credentials, and the digest
is not a security boundary. Production password storage uses scrypt (23 §8.2).
Deliberate non-goals (v1) #
Production durable channel replay, quotas and rate limits (it never throttles; usage headers are absent) ·
the admin plane (provisioning does not exist offline — config comes from
.ffx/project.json directly) · multi-project multiplexing (one process = one
project) · durability (memory-only by design; the export endpoint is the
escape hatch).
The public JSON data plane enforces the deployed limits: 2 MiB per ordinary
request, 10 MiB per batch, and exactly 1,000,000 bytes of compact UTF-8 JSON per
complete record. The body reader counts actual stream bytes before auth or
idempotency and returns 413 on overflow at once (RequestBodyTooLarge), then
reads and discards the rest of the body, at most 64 MiB more and for at most 10
seconds, before the connection closes: closing it with input unread would reset
it, and a client that sends its whole request before reading the answer
(dart:io's HttpClient, so the Dart SDK) would see that reset instead of the
413. The internal Functions API reads its bodies the same way. Record checks run
after normalization, merge/clears, and generated fields, including profile and
file writes; a batch
failure names its operation and applies no writes. File reference counts are
virtual ledger projections: size accounting charges the persisted zero
placeholder used by the platform, while all metadata and other fields count.
Seed files remain local state injection; API updates of seeded records must fit
the same limit. Binary upload grants use their separate file transport and are
not subject to the JSON body cap. Batches have no operation-count cap: the
10 MiB request limit and per-record limit apply at any operation count, matching
04 §8.
Mutation replay #
A 24-hour in-memory claim binds a key to the method, path and body bytes for
POST/PUT/PATCH/DELETE. Reusing it for another request returns 400; a duplicate in
flight returns 409. First stored results carry FFX-Idempotency-Stored, while
replay also carries FFX-Idempotent-Replayed and the original result headers.
Date is generated for each response. Read-only POST queries do not claim keys.
Upload initiation also binds the uploader’s Origin, including omission and the
opaque null origin. Classification follows the actual router, including accepted
trailing slashes. The fingerprint retains the path exposed by dart:io; its URI
parser normalizes unreserved escapes such as %66 to f, while retained path
spellings (including a trailing slash) remain distinct.
Handlers mark execution after validation and authorization. Executed 4xx results, including authorized absence 404, version 412 and final-record 413, replay unchanged; pre-execution failures release the key. Missing and forbidden records remain indistinguishable and unstored for record-dependent rules. Batches authorize every operation before execution and apply no partial writes. See 18 §8.
Verification #
From the repo root: bun run dart:analyze, bun run dart:test,
bun run codegen:check. The suite here covers auth (password reset
included), records, queries, batch idempotency, files, seeds, live reload,
export/reset, the connectors passthrough, and the raw HTTP surface.
test/batch_limits_test.dart covers 21/100-operation replay, mixed operations,
late validation/version failures, final-record overflow and the exact 10 MiB
request boundary; failed batches apply no writes. A client still sending past
either body cap, chunked or with its declared length, one byte or 16 MiB past it,
reads the 413 (size_limits_test.dart), and the reader drops the refused rest to
its end, its byte bound or its time bound (size_reader_test.dart).
Field-marker regressions cover create/patch and batch findings, server-assigned
and immutable owners, null writes, unknown fields and the server-managed
profile fields. Their codes follow 05 §5.
Request-time regressions advance the clock across evaluations, delayed request
bodies and concurrent requests, and exercise forged internal time headers.
The attached Functions host is exercised against a scripted stand-in on a real private
socket directory
(test/support/functions_host_fixture.dart):
the connection line and its directory checks (functions_connection_test.dart), answer
framing (functions_relay_test.dart), verbatim forwarding, labels, 100 Continue, early
answers after a lingering or an abrupt close, failed answers, cancellation and the
replaced leftover socket (functions_forward_test.dart), the internal API in both
namespaces with retained generations, handle and generation bounds on an injected clock,
expired credentials and a body past its cap (functions_internal_test.dart), test principals and their
session leases: resolution by handle and ID, every state, the cap and lifetime on the
injected clock, revocation, a lower session limit, reset and checkpoints
(functions_test_principals_test.dart), the reset signal: what the host receives, its
order before the clearing, refusals, a host that never answers (a shortened bound) and
no host (functions_reset_test.dart), and the binary's handshake, line timeout and exit
codes (functions_cli_test.dart). The shared conformance fixture
functions-emulator-internal.json
of @flutterflow/schema, which the schema package checks against the TypeBox shapes and
whose shapes the Bun host imports, is replayed against a live emulator
(functions_conformance_test.dart): its paths, fields and bounds, its principal
requests and backend calls, its test principals resolved against its auth seed with a
lease and release for each ready one, the generated table's verdict on every shape, and
its project, whose config digest the TypeScript canonicalJson computed; its digest
vectors run through canonical_json_test.dart. The real pair, this package compiled
with dart compile exe and the Bun host started by ffx-functions serve, runs in
functions-cli's test/emulator-pair.test.ts.
Specs #
- 26 — Emulator — package layout (§1), the HTTP surfaces (§5.1/§5.2), seeds, live reload, SDK integration, agent-container wiring, the attached Functions host (§11)
- Functions 05 — Emulator and agent workflow — the local host that owns the Functions routes (§2)
- 04 — Database API · 06 — Auth · 07 — Storage · 18 — API Conventions — the contracts it emulates
- 14 — Dart SDK —
useEmulatorhost defaults - 08 — Realtime — watch protocol; local replay and quotas intentionally differ
- 34 — Dynamic Links — the link host's public wire it serves (§7)
Attached Functions host #
Functions are TypeScript, and the Bun-based local Functions host runs them (functions/05 §2); this package runs no function code and holds no Functions admission, receipt, test principal, fixture, secret, outbound, service-invocation, control or diagnostic state. 26 §11 is the normative contract; in short:
| Surface | What it does |
|---|---|
--functions-connection-stdin / FFXEmulator.start(functionsHost: FunctionsHostConnection) |
Attaches the host: the one line {protocol, hostSocket, emulatorSocket, scope: {projectId, environment}} its parent passes on the private stdin (at most 4 KiB within five seconds; nothing after the first newline is read). protocol must be the pair's (FunctionsHostContract.protocol, the schema's FUNCTION_DEVELOPMENT_HOST_PROTOCOL): a line naming another integer protocol, or none, is a host built from another version of the contract and exits 76 (EX_PROTOCOL) with one line naming both versions (FunctionsHostProtocolMismatch). The sockets must be host.sock and emulator.sock in one real directory of mode 0700; any other refused line exits 64 before anything listens, an unbindable socket 69, and no part of the line is logged |
Every request under /v1/functions/ or /emulator/v1/functions/ (raw or as dart:io normalizes it) |
Forwarded to host.sock verbatim (method, raw target, fields, body), less the connection-scoped fields, with FFX-Emulator-Origin: native (loopback peer, loopback Host, no Origin or Sec-Fetch-Site) or public; the host's answer streams back byte for byte with Connection: close. Without a host: 503 functionsNotDeployed |
GET /internal/functions/config on emulator.sock |
The published config generation: {configVersion, configDigest, functions}, where configDigest is the SHA-256 of the schema package's canonicalJson of the whole parsed .ffx/project.json |
POST /internal/functions/principal on emulator.sock |
{authorization, publishableKey} resolved as the data plane resolves them: {principal: null} or {principal: {uid, accountType, claims, credentialDigest}}, or invalidApiKey, tokenInvalid, tokenExpired, sessionRevoked |
POST /internal/functions/backend on emulator.sock |
One FunctionBackendCall of an admitted invocation (FFX-Function-Name, FFX-Config-Version, FFX-Config-Digest, and for an end user Authorization with FFX-Function-Credential-Digest), served by the ordinary data handlers under that generation: caller as the rechecked original credential, service with only the declaration's exact grants; answers a FunctionBackendResult or a FunctionBackendProblem, each checked against its generated schema before it is sent |
POST /internal/functions/testPrincipal on emulator.sock |
A test principal's fixture reference ({ref}: @ and an auth-seed handle, or an end-user ID) resolved against the current auth state: {state: ready, principal: {uid, accountType, claims}}, or missing / disabled with no principal |
POST /internal/functions/testSession and testSession:release on emulator.sock |
{uid} leases one invocation-only session of that end user: {lease, authorization, principal}. It resolves and is revoked like the user's other sessions, but neither counts toward nor evicts them, is never refreshed or checkpointed and is left out of the state's session count; at most 16 live (quotaExceeded), each ended by {lease} release, after 120 seconds, on reset and at shutdown |
POST /internal/functions/reset to host.sock |
The reset signal POST /emulator/v1/reset sends before it clears anything, without a body or FFX-Emulator-Origin, waiting at most 10 seconds for {reset: true}; the reset's answer reports functionsHost: reset, unacknowledged or null without a host |
GET /emulator/v1/state |
functions: {configured, attached}: whether the served config declares functions, and whether a host connection was supplied |
The emulator publishes every valid .ffx/project.json itself, whatever the host's
state, and keeps the last 16 superseded generations for 10 minutes, so an invocation's
backend calls keep the config they were admitted with. A backend upload handle belongs
to the namespace of the call that began it (mode, function, generation and credential)
and is discarded unless completed or aborted within 120 seconds, on reset and at
shutdown. The host connection is a raw socket the emulator reads itself: a host may
answer before it reads the whole request body (an early 413 or a refusal) and close
at once, as Bun.serve does, and the client still gets that answer; the rest of the
body is read and discarded. The emulator answers a client's Expect: 100-continue
itself, since dart:io never does. Live outbound, the fixture file and the
development-secret file are the host's: the reset signal lets it revoke the first and
read the others again before identities clear
(26 §11.3).
The agent supervisor and
ffx-functions serve are the parents that start the Bun host
(@flutterflow/functions-host) through
ffx-functions host --private-bootstrap and pass its line.
Database watches #
/v1/realtime/connect negotiates ffx.realtime.v1 and serves named-query and
single-record watches (lib/src/engine/realtime.dart).
List and subscribe rules intersect before pagination; a record watch needs the
model's get and subscribe rules, and its bootstrap
GET /v1/records/{model}/{id}?consistencyToken=… hides a record outside either
as recordNotFound. Current auth, config identity and bootstrap tokens are
checked. A record write, a function's through the attached host's internal API
included (its reads, and a function's query, never carry a watch's anchor),
invalidates only that record's watches and the watched queries over its model,
and a refused write invalidates nothing. Files and end users live in their own
stores, so every successful write invalidates their watches; seed and config
reloads, auth changes and the emulator's own routes invalidate every watch. A
config reload also closes each connection made under the earlier version with
a fatal, retryable configUnavailable that names no subscription, as the
platform does, so an SDK reconnects and bootstraps its watches again.
Changes coalesce per event-loop turn. A record watch whose record was updated
and stays visible to it receives an event with the record as its bootstrap
read renders it and a patchFromVersion proof, which both SDKs apply without a
read; every other change is a payload-free invalidation. Config reloads force
fresh admission.
Reconnect always queries current state; replay is deliberately ephemeral.
The authenticated preview proxy preserves the subprotocol to the emulator.
owns() and spend() refuse and evaluate as the platform's rules-engine does: both suites run the cases in test/fixtures/payments_rule_cases.json (cel_test.dart here, test/payments-cases.test.ts there), so a change to either engine lands with the fixture. The payments section itself is checked at load with the compiler's words (config_state.dart).
Known-record exists/get expressions use the same bounded policy semantics as the origin (RuleLookups in engine/rules.dart): projected records, short circuiting, 10 paths per rule evaluation (one row or batch operation), a request-local 20-entry LRU cache shared across evaluations, and the origin's 1,000-read request ceiling, re-reads after eviction included. A list query decides rows in page order after its cursor, so a page that reaches the ceiling ends before the undecided row, with hasMore and a token that resumes there; a batch that reaches it is 413 batchTooLarge with failedOperationIndex and applies nothing. Seeded and builder IDs resolve by model prefix. Lookup-dependent watches receive payload-free invalidations when a referenced model changes and recheck read/subscribe rules during snapshot reads. See 05 §3.8.
File access expressions parse when config loads and run for upload creation,
completion, metadata reads/writes, private download links and query/watch
filtering. Create binds the prospective owner, declared size and metadata;
update binds the existing record. Scalar record.metadata.<field> selectors
and the trusted request time use the same CEL semantics as the platform.
File aggregates authorize each matching file under an expression list rule
(05 §4.4). The end-to-end regression is
file_expression_rules_test.dart.
The emulator serves atomic numeric $increment transforms in record PATCH and batch updates with the same zero base for missing values, numeric result bounds, field protections, update rules and replay behavior as the origin. Its synchronous read/check/write section serializes competing updates. See 04 §3.3.
PUT /v1/auth/users/:endUserId/claims/:claim mirrors per-claim delegation, current actor checks, scalar validation, optimistic revisions and original-result replay. The local config acts as the current app policy for isolated emulator identities. Cloud standalone environments use their current serving policy, published or draft; layered environments cannot modify shared real claims. See auth delegation.
Update expressions bind record to the projected pre-image and newRecord to
its projected proposed update. The platform and emulator resolve increments,
clears and the version/time fields before authorizing and persist that exact
candidate. The binding covers model/batch, profile and file metadata updates;
other operations reject it. has(newRecord.field) supports optional fields.
changedFields() lists the top-level fields the update changes (deep
comparison; a writeOnly/serverOnly field whenever the patch names it), so
changedFields().hasOnly(["pinned", "hidden"]) lets moderation fields change
and protects every other field, including ones added later. Never compare a
hidden field with newRecord: callers could test guesses at its value. Both
images retain protected fields for rules; field markers still prevent
forbidden writes. See 05 §2.2.
Expression-authorized aggregates use the existing count/sum/avg API. The origin collects the
records the query matches and evaluates the list rule on each before it contributes, so totals
are per viewer: only records the caller may list count. More than 1000 matches or 1,000
policy lookup reads fail the whole request with the non-retryable 422 aggregateAuthorizationLimitExceeded, never a partial total. The emulator applies the same
bounds, wording and authorization. See 05 §4.4.
Local Google sign-in #
The google provider requires redirectUris in .ffx/project.json. The SDK's
Google start/complete protocol opens /emulator/v1/auth/google, a clearly local
consent page that accepts a test name/email. It never calls Google, needs no
Google credentials, and issues an ordinary FFX session. State, PKCE, exact app
return URLs, one-use grants, disabled users and email collisions are enforced.
Google subjects and sessions survive checkpoints and seed export; pending
OAuth flows/grants do not. Reset removes pending flows as well as test users.
A ticket-authorized preview proxy may supply its own exact /auth/google
return URL via FFX-Emulator-Google-Origin only together with the private
FFX-Connectors-Secret. The proxy never forwards a caller-supplied origin header.
Production allowlists are unchanged. The provider must still be enabled. The
consent page alone is public; other emulator control routes remain private.