Maintainer guide
What this is. A map of the kernel code behind the headless features, and step-by-step instructions for the changes maintainers make most: a field, a datatype mapping, a mutation, an event kind, a schema extension; the tests that cover them; and the release checklist.
When to use it. Before you change anything under kernel/classes/graphql/, the API keys, the CORS layer or the
event journal, or write an extension that adds to the schema.
Quick example: a schema extension that adds the root query ping (put it in an extension, list it in
SchemaExtensionList[]).
use GraphQL\Type\Definition\Type;
class myGraphQLPingExtension implements expGraphQLSchemaExtension
{
public function isAvailable() { return true; }
public function name() { return 'myping/1'; } // part of the schema hash
public function datatypes() { return array(); }
public function fieldMapping( array $attribute, expGraphQLTypes $types ) { return null; }
public function locationFields( expGraphQLTypes $types ) { return array(); }
public function queryFields( expGraphQLTypes $types )
{
return array( 'ping' => array( 'type' => Type::nonNull( Type::string() ), 'description' => 'Answers pong.',
'resolve' => function () { return 'pong'; } ) );
}
}# extension/myext/settings/graphql.ini.append.php
[GraphQLSettings]
SchemaExtensionList[]=myGraphQLPingExtensionphp bin/php/ezpgenerateautoloads.php -e && php bin/php/ezcache.php --clear-tag=ini --allow-root-user
./console exp:graphql:query '{ ping }' # {"data":{"ping":"pong"}, ...}Contents
- Where the code lives
- Design rules
- How a request flows through the classes
- Adding a field
- Adding a datatype
- Adding a mutation
- Adding an event kind
- Adding a setting
- Messages and translations
- The tests
- Running the gates
- The release checklist
- Keeping the SDK in step
Where the code lives
| Path | What |
|---|---|
kernel/classes/graphql/expgraphql.php | expGraphQL: settings access (setting(), intSetting(), listSetting()), isEnabled(), loadLibrary(), the library state |
expgraphqlserver.php | expGraphQLServer: request parsing, persisted queries, the response, validation rules, error formatting and codes |
expgraphqlcontext.php | expGraphQLContext: who asks, how signed in, request id, cache tags, batch loaders, audit, writer |
expgraphqlschemabuilder.php | expGraphQLSchemaBuilder: the schema of a siteaccess, its hash, the root Query |
expgraphqltypes.php | expGraphQLTypes: every kernel type (Content, Location, connections, value types), extension hooks |
expgraphqlclasscatalogue.php | the classes and attributes the schema shows (ClassList[], HiddenFieldList[] ...) |
expgraphqlnaming.php | type and field names (NamingStyle, reserved names) |
expgraphqlfieldmapper.php | datatype → GraphQL type and resolver |
expgraphqlrepository.php, expgraphqlcontent.php, expgraphqllocation.php, expgraphqlconnection.php, expgraphqlsearchconnection.php, expgraphqlbatchloader.php | reading content through the user's policies, pagination, batching |
expgraphqlimage.php, expgraphqlrichtext.php | value objects of images and rich text |
expgraphqlmutations.php, expgraphqlwriter.php, expgraphqlfieldinput.php, expgraphqlupload.php, expgraphqluploadcheck.php, expgraphqldraftcontent.php | mutations, writing, field input, uploads |
expgraphqlpreviewtoken.php | preview tokens |
expgraphqlpersistedqueries.php | the store of persisted queries |
expgraphqlresponsecache.php | the response cache, the early answer, ETags, cache-tag headers, credential cache |
expgraphqlratelimiter.php | rate limits |
expgraphqlevents.php, expgraphqleventlistener.php, expgraphqleventkinds.php, expgraphqleventextension.php | the journal, the listener, package event kinds |
expgraphqlwebhooks.php, expgraphqlwebhookqueuehandler.php | webhooks, the expqueue handler |
expgraphqlsubscriptions.php | subscriptions, SSE |
expgraphqlschemaextension.php, expgraphqlschemaextensions.php, expgraphqlmutationextension.php | the extension interfaces and their loading |
extensions/ | the shipped extensions: tags (expGraphQLTagsExtension), layouts (expGraphQLLayoutsExtension) |
rest/ | expGraphQLRestProvider (routes), expGraphQLRestController, the response classes |
expgraphqlmessage.php, expgraphqlerror.php | translated messages; error codes |
expgraphqlsetup.php, expgraphqlstarter.php, expgraphqlbench.php | Setup > GraphQL, starters, benchmarks |
kernel/graphql/module.php, kernel/private/classes/views/graphql/ | the module graphql (playground, session end point) |
kernel/private/classes/commands/expgraphql*.php, bin/php/expgraphql*.php | the console commands |
kernel/private/classes/cronjobs/graphqlwebhooks.php | the cron part |
kernel/classes/apikey/expapikey.php, kernel/private/rest/classes/auth/apikey_*.php | personal API keys |
kernel/private/rest/classes/cors.php | expRestCors |
index_rest.php | the early answer hook at the top |
settings/graphql.ini, settings/rest.ini, settings/expqueue.ini | settings with their documentation |
share/graphql/starters/ | the starter kits |
tests/tests/kernel/classes/graphql/ | the tests |
doc/eng-us/features/6.0/graphql.md, doc/eng-us/headless/ | the documentation |
The migrations' schema extension (expMigrationGraphQLExtension) lives with the migration code; expwt and
cjw_newsletter bring their own extensions.
Design rules
These hold for every change; reviews check them.
- The user's policies decide. Every resolver reads through the kernel's fetch functions with policy checks
(
canRead(),checkAccess()); never a raw database read that skips them. What the user may not read isnullor left out, never an error that confirms it exists. - The kernel's operations write. Mutations go through
eZOperationHandler(workflows run) or the same collection functions the administration uses, in a transaction, with audit (expGraphQLMutations::run()), cache expiry and a journal event. - No library, no harm. Classes that the early answer, the journal or the error codes need must not depend on
webonyx (
expGraphQLError,expGraphQLEvents,expGraphQLRateLimiter,expGraphQLResponseCache). Files that use the library are loaded only afterexpGraphQL::loadLibrary()succeeded. - Persistent workers. Velocity serves many requests per process: no request state in statics (reset it per
request, as
expApiKeyRest::reset()and the listener's request id do); a newexpGraphQLContextper request. - Stable contract. Error codes, kernel fields, headers, event fields and wire formats only grow (see Compatibility and upgrades).
- Batch, do not loop. A field that resolves something per item of a list uses a batch loader
(
$ctx->loader( kind, language, batch )) and returns a\GraphQL\Deferred. - Cache tags. A resolver that shows content notes its tags (
$ctx->noteContent(),noteCacheTags(),expGraphQLTypes::noteListTags()); a new kind of answer without tags makes cached front ends stale. - No personal data in the journal or webhooks beyond what the record already carries; package event fields are reviewed for it.
- Every message translatable through
expGraphQLMessage::tr(). - Every change documented in both languages (
doc/eng-us/,doc/ger-de/).
How a request flows through the classes
index_rest.php ── expGraphQLResponseCache::serveEarly() (HIT → answer, exit)
└─ ezpKernelRest ─ CORS (expRestCors) ─ auth (expApiKeyRest / OAuth) ─ route (expGraphQLRestProvider)
└─ expGraphQLRestController::doQuery()
├─ expGraphQL::isEnabled(), loadLibrary()
├─ expGraphQLServer::parseHttpRequest()
├─ expGraphQLRateLimiter::hitRequest()
├─ expGraphQLSchemaBuilder::fromSettings() (catalogue, naming, types, field mapper, extensions)
├─ new expGraphQLContext( user, authMode, repository, baseUrl )
└─ expGraphQLServer::respond()
├─ resolvePersisted() (store, APQ, PersistedQueriesOnly)
├─ response cache lookup / write, credential cache
└─ execute(): parse, mutation refusal, validation rules, GraphQL::executeQuery(), formatError()Mutations: expGraphQLMutations::fields() → resolver → run() (audit begin, expGraphQLWriter::<op>(), audit end,
expireCache(), expGraphQLEventListener::mutation()). Events: kernel hooks → expGraphQLEventListener::note() →
end of request → expGraphQLEvents::append(); read by expGraphQLWebhooks::dispatch()/deliver() and
expGraphQLSubscriptions::stream().
Adding a field
A field every content has (Content): add it to expGraphQLTypes::contentFields(), which is shared by the
interface and every class type. Before you do: a field name that a class attribute could have collides (the
attribute is renamed to <name>_field, which changes those classes' schema): prefer names unlikely as attribute
identifiers, and list the reserved names in expGraphQLNaming.
'mainNodeDepth' => array( 'type' => Type::int(), 'description' => 'The depth of the main location.',
'resolve' => function ( expGraphQLContent $c ) {
$main = $c->mainLocation();
return $main instanceof expGraphQLLocation ? $main->depth() : null;
} ),A field of Location from an extension: locationFields() of a schema extension. A root query from an
extension: queryFields(). In the kernel: expGraphQLSchemaBuilder (the root Query).
Checklist for a new field:
- Read through the policies;
nullwhen not readable. - Note cache tags for what it shows.
- Batch when it is per item of a list.
- Description in the schema (one sentence; clients see it in their tools).
- Tests:
expGraphQLSchemaTest(the field is there, its type), a behavior test (what it answers, for a user who may and one who may not read). - Documentation: GraphQL API reference (EN and DE), the feature page.
- The schema hash changes: mention it in the changelog ("regenerate your types").
Adding a datatype
A datatype without a mapping is a String with its toString(). To give it a type:
In an extension (preferred for an extension's datatype): implement datatypes() and fieldMapping() of a schema
extension:
public function datatypes() { return array( 'myrating' ); }
public function fieldMapping( array $attribute, expGraphQLTypes $types )
{
if ( $attribute['datatype'] !== 'myrating' )
return null;
$type = $types->register( 'MyRating', function () {
return new \GraphQL\Type\Definition\ObjectType( array( 'name' => 'MyRating', 'fields' => array(
'stars' => array( 'type' => \GraphQL\Type\Definition\Type::int() ),
'votes' => array( 'type' => \GraphQL\Type\Definition\Type::nonNull( \GraphQL\Type\Definition\Type::int() ) ),
) ) );
} );
return array( $type, function ( eZContentObjectAttribute $field, expGraphQLContext $ctx, array $args ) {
$content = $field->content();
return array( 'stars' => $field->hasContent() ? (int)$content['stars'] : null, 'votes' => (int)$content['votes'] );
} );
}$types->register( name, factory )makes a type once per schema; the name must not be one a content class could take, nor a kernel name (expGraphQLNaming::RESERVED_TYPES).- The resolver gets the attribute of the translation read; return
nullfor an empty field,[]for an empty list. - A relation-like value uses a batch loader.
In the kernel (for a kernel datatype): add it to expGraphQLFieldMapper::MAPPED and a case in mapping(), a
value type in expGraphQLTypes (and its name in RESERVED_TYPES), and expGraphQLDatatypesTest. When its value is a
file, add it to expGraphQLFieldInput::FILE_DATATYPES so it is written by upload only.
Writing. FieldInput.value goes through the datatype's fromString(); make sure it reads what toString()
writes. Document the format in Datatypes in GraphQL and in
exponentialcms-datatypes.
Adding a mutation
In the kernel: add a field to expGraphQLMutations::fields(), a method to expGraphQLWriter, and run it through
expGraphQLMutations::run():
'renameContent' => array(
'type' => $payload,
'description' => 'Sets the name field of content (content/edit).',
'args' => array( 'id' => array( 'type' => Type::nonNull( Type::int() ) ), 'name' => array( 'type' => Type::nonNull( Type::string() ) ) ),
'resolve' => function ( $root, $args, expGraphQLContext $ctx ) {
return expGraphQLMutations::run( 'renameContent', $ctx, $args, array( 'type' => 'object', 'id' => (int)$args['id'] ),
function ( expGraphQLWriter $writer ) use ( $args ) {
return $writer->update( array( 'id' => $args['id'], 'fields' => array( array( 'identifier' => 'name', 'value' => $args['name'] ) ) ) );
} );
},
),run() records the audit (content.graphql.mutation, or .failed with the reason), expires the response cache
unless the status is CANCELLED, and writes the mutation event. The writer method checks the policies (throw
expGraphQLWriter::forbidden() / notFound()), uses the kernel's operation (eZOperationHandler::execute( 'content', '<op>', ..., null, true )) where one exists so workflows run, maps workflow results with workflowStatus(), and
returns status, contentId, nodeId, version, content.
In an extension: implement expGraphQLMutationExtension::mutationFields(); the resolver must call
expGraphQLMutations::refusal( $ctx ) first and throw what it answers. A mutation open to anonymous callers (a
newsletter sign-up) also declares anonymousMutationFields() and guards itself (its own policy check and rate limit),
since refusal() would refuse the anonymous user.
Checklist: policies; the operation and its workflows; idempotency notes (can a retry duplicate?); audit; cache;
event; ContentPayload status; expGraphQLMutationsTest (allowed, refused per rule, the audit lines, the event);
documentation (reference EN/DE, the SDK package
exponentialcms-write).
Adding an event kind
For a package: implement expGraphQLEventExtension::eventKinds() on the extension's schema extension and call
expGraphQLEventListener::packageEvent( $kind, $fields, $objectId, $nodeIds ) where it happens. The kernel validates
the declaration (segments, length, object/policy, at most 20 typed fields), keeps only declared fields, and lists
the kind in exp:graphql:status. Receivers get it only when they name it. Keep personal data out of the fields.
For the kernel: a new core kind is a contract change. Add the constant to expGraphQLEvents, put it in
EXPLICIT (sent only when named, so existing receivers are not surprised), call the listener from the kernel where it
happens (always through note(), written at the end of the request), add it to ContentEventKind, the SDK's
JournalEventKind and tagsForEvent(), and document it in Events, webhooks and subscriptions.
Tests: expGraphQLRealTimeTest, expGraphQLEventKindsTest.
Adding a setting
- Add it to
settings/graphql.ini(orrest.ini) with a comment that says what it does, its values and its default (the comment is the first documentation). - Read it through
expGraphQL::setting( 'Name', <default> )/intSetting()/listSetting(), with the same default in code, so an installation with an old settings file behaves. - If the early answer needs it, remember it with the cache entry (the early answer reads no settings).
- Show it in
exp:graphql:statusand Setup > GraphQL when operators need it. - Document it: the example pages (
doc/eng-us/examples/ini-settings/graphql/), the feature page, the settings tables of these pages; DE too. - If it changes the schema, include it in the schema hash.
Messages and translations
Every text a client or an operator sees goes through expGraphQLMessage::tr( 'English text with %placeholders.', array( '%placeholder' => $value ) ). The context is kernel/graphql; translations live in
share/translations/<language>/translation.ts of every administration catalogue. The language follows
Accept-Language (expGraphQLMessage::useLanguage(), set per request), else the siteaccess's locale. Do not translate
specification messages of the library or PersistedQueryNotFound/PersistedQueryNotSupported (Apollo reads them).
Add new texts to the catalogues (the translation tests list missing ones).
The tests
tests/tests/kernel/classes/graphql/:
| Test | Covers |
|---|---|
expGraphQLSchemaTest | the schema, naming, hidden classes and fields, the hash |
expGraphQLDatatypesTest | every datatype mapping |
expGraphQLRestTest | the HTTP end point: parsing, statuses, headers |
expGraphQLQueryBudgetTest | depth, complexity, list limits |
expGraphQLSearchTest | search |
expGraphQLMutationsTest, expGraphQLWriterSectionsStatesSqliteTest, expGraphQLMutationExtensionTest | mutations, sections and states (SQLite), extension mutations |
expGraphQLPersistedQueriesTest, expGraphQLResponseCacheTest | persisted queries, the cache, early answers |
expGraphQLRateLimiterTest | rate limits |
expGraphQLRealTimeTest, expGraphQLEventKindsTest, expGraphQLWebhookQueueLiveTest | the journal, webhooks, subscriptions, package kinds, queue delivery |
expGraphQLTagsExtensionTest, expGraphQLLayoutsExtensionTest, expMigrationGraphQLExtensionTest | the shipped extensions |
expGraphQLMessageTest | translated messages |
expGraphQLSetupTest, expGraphQLStarterTest, expGraphQLBenchTest | administration, starters, bench |
expGraphQLLibraryMissingTest | the API without the library |
The API keys and CORS have their own tests under tests/tests/kernel/private/restapi/ (expRestCorsTest, key tests).
tests/test-map.json maps source files to the tests the fast gate runs for them.
Run one test file (never a whole directory by path):
php vendor/bin/phpunit --no-coverage tests/tests/kernel/classes/graphql/expGraphQLMutationsTest.phpContract tests of the SDK run against a test installation: EXPONENTIAL_CONTRACT_URL=https://test.example.com npm run test:contract in exponentialcms-client. Never point them at
production.
Running the gates
Before a push to the kernel's main, the same checks the continuous integration runs: PHP lint (8.3 and 8.0), the
manifest (share/filelist.md5 lines of every changed file), phpcs on the diff, PHPStan, and the PHPUnit tests mapped
to the changed files. The fast mode runs them for the changed files only. The full suites run in CI and before a
release. The manifest line of a changed file is its md5 as committed; a documentation page is in the manifest too.
The release checklist
For a release that changes the headless features:
- Contract. No error code, kernel field, header, event field or wire format renamed, removed or changed in meaning (Compatibility and upgrades). New kernel event kinds are explicit.
- Schema.
exp:graphql:schemabefore and after on a reference installation; every difference intended and in the changelog. - Settings. New settings documented in the INI file, the example pages and these pages; defaults safe.
- Security. Policies on every new resolver; nothing readable that was not; mutations audited; no personal data in events; CSRF for sessions; keys only from the header.
- Persistent workers. No request state in statics; tested under Velocity.
- Tests. The mapped tests and the full suites pass; new behavior has tests (allowed and refused).
- Performance.
exp:graphql:benchon a reference installation: cached rows within 33 ms. - Documentation. These pages and the feature page updated in English and German, the changelog
(
doc/changelogs/6.0/<version>.md) lists every change withAdded:/Updated:/Removed:/Renamed:, the history table extended. - Manifest.
share/filelist.md5current for every changed file. - SDK. The client's contract tests pass against the release candidate; SDK packages that need the new feature state the kernel version.
- Version numbers. Chosen from the tags that exist (
git tag -l 'v*' --sort=version:refname,gh release list), never from memory; a published tag is never moved: a mistake is fixed by the next version.
Keeping the SDK in step
| Kernel change | SDK package to update |
|---|---|
| new error code | exponentialcms-client (errors.ts, the code list) |
| new field or type | exponentialcms-codegen (if it needs special handling), exponentialcms-query |
| new datatype mapping or string format | exponentialcms-datatypes |
| rich text changes | exponentialcms-richtext |
| new mutation | exponentialcms-write |
| new event kind or field | exponentialcms-client (events.ts, cache-tags.ts) |
| new header | exponentialcms-client (ClientResult), the CORS guidance (ExposedHeaders[]) |
| new tag kind | exponentialcms-client (tagsForEvent()), the framework packages |