<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Matt Glaman on Medium]]></title>
        <description><![CDATA[Stories by Matt Glaman on Medium]]></description>
        <link>https://medium.com/@mglaman?source=rss-ca6843159bba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vmW4TH6bJ3GmPH2q7GgLLQ.jpeg</url>
            <title>Stories by Matt Glaman on Medium</title>
            <link>https://medium.com/@mglaman?source=rss-ca6843159bba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 17:16:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mglaman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Status codes your API is getting wrong]]></title>
            <link>https://mglaman.medium.com/status-codes-your-api-is-getting-wrong-4c0e67fef0b3?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0e67fef0b3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[json-api]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rest]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 10 Nov 2026 14:00:10 GMT</pubDate>
            <atom:updated>2026-11-10T14:00:10.360Z</atom:updated>
            <content:encoded><![CDATA[<p>My post on <a href="https://mglaman.dev/blog/post-or-put-patch-and-delete-urls-are-cheap-api-design-matters">choosing between POST, PUT, PATCH, and DELETE</a> is still the most-searched page on this site. It modeled an API for restaurant reservations and argued that the HTTP method is part of the contract. The status code you send back is the other half of that contract, and it gets far less attention.</p><p>A developer who hits an error will read the response body and figure out what went wrong. Their code won’t, and an agent calling your API through a tool often won’t either. Both act on the status code. Each code is an instruction to the caller about what to do next.</p><p>More of your API’s callers are going to be agents. Here are the status codes I see APIs get wrong most often.</p><h4>Stop sending errors with a 200</h4><p>This is the one that breaks callers the worst:</p><pre>HTTP/1.1 200 OK<br>Content-Type: application/json<br><br>{&quot;success&quot;: false, &quot;error&quot;: &quot;Reservation not found&quot;}</pre><p>Guzzle, Axios, and fetch all treat that as a success. So does every retry layer and monitoring tool in the chain. Your error rate dashboard shows zero.</p><p>An agent can read the body, but it often doesn’t see your raw response. It sees what the tool wrapping your API hands back, and that tool decided success or failure from the status code. So the agent marks the step as done and moves on. The failure shows up three steps later, somewhere else.</p><h4>Separate client errors from server errors</h4><p>The split between 4xx and 5xx is how a caller decides whether to retry.</p><ul><li>4xx means the caller did something wrong. Sending the same request again will fail the same way. Don&#39;t retry.</li><li>5xx means the server failed. The same request might work in a few seconds. Retry with backoff.</li><li>429 Too Many Requests is the exception on the 4xx side. Retry, but wait. The Retry-After header says how long.</li></ul><p>An uncaught exception from bad input that surfaces as a 500 tells the caller the server broke, not the request. Retry logic will send the same request a few more times and fail each time. An agent might do the same, or decide your API is down and give up. Either way, it never learns that fixing its input would have worked.</p><h4>Return 201 with a Location header on create</h4><p>A POST that creates something returns 201 Created, not 200 OK. <a href="https://www.rfc-editor.org/rfc/rfc9110#name-201-created">RFC 9110</a> says the new resource is identified by the Location header, so send it.</p><pre>POST /reservations HTTP/1.1<br>Content-Type: application/json<br><br>{&quot;time&quot;: &quot;2026-11-20T19:00:00-06:00&quot;, &quot;party_size&quot;: 4}<br><br>HTTP/1.1 201 Created<br>Location: https://example.com/reservations/42<br>Content-Type: application/json<br><br>{&quot;id&quot;: 42, &quot;time&quot;: &quot;2026-11-20T19:00:00-06:00&quot;, &quot;party_size&quot;: 4}</pre><p>The difference matters once a caller retries. Some APIs return 200 when the resource already existed and they handed back the existing one. If create also returns 200, the caller can&#39;t tell &quot;I booked a new table&quot; from &quot;that reservation was already there.&quot; An agent that timed out on its first attempt needs exactly that answer.</p><p>In a Drupal controller, pass the status and header to the response:</p><pre>public function create(Request $request): JsonResponse {<br>  $payload = json_decode($request-&gt;getContent(), TRUE, 512, JSON_THROW_ON_ERROR);<br>  // json_decode() returns mixed. Narrow it before reading keys.<br>  assert(is_array($payload));<br>  $reservation = $this-&gt;reservationStorage-&gt;create([<br>    &#39;time&#39; =&gt; $payload[&#39;time&#39;],<br>    &#39;party_size&#39; =&gt; $payload[&#39;party_size&#39;],<br>  ]);<br>  $reservation-&gt;save();<br><br>  return new JsonResponse(<br>    [&#39;id&#39; =&gt; $reservation-&gt;id(), &#39;time&#39; =&gt; $payload[&#39;time&#39;], &#39;party_size&#39; =&gt; $payload[&#39;party_size&#39;]],<br>    Response::HTTP_CREATED,<br>    // The caller should never have to build this URL itself.<br>    [&#39;Location&#39; =&gt; $reservation-&gt;toUrl()-&gt;setAbsolute()-&gt;toString()],<br>  );<br>}</pre><p>If the work happens later, in a queue or a batch job, return 202 Accepted instead. It tells the caller the request was taken, not finished.</p><h4>Return 204 on delete when there’s nothing to say</h4><p>A successful DELETE has nothing to return. Send 204 No Content with an empty body, not 200 OK with {&quot;success&quot;: true}.</p><pre>public function delete(ReservationInterface $reservation): Response {<br>  $reservation-&gt;delete();<br>  // No body. A 204 with content in it is a protocol error.<br>  return new Response(NULL, Response::HTTP_NO_CONTENT);<br>}</pre><p>DELETE is idempotent: sending it twice leaves the server in the same state as sending it once. The responses don&#39;t have to match. So what should a retry get back?</p><ul><li>404 Not Found. The reservation is gone, so there&#39;s nothing to find.</li><li>204 No Content again. The caller asked for the reservation not to exist, and it doesn&#39;t.</li><li>410 Gone. With a soft delete, like the canceled reservations in the original post, the record still exists. 410 tells the caller the reservation was deleted, not that the URL is wrong.</li></ul><p>404 is the one that trips up agents. An agent that timed out and retried can&#39;t tell &quot;already deleted&quot; from &quot;wrong URL.&quot; Whichever you pick, list it as an expected response in your OpenAPI spec. The tools wrapping your API are often generated from it.</p><h4>Use 409 for conflicts and 422 for invalid input</h4><p>Most APIs return 400 Bad Request for anything wrong with a request. Split it into 409 and 422. Each code tells the caller to do something different.</p><ul><li>400 Bad Request: the request is malformed. The JSON doesn&#39;t parse, or a required header is missing. Fix the request itself.</li><li>422 Unprocessable Content: the request parsed fine, but the values are wrong. The time isn&#39;t a valid date, or the party size is zero. Fix the values and send again.</li><li>409 Conflict: the values are fine, but they clash with the resource&#39;s current state. The reservation was already canceled, or someone else changed it first. Fetch the current state, then decide.</li></ul><p>An agent that gets a 422 should change its input. An agent that gets a 409 should go read what&#39;s there now. If both come back as 400, the agent has to guess from the message text, and it will guess wrong some of the time.</p><p>Entity validation violations map cleanly to a 422. Symfony&#39;s exception still uses the code&#39;s older name, Unprocessable Entity:</p><pre>$violations = $reservation-&gt;validate();<br>if ($violations-&gt;count() &gt; 0) {<br>  // The values are bad, not the request. 422 tells the caller to fix the input.<br>  throw new UnprocessableEntityHttpException((string) $violations);<br>}</pre><p>Changing a canceled reservation is a different failure, so it gets a different code:</p><pre>if ($reservation-&gt;isCanceled()) {<br>  // The new time is valid. The reservation it applies to no longer is.<br>  throw new ConflictHttpException(&#39;This reservation was canceled and cannot be changed.&#39;);<br>}</pre><h4>Look at how Drupal core’s JSON:API does it</h4><p>If you want a reference implementation, Drupal core already ships one. The JSON:API module follows every rule above. From <a href="https://git.drupalcode.org/project/drupal/-/blob/main/core/modules/jsonapi/src/Controller/EntityResource.php">EntityResource::createIndividual()</a>:</p><pre>static::validate($parsed_entity);<br><br>// Return a 409 Conflict response in accordance with the JSON:API spec.<br>if ($this-&gt;entityExists($parsed_entity)) {<br>  throw new ConflictHttpException(&#39;Conflict: Entity already exists.&#39;);<br>}<br><br>$parsed_entity-&gt;save();<br><br>// ...<br>$response = $this-&gt;buildWrappedResponse($primary_data, $request, $this-&gt;getIncludes($request, $primary_data), 201);<br><br>if ($resource_type-&gt;isLocatable()) {<br>  $url = $resource_object-&gt;toUrl()-&gt;setAbsolute()-&gt;toString(TRUE);<br>  $response-&gt;headers-&gt;set(&#39;Location&#39;, $url-&gt;getGeneratedUrl());<br>}</pre><p>Validation runs first and throws a 422. The conflict check comes second and throws a 409. A successful create returns 201 with a Location header. deleteIndividual() ends with return new ResourceResponse(NULL, 204);.</p><p>The comment in <a href="https://git.drupalcode.org/project/drupal/-/blob/main/core/modules/jsonapi/src/Entity/EntityValidationTrait.php">EntityValidationTrait</a> explains the 422 choice succinctly: it lets clients tell apart syntax errors in a bad request (400) from semantic errors in a well-formed one (422).</p><h4>The status code is only half the answer</h4><p>A 422 tells the caller its input was wrong. It doesn&#39;t say which field, or why. A developer can open the docs and work it out. An agent works from whatever the response body gives it.</p><p><a href="https://www.rfc-editor.org/rfc/rfc9457">RFC 9457</a> defines a standard shape for that body, called problem details. It’s an application/problem+json document with type, title, status, detail, and instance members, plus any fields your API needs to add. The RFC is short, and I recommend reading it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0e67fef0b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Naming my Strava runs from Garmin with a Drupal webhook]]></title>
            <link>https://mglaman.medium.com/naming-my-strava-runs-from-garmin-with-a-drupal-webhook-c2b5c1b0ff1c?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b5c1b0ff1c</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 18:38:07 GMT</pubDate>
            <atom:updated>2026-11-06T18:38:07.636Z</atom:updated>
            <content:encoded><![CDATA[<p>When Garmin syncs a run to Strava, it doesn’t send a title or description. Strava falls back to its automatic titles, so a run my coach plan calls “Kenosha — Threshold” shows up as “Lunch Run.”</p><p>On November 4th, I finished a run at about 3:15 PM. Around 4 PM, I asked Claude Code a question about it. At 5:49 PM, that run on Strava had its real name and its workout plan in the description, set by my Drupal site.</p><h4>It started with a question</h4><p>I had recently added Strava and Garmin connections to this site for my fitness page. So I asked:</p><blockquote>My Garmin pushes to Strava but Strava has generic titles. I was wondering if there could be a webhook from Strava that hits my website, it fetches the Garmin activity (strava should track the external ID… I think) and gets the run title/meta from Garmin. Can we try that out?</blockquote><p>Claude Code didn’t start by writing code. It read Strava’s <a href="https://developers.strava.com/docs/webhooks/">webhook documentation</a>, then looked at my real data. It called Garmin through the OAuth2 provider already in my module, using ddev drush php:eval, and read Strava through the Strava connector. Lining the two up answered most of the design questions:</p><p>StartedStravaGarminNov 4, 2:10 PMAfternoon RunKenosha — BaseNov 3, 11:22 AMLunch RunKenosha — ThresholdOct 24, 5:40 AMMorning RunKenosha — Long RunNov 4, 7:30 AMMorning WalkKenosha Walking</p><p>Three rules came out of that data:</p><ul><li>Garmin’s default names, like “Kenosha Running,” are no better than Strava’s. Skip them.</li><li>I often rename runs by hand, like “Track Tuesday.” Only replace Strava’s generic names.</li><li>I write a lot of descriptions. Never overwrite one.</li></ul><h4>My external ID idea was wrong</h4><p>Strava’s API has an external_id on each activity, and its documentation sample shows garmin_push_12345678987654321. I assumed that was the Garmin activity ID. A forum post suggested it might not be anymore. My local site had a Garmin token but no Strava token, so Claude Code read Strava through production, over SSH with drush php:eval, using the OAuth2 services my module already had:</p><pre>$token = \Drupal::service(\Drupal\mglaman_dev\OAuth2\AccessTokenRepository::class)-&gt;get(&#39;strava&#39;);<br>$strava = \Drupal::service(\Drupal\mglaman_dev\OAuth2\ProviderFactory::class)-&gt;get(&#39;strava&#39;);<br>foreach ($activity_ids as $id) {<br>  $url = &quot;https://www.strava.com/api/v3/activities/$id&quot;;<br>  $activity = $strava-&gt;getParsedResponse($strava-&gt;getAuthenticatedRequest(&#39;GET&#39;, $url, $token));<br>  echo json_encode(array_intersect_key($activity, array_flip([&#39;name&#39;, &#39;start_date_local&#39;, &#39;external_id&#39;]))) . PHP_EOL;<br>}</pre><pre>{&quot;name&quot;:&quot;Afternoon Run&quot;,&quot;start_date_local&quot;:&quot;2026-11-04T14:10:01Z&quot;,&quot;external_id&quot;:&quot;garmin_ping_6528…&quot;}<br>{&quot;name&quot;:&quot;Lunch Run&quot;,&quot;start_date_local&quot;:&quot;2026-11-03T11:22:12Z&quot;,&quot;external_id&quot;:&quot;garmin_ping_6522…&quot;}<br>{&quot;name&quot;:&quot;Morning Walk&quot;,&quot;start_date_local&quot;:&quot;2026-11-04T07:30:20Z&quot;,&quot;external_id&quot;:&quot;garmin_ping_6526…&quot;}</pre><p>Then it asked Garmin about those numbers from my local DDEV site, with ddev drush php:eval:</p><pre>$token = \Drupal::service(\Drupal\mglaman_dev\OAuth2\AccessTokenRepository::class)-&gt;get(&#39;garmin&#39;);<br>$garmin = \Drupal::service(\Drupal\mglaman_dev\OAuth2\ProviderFactory::class)-&gt;get(&#39;garmin&#39;);<br>foreach ($external_ids as $id) {<br>  try {<br>    $url = &quot;https://personal.connectapi.garmin.com/activity-service/activity/$id&quot;;<br>    $garmin-&gt;getParsedResponse($garmin-&gt;getAuthenticatedRequest(&#39;GET&#39;, $url, $token));<br>    echo &quot;$id =&gt; found&quot; . PHP_EOL;<br>  }<br>  catch (\Throwable $e) {<br>    echo &quot;$id =&gt; HTTP &quot; . $e-&gt;getCode() . PHP_EOL;<br>  }<br>}</pre><pre>6528… =&gt; HTTP 404<br>6522… =&gt; HTTP 404<br>6526… =&gt; HTTP 404</pre><p>All three were 404s. The real Garmin ID for the first run is 2496…, and none of the external_id numbers showed up in the activity details or search results either. The start time matches. Strava and Garmin agreed to the second on all 40 recent activities we compared, so the code looks up the run on Garmin by its local start time:</p><pre>public function getRunStartedAt(AccessToken $token, string $start): ?array {<br>  $date = substr($start, 0, 10);<br>  foreach ($this-&gt;searchActivities($token, &#39;running&#39;, $date, $date) as $activity) {<br>    $id = $activity[&#39;activityId&#39;] ?? NULL;<br>    $name = $activity[&#39;activityName&#39;] ?? NULL;<br>    if (($activity[&#39;startTimeLocal&#39;] ?? NULL) === $start &amp;&amp; is_int($id) &amp;&amp; is_string($name)) {<br>      return [&#39;id&#39; =&gt; $id, &#39;name&#39; =&gt; $name];<br>    }<br>  }<br>  return NULL;<br>}</pre><p>The first version tried external_id and fell back to start time. Once we had the real value, the external_id path was just a failed Garmin request on every run, so it was deleted before the PR was opened.</p><h4>Receiving the webhook</h4><p>A Strava app gets one webhook subscription, and it covers everything that app’s athletes do. Each event is a small JSON payload that says what changed and gives you IDs, not the activity itself:</p><pre>{<br>  &quot;object_type&quot;: &quot;activity&quot;,<br>  &quot;object_id&quot;: 12345678987,<br>  &quot;aspect_type&quot;: &quot;create&quot;,<br>  &quot;owner_id&quot;: 1234567,<br>  &quot;subscription_id&quot;: 123456,<br>  &quot;event_time&quot;: 1762287001,<br>  &quot;updates&quot;: {}<br>}</pre><p>object_type is activity or athlete, and aspect_type is create, update, or delete. An update lists what changed in updates, like a new title. To get the run&#39;s start time, you call the API with object_id.</p><p>Strava wants a 200 within two seconds, and it doesn’t sign its events. There’s no signature header to check, so anyone who finds the callback URL can post to it. The <a href="https://hookdeck.com/webhooks/platforms/guide-to-strava-webhooks-features-and-best-practices">usual advice</a> is to make the URL itself the secret, with a long random token in the path. That’s what this route does. Its access check compares the token against an environment variable, and if the variable isn’t set, every request is rejected:</p><pre>public function access(string $token): AccessResultInterface {<br>  $secret = $_ENV[&#39;STRAVA_WEBHOOK_TOKEN&#39;] ?? &#39;&#39;;<br>  $allowed = is_string($secret) &amp;&amp; $secret !== &#39;&#39; &amp;&amp; hash_equals($secret, $token);<br>  return AccessResult::allowedIf($allowed)-&gt;setCacheMaxAge(0);<br>}</pre><p>The controller only queues new activities. Updating an activity makes Strava send an update event, and ignoring those keeps this from looping:</p><pre>public function receive(Request $request): JsonResponse {<br>  $event = json_decode((string) $request-&gt;getContent(), TRUE);<br>  if (<br>    is_array($event)<br>    &amp;&amp; ($event[&#39;object_type&#39;] ?? NULL) === &#39;activity&#39;<br>    &amp;&amp; ($event[&#39;aspect_type&#39;] ?? NULL) === &#39;create&#39;<br>    &amp;&amp; is_int($event[&#39;object_id&#39;] ?? NULL)<br>  ) {<br>    $this-&gt;queueFactory-&gt;get(StravaRunName::ID)-&gt;createItem($event[&#39;object_id&#39;]);<br>  }<br>  return new JsonResponse([&#39;status&#39; =&gt; &#39;ok&#39;]);<br>}</pre><p>When you create the subscription, Strava checks the callback URL once with a GET request carrying hub.mode, hub.challenge, and hub.verify_token, and your endpoint has to echo hub.challenge back as JSON. There&#39;s a small PHP trap there. PHP turns the dots in query parameter names into underscores, so you read hub_challenge and answer with hub.challenge.</p><p>Claude Code first wrote the subscription setup as a curl command, which meant exporting my Strava app secrets into the shell. The site&#39;s PHP code already had them, so I had it swapped for a drush php:eval script. Creating the subscription is a change to my Strava account, not my site, so when Claude Code tried to run it over SSH, auto mode blocked the command as an account-level change. It stopped and gave me the command, without looking for another way in. I read it, approved that exact command, and it ran.</p><h4>Reply first, then do the work</h4><p>The first version let cron process the queue. My cron runs every 19 minutes, so a run could keep its generic name that long. A streamed response doesn’t help: the request stays open until the callback finishes, and Strava wants a completed response.</p><p>Inside the request, kernel.terminate is the clean option. I wrote about it back in 2018 in <a href="https://mglaman.dev/blog/flush-and-run-using-kernelterminate-improve-page-speed-performance">Flush and run, using Kernel::TERMINATE to improve page speed performance</a>. A DestructableInterface service runs in the same terminate step, and a crontab line running drush queue:run every minute adds a second place to maintain. So I went with kernel.terminate:</p><pre>public function onTerminate(TerminateEvent $event): void {<br>  $route = $event-&gt;getRequest()-&gt;attributes-&gt;get(RouteObjectInterface::ROUTE_NAME);<br>  if ($route !== StravaWebhook::ROUTE || !$event-&gt;getResponse()-&gt;isSuccessful()) {<br>    return;<br>  }<br>  $queue = $this-&gt;queueFactory-&gt;get(StravaRunName::ID);<br>  $worker = $this-&gt;queueWorkerManager-&gt;createInstance(StravaRunName::ID);<br>  assert($worker instanceof QueueWorkerInterface);<br>  while (($item = $queue-&gt;claimItem(self::LEASE)) instanceof \stdClass) {<br>    $worker-&gt;processItem($item-&gt;data);<br>    $queue-&gt;deleteItem($item);<br>  }<br>}</pre><p>The queue is still the safety net. If the process dies, the item is still there, and cron picks it up when the two-minute lease expires.</p><p>As the 2018 post points out, this needs PHP-FPM. That’s where fastcgi_finish_request() closes the connection, so Strava gets its 200 before the terminate work starts.</p><h4>More than a name</h4><p>Next I asked whether Garmin’s FIT file had anything worth putting in the description. It parsed that run’s file, skipping GPS. There’s plenty in there, including my weight and resting heart rate, which should stay out of Strava.</p><p>The useful part was the workout block, and it turned out nothing needed to parse FIT at all. Garmin’s /activity-service/activity/{id}/workouts endpoint returns the same plan as JSON, including target speeds and repeat steps:</p><pre>{<br>  &quot;stepIndex&quot;: 3,<br>  &quot;intensity&quot;: &quot;ACTIVE&quot;,<br>  &quot;durationType&quot;: &quot;REPEAT_UNTIL_STEPS_CMPLT&quot;,<br>  &quot;durationValue&quot;: 1,<br>  &quot;targetValue&quot;: 3<br>}</pre><p>That step means “go back to step 1, three times through.” The speeds are in meters per second, so WorkoutDescription turns them into paces. The November 3 threshold workout comes out like this:</p><pre>10:00 warm-up at 9:07-10:16/mi<br>3 x 7:00 at 7:33-8:11/mi, 2:00 recovery<br>10:00 cool-down at 9:07-10:16/mi</pre><p>The numbers check out against the run. That plan adds up to 45:00 if the last recovery is skipped, and I ran 45:04. Repeats can also nest, which my anaerobic workouts do:</p><pre>15:00 warm-up at 9:02-10:10/mi<br>3 x (4 x 0:40 at 6:19-6:45/mi, 3:00 recovery), 5:00 recovery<br>10:00 cool-down at 9:07-10:16/mi</pre><p>I typed that same structure into a Strava description by hand in October. This is a chore I was already doing.</p><p>I also asked for hours on long runs, so 150 minutes reads 2:30:00, and for the pace on the cool-down.</p><p>If the formatter finds a step it doesn’t understand, it returns NULL and the run gets no description. A wrong plan is worse than no plan.</p><h4>Expect Garmin to say no sometimes</h4><p>To check the formatter, Claude Code looped over every 2026 run with no delay between requests, and Garmin answered with a 429. Production’s fitness cron logged a failed Garmin refresh at 5:00 PM, right around then. That loop is the likely cause.</p><p>Nothing broke, because the site already expects Garmin to fail now and then. The fitness page serves a stored copy, and the next cron run refreshed it without trouble. Claude Code flagged the 429 on its own, redid the sampling with one request every three seconds over ten runs, and added a note to AGENTS.md about Garmin&#39;s rate limit.</p><p>The webhook works the same way. If a Garmin request fails while renaming a run, the worker logs it and moves on, and that run keeps Strava’s name.</p><h4>What changed for me</h4><p>The PR was +1,147/-6 across 14 files, and about 530 of those lines are tests. It was open for 79 minutes. The whole thing took under two hours, on the same afternoon as the run.</p><p>Writing code faster isn’t the interesting part. Finding out got cheap. Does Strava have webhooks? Is external_id the Garmin ID? Does Garmin keep the workout? What&#39;s in the FIT file? Each of those is a small research task I&#39;d normally put off, and each one got answered against my real accounts before any code depended on it. Ideas like this usually stay in my head, because the first hour is reading API docs to see if it&#39;s even possible.</p><p>Drupal helps here. Queue workers, route access checks, event subscribers, and the key/value store are well-worn patterns, and my module already had examples of each. Kernel tests run the real routes through http_kernel. PHPStan at level 9 and PHPCS caught real problems, and CI still had to pass before anything merged. AGENTS.md tells the agent how the project works, and now it also records what we learned, like not matching on external_id.</p><p>I made the calls. I decided what the feature should do. I pointed Claude Code at <a href="https://github.com/cyberjunky/ha-garmin/pull/32">a PR in ha-garmin</a> that explained the FBT_ADAPTIVE flag on my runs, which marks an activity that came from a generated workout. I decided when to merge. The answers were only useful because I knew what to ask next.</p><h4>What’s next</h4><p>Running the worker by hand on that afternoon’s run proved the Garmin match and the write to Strava. It now reads “Kenosha — Base,” with 1:04:00 at 9:07-10:16/mi as its description.</p><p>That left the real test: an event from Strava, and the update running after the response is sent. My next run passed it. It wasn’t much of a structured workout, but it worked without me touching anything.</p><p>Next, I want strength workouts. “P/L/P: Legs” is a lot better than “Morning Weight Training.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b5c1b0ff1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ContribKanban now tracks GitLab work items]]></title>
            <link>https://mglaman.medium.com/contribkanban-now-tracks-gitlab-work-items-1847e15269ce?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/1847e15269ce</guid>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 12:00:07 GMT</pubDate>
            <atom:updated>2026-10-28T12:00:07.768Z</atom:updated>
            <content:encoded><![CDATA[<p>ContribKanban read issues from Drupal.org’s API, where every issue is a node. When a project moves to GitLab, its new issues are work items, not nodes, so the API stops returning them. Every month, more boards went quiet. Tag boards were the worst. A tag like “Novice” spans migrated and unmigrated projects, and the board only saw the unmigrated half.</p><p>Rosetta is a good example of work that spans both. Dries called it out in his DrupalCon Rotterdam Driesnote and wrote it up in <a href="https://dri.es/one-description-inside-and-outside-drupal">One description, inside and outside Drupal</a>. The goal is for Drupal and outside software to work from shared descriptions of a module’s data and operations. Core issues, like <a href="https://www.drupal.org/i/3352063">allowing schema references in SDC prop schemas</a>, are on Drupal.org. Tool API and MCP track theirs as GitLab work items on git.drupalcode.org. Neither system searches the other.</p><p>Fixing that meant rewriting how boards load issues. While I was in there, I rebuilt the rest of the app to make it easier to maintain. ContribKanban has been around since 2015, and this is its fourth architecture. It <a href="https://mglaman.dev/blog/introducing-contribkanbancom">launched</a> as a MEAN stack app on Parse.com. In 2017, it became a progressively decoupled Drupal 8 site. The <a href="https://mglaman.dev/blog/contribkanban-v3-2020-update">2020 v3 update</a> put a React frontend in front of Drupal. That came at the height of Drupal’s API-First push, and I wanted to dogfood those modules. <a href="https://mglaman.dev/blog/impact-individual-funding-can-make-open-source-maintenance">Every layer of that stack</a> needed its own upkeep.</p><h4>Drupal pages, one React island</h4><p>The board is the only interactive part of ContribKanban. It loads issues from two APIs, sorts them into status columns, and filters them by type and priority without a page reload. Everything else is a form or a list.</p><p>So Drupal renders every page, and React renders only the board. That is close to the 2017 version, where the board template was a single &lt;div id=&quot;Board&quot;&gt; and Drupal passed each list&#39;s configuration to drupalSettings. Drupal handles accounts, forms, listings, access, and layout, which is what it&#39;s good at. The forgot password page, a React stub that said &quot;In progress&quot; for years, now just works because it is Drupal core&#39;s.</p><h4>The board-shell component</h4><p>The new contribkanban theme keeps its markup in single directory components. The board page is the board-shell component. Drupal builds the board&#39;s configuration in PHP and renders it into a data attribute, with an empty column per list so the page has its layout before any JavaScript runs:</p><pre>{# The island replaces these columns. #}<br>&lt;div class=&quot;board-shell__columns&quot; data-board=&quot;{{ config|json_encode }}&quot;&gt;<br>  {% for list in config.lists %}<br>    &lt;section class=&quot;board-column&quot;&gt;<br>      &lt;h2 class=&quot;board-column__header board-column__header--{{ list.tone }}&quot;&gt;{{ list.title }}&lt;/h2&gt;<br>      &lt;p class=&quot;board-column__status&quot;&gt;{{ &#39;Loading issues…&#39;|t }}&lt;/p&gt;<br>    &lt;/section&gt;<br>  {% endfor %}<br>&lt;/div&gt;</pre><p>The board’s configuration is right there in the page, so the island never calls back to Drupal.</p><p>The island’s entry point reads that attribute and mounts:</p><pre>import { createRoot } from &quot;react-dom/client&quot;;<br>import Board from &quot;./Board&quot;;<br><br>for (const element of document.querySelectorAll(&quot;[data-board]&quot;)) {<br>  const config = JSON.parse(element.dataset.board);<br>  const filtersSlot = element.closest(&quot;.board-shell&quot;)?.querySelector(&quot;[data-board-filters]&quot;) ?? null;<br>  createRoot(element).render(&lt;Board config={config} filtersSlot={filtersSlot} /&gt;);<br>}</pre><h4>Building into the component</h4><p>Vite builds the island in library mode, as an IIFE, straight into the component’s directory. The file is named board-shell.js, so the SDC system attaches it through the component&#39;s own library. There&#39;s no separate frontend deploy target and no libraries.yml entry to keep in sync:</p><pre>export default defineConfig(({ command }) =&gt; ({<br>  plugins: [react()],<br>  publicDir: false,<br>  // Library mode leaves process.env alone, and React reads NODE_ENV.<br>  define: command === &#39;build&#39; ? { &#39;process.env.NODE_ENV&#39;: JSON.stringify(&#39;production&#39;) } : {},<br>  build: {<br>    outDir: &#39;../web/themes/custom/contribkanban/components/board-shell&#39;,<br>    // The output directory holds the component&#39;s other files.<br>    emptyOutDir: false,<br>    lib: {<br>      entry: &#39;src/island/main.jsx&#39;,<br>      formats: [&#39;iife&#39;],<br>      name: &#39;ContribKanbanBoard&#39;,<br>      fileName: () =&gt; &#39;board-shell.js&#39;,<br>    },<br>  },<br>}));</pre><p>The define is there because of a gotcha. In library mode, Vite leaves process.env.NODE_ENV alone. It assumes whatever bundles the library later will replace it. Nothing bundles this one, so the built file referenced process, which doesn&#39;t exist in the browser. I only set it for build, so Vitest still gets React&#39;s development build and its warnings.</p><p>Git ignores the built file. The CLI image builds it in a Node stage and copies it in:</p><pre>FROM node:24 AS island<br>WORKDIR /app/frontend<br>COPY frontend/package.json frontend/package-lock.json ./<br>RUN npm ci<br>COPY frontend ./<br>RUN npm run build<br><br>FROM uselagoon/php-8.4-cli-drupal<br># ...<br>COPY --from=island /app/web/themes/custom/contribkanban/components/board-shell/board-shell.js /app/web/themes/custom/contribkanban/components/board-shell/</pre><p>Cards and columns are plain elements styled by the theme’s CSS custom properties. The island’s package.json dependencies are only react and react-dom.</p><h4>Why the browser still fetches issues</h4><p>I considered having Drupal fetch issues and render the whole board in Twig. That puts every viewer behind production’s single GitLab rate limit, so every board would need a server-side cache and a way to invalidate it. Fetching in the browser gives each viewer their own rate limit, and tag boards need no cache.</p><h4>Boards in the GitLab era</h4><h4>Tag boards</h4><p>Drupal.org issue tags became GitLab labels with the same name. The project group&#39;s issues endpoint filters by label, works without a token, and sends CORS headers:</p><pre>export function fetchLabeledWorkItems(label, onPage, signal) {<br>  const params = new URLSearchParams({ labels: label, state: &quot;opened&quot;, per_page: &quot;100&quot; });<br>  return fetchAllPages(`${GITLAB_API_URL}/groups/project/issues?${params}`, onPage, signal);<br>}</pre><p>A tag board now loads the label’s work items once, sorts them into columns by their state:: label, and merges them with Drupal.org&#39;s results. The <a href="https://contribkanban.com/sprint/rosetta-tag">Rosetta board</a> pulls its label from Tool API, Tool Belt, AI Context, and the MCP server tool bridge in one view.</p><p>When a project moves, Drupal.org keeps its old issues as read-only copies, and the API still returns them for the tag. Their status is whatever it was on moving day. For projects that moved, the board skips Drupal.org’s results and uses the GitLab work items instead.</p><h4>Issue collections</h4><p>Tags only cover issues someone tagged. For anything else, there are issue collections, added in the <a href="https://mglaman.dev/blog/contribkanban-2019-update">2019 update</a>: you paste in the issues you want, from any project. For example, the upstream issues your site carries patches for.</p><p>Collections used to hold only Drupal.org node IDs, and GitLab adds two kinds of issues they need to handle. A migrated issue keeps its node ID as its GitLab IID, and its Drupal.org URL names the project. For any issue from a moved project, the island fetches the work item by IID instead of trusting Drupal.org’s frozen copy:</p><pre>GET /api/v4/projects/project%2F&lt;machine_name&gt;/issues?iids[]=&lt;nid&gt;&amp;state=all</pre><p>A work item created on GitLab after the move has no Drupal.org node. Its IID is only unique within its project, and new IIDs overlap unrelated Drupal.org nodes: MCP’s work item 3587791 shares its number with a Thunder issue on Drupal.org. A node ID can’t identify it, so the collection stores the project path with the IID. Paste the work item’s URL and the form keeps both:</p><pre>$patterns = [<br>  &#39;~^https?://git\.drupalcode\.org/(project/[a-z0-9_]+)/-/(?:issues|work_items)/(\d+)(?:[/?#]|$)~&#39;,<br>  &#39;~^(project/[a-z0-9_]+)#(\d+)$~&#39;,<br>];<br>foreach ($patterns as $pattern) {<br>  if (preg_match($pattern, $line, $matches) === 1) {<br>    // Stored as &quot;project/mcp#3587791&quot;.<br>    return $matches[1] . &#39;#&#39; . $matches[2];<br>  }<br>}</pre><p>The island groups them by project and fetches each project’s work items in one request, alongside the Drupal.org issues. One collection can now hold Core’s SDC issue alongside Tool API and MCP work items, each in its status column.</p><h4>Issue roulette and embedded boards</h4><p>With Drupal rendering every page and one island rendering the board, new features no longer needed a frontend release and an API endpoint.</p><h4>Issue roulette</h4><p>Fons Vandamme (<a href="https://www.drupal.org/u/f0ns">f0ns</a>) <a href="https://github.com/mglaman/contribkanban.com/issues/625">opened an issue</a> after a walk: “I can’t pick myself, but I do want to work on something.” Then he built it. The <a href="https://contribkanban.com/roulette?tag=rosetta">issue roulette</a> rolls a strip of open issues for a tag and lands on one. You get three re-rolls.</p><p>The roulette is a second mount point in the same island. Drupal renders an issue-roulette component with the tag boards&#39; tags in data-roulette, and the entry point mounts &lt;Roulette&gt; on it the same way it mounts &lt;Board&gt; on data-board. It loads issues with the board&#39;s hooks, useListIssues for Drupal.org and useWorkItems for GitLab, and draws them with the board&#39;s Card.</p><p>So a tag’s roulette pulls from both systems and skips frozen copies of moved projects, as a tag board does. Only Active, Needs work, and Needs review issues go on the strip, and assigned issues stay off it, since someone already works on those.</p><p>Tag boards and project boards link to the roulette with a die button. The link carries the board’s filters, so rolling from a board filtered to bugs in one milestone only rolls for those bugs.</p><p>Fons also reworked the theme while they were at it: flat, bordered surfaces, restyled lanes and filters, and a header menu that collapses behind a button on small screens.</p><h4>Embedding a board</h4><p>A board can now live in an iframe on another site, like an initiative’s landing page. /board/{machine_name}/embed reuses the board&#39;s full view mode, so it&#39;s the same board-shell component. A page template for the route renders only the main content, without the header or footer:</p><pre>entity.board.embed:<br>  path: &#39;/board/{board}/embed&#39;<br>  defaults:<br>    _entity_view: &#39;board.full&#39;<br>    _title_callback: &#39;\Drupal\Core\Entity\Controller\EntityController::title&#39;<br>  requirements:<br>    _entity_access: &#39;board.view&#39;</pre><p>Core sends X-Frame-Options: SAMEORIGIN on every response, so browsers refuse to frame the page on any other site. An event subscriber removes the header on the embed route. It runs at priority -10, after core&#39;s FinishResponseSubscriber adds the header:</p><pre>public function onResponse(ResponseEvent $event): void {<br>  if ($event-&gt;isMainRequest() &amp;&amp; $this-&gt;routeMatch-&gt;getRouteName() === &#39;entity.board.embed&#39;) {<br>    $event-&gt;getResponse()-&gt;headers-&gt;remove(&#39;X-Frame-Options&#39;);<br>  }<br>}<br><br>public static function getSubscribedEvents(): array {<br>  return [KernelEvents::RESPONSE =&gt; [&#39;onResponse&#39;, -10]];<br>}</pre><p>Dropping the header is safe here because the embed has no forms or links that act for the viewer. Every other page keeps it.</p><p>Each board has an Embed button that copies the iframe. The board’s current filters go into the query string, and the embed applies them without showing the filter bar:</p><pre>&lt;iframe title=&quot;Tool API&quot; src=&quot;https://contribkanban.com/board/tool/embed?milestone=1.0.0-rc1&quot; width=&quot;100%&quot; height=&quot;600&quot;&gt;&lt;/iframe&gt;</pre><h4>What’s next</h4><p>Core component boards stay on Drupal.org until Core’s issues move. When they do, a component will probably become a label on one project, making it a project board with a label filter.</p><p>ContribKanban spent six years as a decoupled app. Now it’s a Drupal site again, and the only JavaScript left is what has to be JavaScript. If you’re working on Rosetta, <a href="https://contribkanban.com/sprint/rosetta-tag">start with its board</a> or <a href="https://contribkanban.com/roulette?tag=rosetta">roll for an issue</a>. If your sprint or initiative tracks work with an issue tag, <a href="https://contribkanban.com/boards/new">make it a board</a> and embed it on your initiative’s page.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1847e15269ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SDCs, Canvas, and the agent skills that build with them]]></title>
            <link>https://mglaman.medium.com/sdcs-canvas-and-the-agent-skills-that-build-with-them-de47943eed87?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/de47943eed87</guid>
            <category><![CDATA[drupalcon]]></category>
            <category><![CDATA[tool-api]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Thu, 08 Oct 2026 13:00:06 GMT</pubDate>
            <atom:updated>2026-10-08T13:00:06.625Z</atom:updated>
            <content:encoded><![CDATA[<p>On September 30th, I presented “SDCs, Canvas, and the Agent That Builds With Them” at DrupalCon Rotterdam. The <a href="https://mglaman.dev/sites/default/files/2026-10/sdcs-canvas-agent-skills-build-with-them.pdf">slides are available as a PDF</a> (1.8 MB).</p><p>I submitted that title in March. By the time I gave the talk, two parts of it were out of date. “The agent” meant one agent, set up through an agent-specific Markdown file. And that agent was going to reach the Drupal site over MCP. Both changed as I built it. What I demoed was a coding agent in a terminal, running Drush, guided by skills shipped inside the modules it used. Hence the new title.</p><p>A week before the conference, I wrote <a href="https://mglaman.dev/blog/define-capability-once-call-it-anywhere">Define the capability once; call it from anywhere</a>, about how I came around on the Tool API once I stopped treating MCP as the center. It ended with what the demo would show: an agent creating an SDC, modeling a Recipe content type, building a content template that binds to the node’s fields, and publishing a page, all through drush tool:run. This post covers how that went and what it didn&#39;t cover: the skills that tell the agent how to use those tools.</p><h4>From MCP to the CLI</h4><p>In March, I planned for the agent to reach the site over MCP. The plan split the work into two parts. The agent writes SDCs on the filesystem, because components are files you commit and review. It reaches the running site over MCP, because pages, templates, and content are stored in a database. Most of my early design effort went into the MCP side: the server, the auth, the tool descriptions.</p><p>The split was right. The transport was not. A coding agent already works in a terminal, and that terminal already has Drush pointed at the site. A Drush call is a tool call, with no server to stand up, no transport to configure, and no auth to wire. The agent doesn’t need a new protocol. It needs to know how to use the CLI it already has, and that is what skills are for. MCP only matters when the site is not on your machine.</p><h4>Give agents a way into Canvas</h4><p>The point of SDCs is that you can write them without being a backend Drupal developer. A component is a folder in a theme’s components/ directory with a .component.yml and a Twig file. Its props are JSON Schema, so it is typed. That also makes SDCs a good fit for agents. An agent edits files all day; that half needs nothing new.</p><p>The other half is putting those components on a page. A Canvas page is state inside a running site, with no file to edit.</p><p>I built <a href="https://www.drupal.org/project/canvas_tools">Canvas Tools</a> to close that gap. It wraps Canvas page building once, keeps all the coupling to Canvas in two services (CanvasManager and AutoSavePublisher), and exposes 21 operations as <a href="https://www.drupal.org/project/tool">Tool API</a> plugins. As that earlier post argued, one #[Tool] plugin serves Drush, MCP, and the AI module.</p><p>In the <a href="https://dri.es/state-of-drupal-presentation-september-2026">DrupalCon Rotterdam keynote</a>, Dries called the Tool module “one of the most important modules for Drupal developers to watch.” He also pointed out that several groups had worked on the same problem and converged on the Tool API. Canvas Tools is one of them. I built it before the keynote, not because of it.</p><p>Canvas Tools uses ordinary tool plugins, one class per operation. Dries’s demo used the attribute-on-methods approach I’m working on for the Tool API. Either way, you expose a capability you own as tools, and every caller gets it.</p><pre>composer require &#39;drupal/canvas_tools:^1.0@beta&#39;<br>drush pm:enable canvas_tools<br><br># tool:run runs as anonymous unless you pass --uid.<br>drush tool:run canvas_list_targets --uid=7 --input=&#39;{&quot;target_type&quot;:&quot;page&quot;}&#39;<br>drush tool:run canvas_list_components --uid=7</pre><p>Pages, page templates (page variants), and content templates are all component trees. The same tools drive all three. You pass a target type and an id.</p><h4>Agents get no special path</h4><p>Every write goes through Canvas’s auto-save store, the same drafts the editor uses. The tools are not a second way into Canvas. They are the editor’s own path, called from somewhere else.</p><p>Auto-save is keyed by the object being edited, not by who is editing it. That has three useful results:</p><ul><li>There is no back door. The tools check the entity’s own access, so hook_entity_access() and per-entity access modules apply.</li><li>An editor left open on a page sees the agent’s changes land as it works.</li><li>What the agent builds is an ordinary Canvas draft. Nothing goes live until you publish, and you choose what to publish.</li></ul><p>Each plugin declares whether it is destructive, so an agent or a harness knows before it calls:</p><pre>#[Tool(<br>  id: &#39;canvas_add_component&#39;,<br>  // ...<br>  operation: ToolOperation::Write,<br>  // Writes to a draft. Discard it or publish it; nothing is lost.<br>  destructive: FALSE,<br>  // ...<br>)]</pre><p>Eighteen of the 21 tools write to a draft. Three are marked destructive: TRUE: canvas_delete_page, canvas_delete_component, and canvas_discard_auto_save. If you want to gate an agent, gate those three. You don&#39;t need to know anything about Canvas to do it.</p><h4>From one agent file to skills</h4><p>The tools give an agent typed inputs. They don’t tell it which values are valid on this site, or what order to call things in. In March I would have put that in a Markdown file for one agent. What I ended up with is <a href="https://agentskills.io/specification">Agent Skills</a> that ship in the modules themselves.</p><p>There are two kinds.</p><p><strong>The mechanics.</strong> The Tool module ships use-drupal-tools, plus create-tool-plugins for people writing their own tools. use-drupal-tools is not about Canvas. It teaches an agent how to call any Tool API operation: find it, read its contract, run it. The main rule is to never copy input names out of an example.</p><pre>drush tool:search &quot;canvas page&quot; --format=json<br>drush tool:info canvas_add_component --format=json   # input_schema is the contract<br>drush tool:run canvas_add_component --uid=7 --input=&#39;{...}&#39; --json</pre><p><strong>The workflows.</strong> Canvas Tools ships four skills, one per job:</p><ul><li>author-sdc-component: write an SDC into the theme, then verify Canvas accepts it.</li><li>build-content-template: lay out how a bundle renders and bind props to the entity&#39;s fields.</li><li>build-canvas-page: build a standalone landing page and publish it.</li><li>build-page-template: build the full-page template and make it the site default.</li></ul><p>author-sdc-component matters most, because its second step is the one an agent skips. A component is only usable in Canvas if its props schema matches a shape Canvas understands. You find that out after a cache rebuild, not before. So the skill says write, then verify:</p><pre>drush cache:rebuild<br>drush tool:run canvas_list_components --uid=7 | grep callout   # sdc.&lt;theme&gt;.callout<br>drush tool:run canvas_get_component_schema --uid=7 \<br>  --input=&#39;{&quot;component_id&quot;:&quot;sdc.&lt;theme&gt;.callout&quot;}&#39;             # props, enums, slots</pre><p>If the component is missing, or a prop didn’t come through, Canvas rejected that shape. The agent fixes the YAML and runs it again instead of assuming it is fine.</p><p>These skills live in each module’s .agents/skills/ directory. <a href="https://www.drupal.org/project/ai_best_practices">AI Best Practices</a> discovers skills from Composer packages and syncs them into your project&#39;s .agents/skills/ on composer install. Require the module, and the agent gets the workflow, not just the tools. And because it is a plain folder, it doesn&#39;t matter which agent reads it. Claude Code, Cursor, and opencode all pick it up.</p><p>You can write your own alongside the shipped ones. Tool Belt ships the content-modeling tools but no skill, so I wrote a model-content skill in the demo project to create a content type, add fields, and seed nodes.</p><p>That was the biggest change between the proposal and the talk. I stopped configuring one agent and started writing skills for the tools.</p><h4>The demo</h4><p>The demo started with a design. I used Claude Design to produce a coffee and baking shop: a welcome page, a recipe page, the components behind both, and a handoff document. The handoff listed every component with its props and allowed values, the page trees, and the content fields the recipe page implies. The design side never touched Drupal.</p><p>I built it with Claude Code in four steps, pointing it at the handoff document rather than screenshots. The clips in the talk are recordings of real runs. One change for recording: I patched Canvas to check for unpublished changes every 200ms instead of every 10 seconds, so the editor updates quickly on screen.</p><p><strong>Author the SDCs.</strong> The agent built all eight components from the handoff, then audited them. For the audit, I used the Drush commands proposed in <a href="https://www.drupal.org/project/canvas/issues/3585531">Canvas #3585531</a>, patched into the demo site. canvas:component:status reports the incompatible components and exits non-zero, so the same command can gate CI. Without being asked, the agent also rendered each component with its optional props empty to catch Twig errors, and listed what the design left unspecified.</p><p><strong>Model the content.</strong> The Recipe content type and fourteen fields, through <a href="https://www.drupal.org/project/tool_belt">Tool Belt</a> over the same tool:run surface. Each field is two operations: storage, then instance. No batch operation exists, so the agent wrote a shell loop. Then it created the Stroopwafels sample recipe in one entity_create call.</p><p><strong>Build the display.</strong> A content template for node.recipe.full. The hero&#39;s title, intro, and image bind to the node&#39;s fields. Canvas refused two bindings in the design. The difficulty level is an enum prop, and an enum takes a static value, never a field. The callout&#39;s required title and body would not bind to optional fields, because an optional field can&#39;t promise a value. The agent is on the editor&#39;s path, so it inherits the editor&#39;s rules. It set static values and kept going.</p><p><strong>Build a page.</strong> The welcome page used the same operations against a different target. A landing page has no host entity, so every value is a literal from the handoff. Partway through, canvas_get_component_schema failed on components that have no slots. The agent said so, read the .component.yml files directly instead, and kept building. That bug is fixed now in <a href="https://git.drupalcode.org/project/canvas_tools/-/work_items/26">#26</a>: a newer Tool API release started validating tool outputs, and an empty PHP array failed the check for a required map. Nothing changed on the front end until canvas_publish_auto_saves ran.</p><p>Then I opened the site with no agent involved. The recipe page rendered through the content template the agent built. The welcome page was a normal Canvas page. Both open in the editor, and a site builder can keep going from there.</p><h4>MCP is still there</h4><p>Everything in the demo is also available over MCP, with no extra code. Enable <a href="https://www.drupal.org/project/mcp_server">MCP Server</a> and <a href="https://www.drupal.org/project/mcp_server_tool_bridge">MCP Server Tool Bridge</a>, and Canvas Tools ships an mcp_tool_config entity for each operation. Over MCP, canvas_create_page comes back as tool_api__canvas_create_page.</p><p>So the split from March holds, with a different default. SDC work belongs on a developer’s machine, because it produces files someone reviews and commits. Page building against a site you have a shell on goes over Drush. Page building against a site you don’t have a shell on goes over MCP.</p><p>Remote MCP is not a five-minute setup yet. You have to say who is calling. Over HTTP, that means OAuth, and mcp_server_oauth is still in alpha. That is a decision for each team, and plenty of teams won&#39;t want that endpoint in production.</p><h4>What is still rough</h4><p>Canvas has no public API, so Canvas Tools is tied to Canvas versions on purpose. The Canvas 1.11.0 upgrade proved it: page templates replaced theme regions, and the bridge had to follow. Keeping that coupling in two services is the trade-off. Canvas Tools absorbs each Canvas release, so the sites, scripts, and agents calling the tools don’t have to. The alternative was waiting for an API that doesn’t exist yet.</p><p>An agent can’t clear an optional prop yet. A new component keeps its example values, and canvas_update_component_props can only set values, not remove them. In the demo, a heading section kept its example body text on the published page. The agent noticed and asked me to clear it in the editor. That is <a href="https://git.drupalcode.org/project/canvas_tools/-/work_items/27">#27</a>.</p><p>The MCP tool configs live in config/optional, which only imports when a module is installed. Tools added in a later release have to be imported by hand. That bit my demo site twice.</p><p>The Tool API and MCP Server are both in beta. The Tool API is headed for core, at least in part. The skills will move with it, which is the reason they ship next to the code instead of in my agent’s configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de47943eed87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplytest.me can launch Drupal CMS site templates]]></title>
            <link>https://mglaman.medium.com/simplytest-me-can-launch-drupal-cms-site-templates-2646e74a2147?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/2646e74a2147</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[drupal-cms]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 12:00:08 GMT</pubDate>
            <atom:updated>2026-09-18T12:00:08.194Z</atom:updated>
            <content:encoded><![CDATA[<p>About a week ago, I wrote about <a href="https://medium.com/blog/simplytestme-should-be-good-enough-sell-drupal">the simplytest.me rewrite</a> and closed on what was next: site templates and recipes. You can now launch a sandbox for a site template. I’m excited that people can now easily try out all the site templates on Simplytest.me.</p><h4>Pick a template, not just a project</h4><p>The home page now has a button that opens a modal listing the available site templates: screenshot, creator, launch link per card. The data comes from <a href="https://git.drupalcode.org/api/v4/projects/204857/repository/files/site-templates.yml/raw?ref=HEAD">the same curated list</a> Drupal CMS’s installer uses for templates.</p><p>The modal lists every imported template. Filtering is a text search over name, description, and creator, not category pills — the curated list has no category field to filter on. Screenshots are hotlinked from each creator’s own infrastructure and fall back to a placeholder when one 404s.</p><h4>Share one base across every template</h4><p>Each launch builds:</p><pre>composer require drupal/&lt;template&gt;<br>composer drupal:recipe-unpack<br>drush si ../recipes/&lt;template&gt;</pre><p>Installing from the recipe path, not the drupal_cms_installer profile — that profile installs a theme partway through the install and rebuilds the installer&#39;s container without its synthetic services, which is the failure the Drupal CMS demo already routes around.</p><p>The drupal_cms base preview this builds on isn&#39;t new. <a href="https://github.com/simplytestme/website/pull/640">PR #640</a> is what made a base preview hold a complete, installed project instead of a bare Drupal checkout, and gave Drupal CMS its own base name so one-click demos could clone it instead of building from scratch. Templates don&#39;t clone (a recipe apply is database work specific to that template, so there&#39;s nothing to snapshot ahead of time) but they launch on top of the same daily-rebuilt base rather than starting from an empty Composer project.</p><p>The open question was whether every template also gets its own base. Timed against real Tugboat builds:</p><p>timebase-drupal_cms (Composer run, no site installed, rebuilt daily)119sByte launch60sHealthcare launch87s</p><p>Healthcare declares ~65 requirements and only 14 are missing from the shared base, so its composer require step runs in 9.7s. The rest — 33s for Byte, 48s for Healthcare — is the recipe apply, and that&#39;s the part no base preview can cache away. A dedicated base per template would cut launches to seconds, but that&#39;s 16 extra daily installs to save 60 seconds. Shared base wins, and promoting a template to its own base later is a simple config flip if one ever needs it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2646e74a2147" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Define the capability once; call it from anywhere]]></title>
            <link>https://mglaman.medium.com/define-the-capability-once-call-it-from-anywhere-6d69cb4dc93e?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d69cb4dc93e</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[drupalcon]]></category>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 13:00:08 GMT</pubDate>
            <atom:updated>2026-09-15T13:00:08.431Z</atom:updated>
            <content:encoded><![CDATA[<p>Drupal’s <a href="https://www.drupal.org/project/tool">Tool API</a> lets you declare an operation one time — typed inputs, typed outputs, an access check — and then invoke it from Drush, from MCP, from ECA, or from a controller. I spent a good while arguing against it before I understood that, and my DrupalCon Rotterdam session is now built on top of it. Here is what changed my mind.</p><h4>Another abstraction in another module</h4><p>I first heard about the Tool module through the AI initiative, and that is roughly where I filed it. A plugin type for well-described, self-contained operations — declare what a thing does, what typed inputs it takes, what typed outputs it returns. Drupal has a track record of generalizing a problem before anyone has finished understanding the problem, and agent tooling was very much an unfinished problem. Locking in a contract that early usually costs more than it saves.</p><p>It stopped being an abstract objection when I started looking at mcp_server. On <a href="https://www.acquia.com/products/source">Acquia Source</a>, we already had our own MCP module built directly on the <a href="https://github.com/modelcontextprotocol/php-sdk">official MCP PHP SDK</a>. It worked. But maintaining a private implementation of a public protocol is a bad long-term position, so the goal was to align with the community module instead of carrying our own.</p><p>I found an MCP implementation with the Tool API underneath it. Aligning meant adopting not just a protocol server but a plugin type I had already decided was premature — and we would be trading a working thing for it. That is a real cost when the abstraction is unproven, and the protocol isn’t.</p><p>Mateu (<a href="https://www.drupal.org/u/e0ipso">e0ipso</a>) has since pulled the two apart. <a href="https://www.drupal.org/project/mcp_server">mcp_server</a> is the protocol runtime and nothing more — it requires only php and mcp/sdk at the Composer level — and the Tool API integration spun out into <a href="https://www.drupal.org/project/mcp_server_tool_bridge">mcp_server_tool_bridge</a> as its own project.</p><p>That split says the instinct about mcp_server was right. A protocol server should be a thin integration between Drupal and the SDK, and that is what it is now.</p><p>What I had backward was the other half. I was judging the Tool API entirely as a tax on getting MCP working, which is the wrong frame — MCP is one caller among several. I did not see that until I started thinking about the others.</p><h4>The Action API objection</h4><p>My other complaint was that Drupal already has this. Action plugins are executable, access-checked units of work. Why not extend them?</p><p>I took that to Michael Lander (<a href="https://www.drupal.org/u/michaellander">michaellander</a>), expecting a philosophical answer. I got a backward compatibility answer instead, and it is more persuasive.</p><p>Look at what an action actually promises. Here is ExecutableInterface on 11.x:</p><pre>interface ExecutableInterface {<br><br>  /**<br>   * Executes the plugin.<br>   *<br>   * @todo Uncomment the new $object method parameter before drupal:12.0.0.<br>   */<br>  public function execute(/* ?object $object = NULL */);<br><br>}</pre><p>No return type. No typed inputs. No declared outputs. Adding one optional parameter is a Drupal 12 change, and it has been sitting commented out waiting for the major.</p><p>ActionInterface is more honest about it. The docblock carries a @todo WARNING list of additions the API was supposed to receive — context awareness, configuration handling, a data processing API — with issue links going back to 2013. None of it landed.</p><p>So the question is not “could actions do this.” It is “how many minor releases and how many downstream contrib breaks does it cost to get typed inputs, declared outputs, operation semantics, and per-invocation access onto an interface a decade of code already implements?” The answer is: more than building alongside it. The abstraction I was calling overhead was the faster path.</p><h4>What made it click: stop thinking about MCP</h4><p>The shift was thinking about callers instead of protocols.</p><p>A tool declares a capability. It does not know who is invoking it. Define the capability once, and every caller gets it:</p><pre>drush tool:list --operation=read --format=markdown<br>drush tool:info canvas_create_page --format=json<br>drush tool:run canvas_create_page --input=&#39;{&quot;title&quot;:&quot;Pricing&quot;,&quot;path&quot;:&quot;/pricing&quot;}&#39;</pre><p>Same plugin over MCP stdio. Same plugin from ECA. Same plugin from a controller. --format=json on tool:info means a developer running an agent locally gets the input contract read back before anything is called, with no protocol server in the loop at all.</p><h4>What I built with it</h4><p>That reframing produced <a href="https://www.drupal.org/project/canvas_tools">Canvas Tools</a>, which is what the session demos.</p><p>The problem it solves is specific. <a href="https://www.drupal.org/project/canvas">Drupal Canvas</a> 1.x ships no public API — the authoring surface is @internal top to bottom — and it had no Tool API integration. So the module wraps Canvas&#39;s authoring behavior once, keeps all the coupling in two services, and exposes the result as typed operations. The agent never imports a Canvas class. When 1.x internals shift, one service changes.</p><p>The rule that makes it safe to run unattended: mutations write to Canvas’s auto-save store, never a direct save. Create makes an unpublished draft. “Published” is intent carried in the auto-save and realized atomically when canvas_publish_auto_saves runs. A whole page gets built across a dozen operations and either goes live in one commit or gets opened in the Canvas editor for review first. That is Canvas&#39;s own draft path, the same one a human editor rides. Nothing about it is agent-specific.</p><p>Here is one operation, trimmed:</p><pre>#[Tool(<br>  id: &#39;canvas_create_page&#39;,<br>  label: new TranslatableMarkup(&#39;Create Canvas page&#39;),<br>  description: new TranslatableMarkup(&#39;Create a new Drupal Canvas page. The page entity is always created as an unpublished draft, so it never appears live with an empty layout. With published=TRUE (the default) the page is marked to go live the next time auto-saves are published.&#39;),<br>  operation: ToolOperation::Write,<br>  destructive: FALSE,<br>  input_definitions: [/* typed inputs */],<br>  output_definitions: [/* page_id, uuid */],<br>)]<br>final class CreateCanvasPageTool extends CanvasToolBase {<br><br>  protected function doExecute(array $values): ExecutableResult { /* … */ }<br><br>  protected function checkAccess(array $values, AccountInterface $account): bool { /* … */ }<br><br>}</pre><p>The description is doing real work. It is the only thing a non-deterministic caller reads before deciding to invoke, so it documents the draft semantics rather than the happy path. ToolOperation::Write says this mutates and is not idempotent. destructive: FALSE says do not prompt; canvas_delete_page sets TRUE and callers confirm first.</p><p>checkAccess() is abstract on ToolBase, so every tool has to answer the access question. Canvas Tools answers it by delegating to $entity-&gt;access() rather than checking a bare permission, which means hook_entity_access() and per-entity access modules still apply to an agent exactly as they apply to a person.</p><h4>The seam is what generalizes</h4><p>The interesting part is not the Canvas plumbing. It is that drupal/tool_belt was already doing the same thing for content modeling, with no coordination between us:</p><pre>tool_belt                          canvas_tools<br>content type + fields → nodes   →  content template + binding → page</pre><p>tool_belt builds the data model and seeds content. Canvas Tools owns display: content templates, page regions, pages. No overlap, no shared code, and an agent chains straight through the two because both are #[Tool] plugins with typed outputs. That composition is what I didn&#39;t see when I argued that actions could cover this.</p><p>Field binding is where the typing earns itself. canvas_bind_component_props binds a component prop to a host entity field, and it validates against the same candidate set the Canvas editor offers in a site builder. Bind a boolean field to a string prop, and it is rejected up front with the list of valid fields, instead of failing silently at render.</p><h4>The part I did not expect: I am now filing issues against it</h4><p>Building roughly twenty operations against the Tool API surfaced the gaps you only find by using something hard.</p><p>tool:run was masking failure messages by reading outputs from a failed tool (<a href="https://git.drupalcode.org/project/tool/-/work_items/3582942">#3582942</a>, fixed in tool 1.0.0-beta3). Tools with no inputs at all were uncallable over MCP, because the bridge emits empty properties as a JSON array and the SDK&#39;s validator wants an object — a PHP-to-JSON footgun, fixed in <a href="https://git.drupalcode.org/project/mcp_server_tool_bridge/-/merge_requests/2">mcp_server_tool_bridge MR !2</a> and released in 1.0.0-beta1.</p><p>The bigger one is still open (<a href="https://git.drupalcode.org/project/tool/-/work_items/3582943">#3582943</a>): a consumer can read <em>what</em> tools exist but not enough about them to drive one safely. tool:info flattens an input to its data type — it shows variant: string, not that it only accepts info|success|warning. Required permissions are not listed. checkRequirements() failures are not surfaced, so tool:list happily shows an agent a tool it cannot run. Most of that metadata is already declared in the model. It just is not introspectable from the outside.</p><p>Which is a much better problem to have than the one I thought I had. “This abstraction is premature” turned into “this abstraction needs to expose more of what it already knows.” I would rather argue about the second.</p><h4>The whole arc, at DrupalCon Rotterdam</h4><p>The demo runs it end to end: an agent authors an SDC, models a Recipe content type, lays out a content template with props bound to the node’s own fields, and publishes a page — every step a drush tool:run call, and nothing live until publish. Then the same operations over MCP, with no extra code.</p><p><a href="https://events.drupal.org/rotterdam2026/session/sdcs-canvas-and-agent-builds-them"><strong>SDCs, Canvas, and the Agent That Builds With Them</strong></a> — Wednesday 30 September, 15:00, Van Oldenbarnevelt Room.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d69cb4dc93e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[simplytest.me should be good enough to sell Drupal with]]></title>
            <link>https://mglaman.medium.com/simplytest-me-should-be-good-enough-to-sell-drupal-with-9c496868bdb6?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c496868bdb6</guid>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 13:00:07 GMT</pubDate>
            <atom:updated>2026-09-08T13:00:07.085Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://simplytest.me/">simplytest.me</a> had been sitting in the back of my mind for a long time. I knew it was unstable, and that release information kept falling out of date. It was a constant battle that always needed another round of maintenance, and it kept sliding.</p><p>Then Ryan Szrama <a href="https://www.linkedin.com/posts/ryanszrama_someone-cold-called-the-centarro-phone-number-share-7499188209386422272-vtyd">wrote about someone cold calling the Centarro phone number</a> looking for a way to sell online. <a href="https://www.drupal.org/project/commerce_kickstart">Commerce Kickstart</a> already did what the caller needed, so instead of selling him an engagement, Ryan pointed him to simplytest.me to try it.</p><p>That was the kick I needed. The person Ryan sent over was a merchant with no Drupal background, deciding whether Drupal was worth his time off a sandbox alone. What he would have found worked, but not reliably, and it looked like a hobby project rather than a product anyone was standing behind.</p><p>The list was not short. Core versions stopped updating. The progress page hammered Tugboat. The advanced options had a handful of bugs that broke builds outright. The home page still led with a photo hero and yellow accents, the headline set on top of the photo where it was hard to read.</p><p>Over five days, I worked through most of that, using Claude Code for the implementation and Claude Design for the redesign. This is what shipped, and how. The full details are in the <a href="https://github.com/simplytestme/website">simplytestme/website</a> pull requests, #579 through #608.</p><h4>Start with tests, not the refactor</h4><p>A large frontend rewrite and a backend cleanup were both coming. The custom modules sat at 52% line coverage, so the first PR was tests. Coverage went to 89%, and CI now fails under 85%. PHPUnit 9 has no built-in threshold, so scripts/coverage-check.php reads the Clover report and lists the least covered files when it fails.</p><p>Every new test is Unit or Kernel. Functional tests run in a separate process, so Xdebug never sees that code, and they cannot move the number. Kernel tests run the real container through http_kernel, so routing and controller wiring get covered instead of method bodies in isolation.</p><p>Writing tests against existing behavior found five real bugs before any refactoring started. The worst one: ProjectRefresher::processItem() caught EntityValidationException, but entity storage wraps preSave() throwables in EntityStorageException. The catch never fired, and a project failing validation took the whole queue worker down. PHPStan had the dead catch baselined.</p><pre>try {<br>  $project-&gt;save();<br>}<br>catch (EntityStorageException $e) {<br>  // Entity storage wraps whatever preSave() threw, so the validation<br>  // exception arrives as the previous exception rather than directly.<br>  $validation_exception = $e-&gt;getPrevious();<br>  if (!$validation_exception instanceof EntityValidationException) {<br>    throw $e;<br>  }<br>  $this-&gt;logger-&gt;error(sprintf(<br>    &quot;Validation errors when saving project %s: %s&quot;,<br>    $project-&gt;label(),<br>    implode(&#39;|&#39;, $validation_exception-&gt;getViolationMessages())<br>  ));<br>}</pre><p>The tests also found that every project route was going to Fastly as private. ModifyMaxAgeResponseSubscriber called setMaxAge() before core ran, Symfony appended private, and core skipped setResponseCacheable() because the header was already customized. The fix is entirely in the priority:</p><pre>public static function getSubscribedEvents(): array {<br>  return [<br>    // In Symfony a higher priority runs earlier, so this has to be negative<br>    // to run last. Core&#39;s FinishResponseSubscriber writes Cache-Control at<br>    // priority 0 and http_cache_control adds s-maxage at -10; running before<br>    // either of them means writing a header they then rebuild.<br>    KernelEvents::RESPONSE =&gt; [&#39;onResponse&#39;, -100],<br>  ];<br>}</pre><p>Running last brought a second problem into view. The fastly module copies Cache-Control into Surrogate-Control at priority 0, and Fastly prefers Surrogate-Control over s-maxage, so the edge would have kept the site-wide 32-day lifetime. The subscriber rewrites that header&#39;s max-age to the CDN lifetime from http_cache_control.</p><h4>Stop spamming Tugboat</h4><p>The sandbox progress page polled its status endpoint every 3 seconds with setInterval. Each poll made the controller call the Tugboat API twice. Nothing stopped on a failed build, so a failed sandbox polled Tugboat every 3 seconds for as long as the tab stayed open.</p><p>Server-side, an in-progress job still returns an uncacheable JsonResponse, because a job that is still changing has to be re-read on every poll. What changed is the error handling and the finished case. A 404 from Tugboat returns a JSON body saying the sandbox is gone, and any other client or transport failure returns a 502 JSON body instead of an exception page, so the poller gets something it can parse either way.</p><p>Finished previews are the one state worth caching, and only briefly:</p><pre>// A preview is a finished job: its state only changes when the sandbox<br>// expires, so browsers and the page cache may hold it briefly.<br>if ($instance_state[&#39;type&#39;] === &#39;preview&#39;) {<br>  $response = new CacheableJsonResponse($instance_state);<br>  $metadata = (new CacheableMetadata())<br>    -&gt;setCacheMaxAge(self::PREVIEW_MAX_AGE)<br>    -&gt;addCacheContexts([&#39;url.path&#39;]);<br>  $response-&gt;addCacheableDependency($metadata);<br>  // Core writes the site-wide max-age into Cache-Control regardless of<br>  // the response&#39;s cacheability metadata; setting it here marks the<br>  // header as customized so the finite lifetime survives.<br>  $response-&gt;setMaxAge(self::PREVIEW_MAX_AGE);<br>  return $response;<br>}</pre><p>Sixty seconds, and finite on purpose. Sandboxes are deleted two hours after creation, so a permanently cached “ready” would keep redirecting people to a dead preview.</p><p>Which leaves the client as the thing that actually has to stop asking. Polling is now a chained setTimeout, so the next request is only scheduled after the current one finishes:</p><pre>const poll = async () =&gt; {<br>  let json;<br>  try {<br>    const res = await fetch(stateUrl);<br>    if (!res.ok) {<br>      throw new Error(`Status request failed with ${res.status}`);<br>    }<br>    json = await res.json();<br>  } catch (e) {<br>    failures += 1;<br>    if (failures &gt;= MAX_FAILURES) {<br>      setError(true);<br>      return;<br>    }<br>    // Back off so a struggling backend gets 6s, 12s, 24s, 48s of air.<br>    schedule(POLL_INTERVAL * 2 ** failures);<br>    return;<br>  }<br><br>  failures = 0;<br>  setState(json);<br>  // A preview means the job finished; a failed job never becomes one.<br>  // Either way the state is final and polling must stop.<br>  if (json.type === &quot;preview&quot;) {<br>    return;<br>  }<br>  schedule(POLL_INTERVAL);<br>};</pre><p>Failed builds, 404s, and previews are all terminal states. Errors back off exponentially and give up after five straight failures.</p><h4>Stop spamming Drupal.org</h4><p>This one was worse, and it was the real reason core versions had gone stale. simplytest.me generated around 36,000 requests a day against the Drupal.org JSON API (api-d7):</p><ul><li>The refresher fetched every project’s usage count individually: 250 projects every 10 minutes, requeued after 4 hours.</li><li>Cron crawled paginated core release listings for five majors.</li><li>The autocomplete imported from Drupal.org on every unmatched search string.</li></ul><p>That is one environment. simplytest.me runs on amazee.io’s Lagoon, which builds an environment per pull request, and those ran drush cron too. Every open Dependabot PR was another copy of the core release crawl.</p><p>Then requests started failing. Our user agent is supposed to be allowed through, but something was blocking one or two of our egress IPs anyway. Cron’s core version updates failed silently.</p><p>The fix removes every background and implicit api-d7 request. What remains is explicit user action.</p><p><strong>Refresher diet.</strong> ProjectRefresher updates release data only, using conditional GETs against updates.drupal.org rather than the API that was failing. The usage count refresh is deleted: usage only orders autocomplete results, and relative popularity does not change fast enough to justify that traffic. Cron queues projects stale by a week instead of 4 hours, capped at 250 instead of 1250.</p><p><strong>Freshness on demand.</strong> The versions and compatibility endpoints refresh a project’s releases inline when they are more than 6 hours stale. Data is fresh exactly when someone looks at a project.</p><p><strong>Explicit lookup.</strong> The autocomplete only searches known projects. When nothing matches, the form offers “Look up on drupal.org”, backed by a POST endpoint flood-limited to 20 lookups an hour per client. Deep links like /configure?project=pathauto go through the same endpoint, so maintainers linking to their own project still get an import.</p><p><strong>Core versions from release history.</strong> CoreVersionManager::updateData() reads the release history feed instead of crawling api-d7:</p><pre>$channel = $major_version === 7 ? &#39;7.x&#39; : &#39;current&#39;;<br>$release_xml = $this-&gt;fetcher-&gt;getProjectData(&#39;drupal&#39;, $channel, self::STATE_KEY_SUFFIX);</pre><p>The current channel carries every 8+ major in one document, so a single conditional request refreshes them all, and the later calls for other majors short-circuit on the 304. That fixed <a href="https://www.drupal.org/project/simplytest/issues/3593391">#3593391</a> without needing to know what was blocking us. I asked in #drupal-infrastructure afterward, and Neil Drumm didn&#39;t see any 403s from our user agent at the WAF, so whatever it was didn&#39;t show up there either. By then, the traffic was gone and updates were working again, so I didn&#39;t press it.</p><h4>Redesign with Claude Design</h4><p>I gave Claude Design two screenshots (the home page and the form with advanced options open), connected it to the repo so it could read the existing React and PostCSS, and one prompt:</p><blockquote>Help me redesign Simplytest.me, the service that lets users test out Drupal. The design and form aren’t very friendly.</blockquote><p>What came back first was questions, not designs. My answers:</p><pre>audience: First-timers evaluating Drupal, agency folks doing client demos, trainers and camp presenters<br>problems: Form is intimidating, advanced options are a dumping ground, hero image hurts legibility, weak visual hierarchy<br>scope: Rethink the whole page<br>form_shape: Card with progressive disclosure<br>screens: Home / launch form, advanced options expanded<br>brand: Open to a full rebrand<br>variations: One strong direction<br>notes: Centarro is using this as a way to sell Drupal Commerce, it can be a way to easily test Drupal CMS, and I want to add the ability to test Drupal Site Templates easily</pre><p>Before anything new got drawn, I had it recreate the current site from the theme’s React components and PostCSS, so there was a baseline to compare against. Then a second round on visual direction:</p><pre>vibe: Clean product marketing. Light, generous space, big type<br>palette: Keep Drupal blue, drop the yellow<br>type: Sans + mono pairing<br>hero_hierarchy: Curated demos first, search second<br>background: Solid or subtle-gradient hero</pre><p>That was all the input. The output was a handoff bundle: the redesign as HTML with six labeled screens (home, browse site templates, advanced options, building, sandbox ready, build failed), the current-site recreation, and a README with exact tokens. Every color has a hex and a use. Every type role has size, weight, and tracking. The README is explicit that the HTML is a design reference, not production code, and that the target is the existing React components and Tailwind theme with no new framework.</p><p>I handed that bundle to Claude Code and asked it to rebuild the frontend from the handoff. PR #586 came in at +11,047/-35,461. What changed:</p><ul><li>The home page leads with tiles (Drupal CMS, Commerce Kickstart, Umami), and the project search comes second. The OneClickDemo plugin gained description, weight, and recommended properties so the tiles are data-driven.</li><li>Advanced options are grouped into Environment, Patches, and Extra projects, each with an explanation column.</li><li>The progress page has dedicated Build, Ready, and Failed screens. The five-step checklist derives from stage markers already in the build log, so no backend progress work was needed.</li><li>The failed screen offers “Edit and try again” and “Launch without the patch” prefills. The ready screen offers a shareable relaunch link.</li><li>Header, hero, and footer are hardcoded inTwig. The theme settings form and layout block config are gone. Claro is no longer the base theme.</li><li>Laravel Mix and Gulp are replaced by one Vite build. Plus Jakarta Sans and Space Mono are self-hosted. All tokens live in tailwind.config.js.</li></ul><p>The site templates tile ships with a disabled “Browse templates” button. The picker modal is designed but deliberately not built until template launches are supported.</p><h4>Fix the patch bugs</h4><p>Two Drupal.org issues, one of which had been open since March 2023.</p><p><a href="https://www.drupal.org/project/simplytest/issues/3348026">#3348026</a>: selecting an additional project without patching it broke the build. The form renders a patch field for every project and posts them verbatim, so every unpatched project submitted an empty string, and the generator turned each one into a real patch entry. composer-patches takes an empty URL at face value and fails the whole update. The documented workaround was to paste a throwaway patch URL into every field.</p><pre>private function getSubmittedPatches(array $patches): array {<br>  $urls = [];<br>  foreach ($patches as $patch) {<br>    $patch = trim((string) $patch);<br>    if ($patch !== &#39;&#39;) {<br>      $urls[] = $patch;<br>    }<br>  }<br>  return $urls;<br>}</pre><p>Dropping empties in PreviewConfigGenerator rather than the form covers the JSON POST, ?patch= prefill links, and one-click demos in one place.</p><p><a href="https://www.drupal.org/project/simplytest/issues/3588836">#3588836</a>: patches that used to apply stopped applying. Sandboxes required szeidler/composer-patches-cli at ~1.0, which now resolves to a version allowing cweagans/composer-patches 2.x. Sandboxes silently moved to 2.x. 1.x tried several -p levels and fell back to GNU patch, which tolerates fuzz. 2.x uses git apply at one fixed depth, and git apply has no fuzz at all.</p><p>The CLI only existed to edit JSON we already generate, so it is gone. The module writes patches.json directly, which unlocks the expanded format the CLI could not emit:</p><pre>{&quot;patches&quot;: {&quot;drupal/core&quot;: [{<br>    &quot;description&quot;: &quot;STM patch 5876.diff&quot;,<br>    &quot;url&quot;: &quot;https://git.drupalcode.org/project/drupal/-/merge_requests/5876.diff&quot;,<br>    &quot;depth&quot;: 2,<br>    &quot;extra&quot;: {&quot;freeform&quot;: {<br>        &quot;executable&quot;: &quot;patch&quot;,<br>        &quot;dry_run_args&quot;: &quot;-p%s -d %s --dry-run --no-backup-if-mismatch -i %s&quot;,<br>        &quot;args&quot;: &quot;-p%s -d %s --no-backup-if-mismatch -i %s&quot;<br>    }}<br>}]}}</pre><p>Depth is explicit per package. The freeform patcher falls back to GNU patch only after the git patchers refuse, restoring the 1.x behavior without pinning to 1.x. Merge request .patch URLs are rewritten to .diff, because the .patch form is a full commit series and any file it touches outside the patch depth aborts the apply. Failed patches now say why, with the actual Hunk #1 FAILED line on the failure page instead of Composer&#39;s usage synopsis.</p><h4>Validate what the launch endpoint accepts</h4><p>The launch endpoint accepted any non-blank string for the core version and install profile. The form only ever sends known releases and one of three profiles, but the endpoint is an anonymous JSON POST and the form is not its only possible client. Tugboat accepts a preview before the installer runs, so a made-up profile still produced a “successful” launch, and the value is interpolated straight into drush si.</p><p>The install profile is now a Choice constraint over standard, minimal, and demo_umami. The core version gets a CoreVersion constraint that checks the release exists in the same table the dropdown reads:</p><pre>#[Constraint(<br>  id: &#39;CoreVersion&#39;,<br>  label: new TranslatableMarkup(&#39;Drupal core version&#39;, [], [&#39;context&#39; =&gt; &#39;Validation&#39;]),<br>)]<br>final class CoreVersionConstraint extends SymfonyConstraint {<br><br>  public string $message = &#39;There is no Drupal core release with the version @version.&#39;;<br><br>}</pre><p>Attribute-based discovery, not the annotation the older PatchesUrl constraint still uses. The validator resolves CoreVersionManager through ContainerInjectionInterface. It returns early on an empty string, since NotBlank already reports that and one message per field is enough.</p><p>This mattered for the next change. Anything submitted here ends up in the sandbox’s Composer command and on a public page.</p><h4>Record what gets launched</h4><p><a href="https://www.drupal.org/project/simplytest/issues/3541515">#3541515</a> asked for usage analytics. The issue pointed at Tugboat’s statistics endpoints. Those answer how much: active previews, build durations, failure rates. They cannot answer what. Every preview is named simplytest and built from the base branch. The project, version, and core release live inside the build config, which Tugboat does not index. So the composition data has to come from us.</p><p>Every launch now writes a row through LaunchRecorder, called from InstanceManager::launchInstance(). That location is deliberate: one-click demos go straight from their controller to the instance manager and never touch the launch form. InstanceManager is the one point both paths reach. Failed launches are recorded too, because a launch that never reached Tugboat leaves nothing behind there. A failed insert is logged and never thrown, so analytics cannot turn a working launch into an error page.</p><p>The record holds what was launched, never who. No IP, no user agent, no session. Patch counts, not patch URLs, because a patch URL names the issue somebody is testing. The schema test asserts that stays true:</p><pre>// The launch record deliberately holds nothing that identifies a person.<br>$columns = array_keys($table[&#39;fields&#39;]);<br>self::assertNotContains(&#39;hostname&#39;, $columns);<br>self::assertNotContains(&#39;uid&#39;, $columns);<br>self::assertNotContains(&#39;patches&#39;, $columns);<br>self::assertContains(&#39;patch_count&#39;, $columns);</pre><p>The report is at <a href="https://simplytest.me/statistics">simplytest.me/statistics</a>: totals for 7 days, 30 days, and all time, a per-day chart, and breakdowns by project, core release, install profile, and project type. It is plain aggregate queries in a service, not Views, rendered through the site’s first single directory component. The report is cached by time, never by tag, since tagging would invalidate it on every launch.</p><h4>What is next</h4><p>Site templates and Drupal recipes. Both are Drupal.org projects, so the existing shortname lookup already finds them. What does not fit is the shape of a launch. Today, that is one project on a core version, and a recipe launch is core with a set of recipes applied on top- three of them, if that is what someone wants to try.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c496868bdb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[phpstan-drupal 2.1.0: stricter defaults]]></title>
            <link>https://mglaman.medium.com/phpstan-drupal-2-1-0-stricter-defaults-71d467e4f580?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d467e4f580</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[phpstan-drupal]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 14 Jul 2026 17:18:54 GMT</pubDate>
            <atom:updated>2026-07-14T17:18:54.714Z</atom:updated>
            <content:encoded><![CDATA[<p>phpstan-drupal 2.1.0 is out. The theme of this release: rules and behaviors that proved themselves as opt-ins are now the defaults. If you run `composer update` and see new errors, that is the release working as intended — everything below includes the configuration to opt back out.</p><h4>Nine rules are now enabled by default</h4><p>These rules shipped as opt-ins over the 2.0 cycle. They have had time to bake, and they catch real bugs, so they no longer require configuration:</p><ul><li>testClassSuffixNameRule</li><li>dependencySerializationTraitPropertyRule</li><li>accessResultConditionRule</li><li>cacheableDependencyRule</li><li>hookFormAlterRule</li><li>loggerFromFactoryPropertyAssignmentRule</li><li>entityStorageDirectInjectionRule</li><li>symfonyYamlParseRule</li><li>entityOperationsCacheabilityRule</li></ul><p>Disable any of them individually if they don’t fit your project:</p><pre>parameters:<br>   drupal:<br>       rules:<br>           cacheableDependencyRule: false</pre><p>One rename to watch for: hookRules is now hookFormAlterRule. If your phpstan.neon references the old key, PHPStan will reject the configuration until you rename it.</p><h4>ContainerInterface::has() returns bool now</h4><p>Previously, $container-&gt;has(&#39;some.service&#39;) resolved to always-true for any service the service map knew about. PHPStan then flagged the guard as redundant:</p><pre>if ($this-&gt;container-&gt;has(&#39;some.service&#39;)) {<br>   // &quot;Comparison will always evaluate to true&quot; — so you delete the guard.<br>   $this-&gt;container-&gt;get(&#39;some.service&#39;)-&gt;doThing();<br>}</pre><p>That guard is not redundant. Modules get uninstalled. Site builds differ. The static analyzer knowing about a service does not guarantee the runtime container has it. Deleting the check trades a static-analysis warning for a production crash.</p><p>This behavior shipped in bleedingEdge.neon first and has now graduated: has() returns bool for known services by default. If you want the old inference back:</p><pre>parameters:<br>   drupal:<br>       bleedingEdge:<br>           containerHasAlwaysTrue: true</pre><h4>A three-year-old one-line fix: LoadIncludes</h4><p><a href="https://github.com/mglaman/phpstan-drupal/pull/587">PR #587</a> from donquixote sat open since 2023. The LoadIncludes rule — which verifies $module_handler-&gt;loadInclude() points at a file that exists had its type check inverted:</p><pre>// Before: bails on concrete ModuleHandler, fires on plain object/mixed.<br>if (!$type-&gt;isSuperTypeOf($moduleHandlerInterfaceType)-&gt;yes()) {<br>   return [];<br>}<br><br>// After: fires only when the receiver is definitely a ModuleHandlerInterface.<br>if (!$moduleHandlerInterfaceType-&gt;isSuperTypeOf($type)-&gt;yes()) {<br>   return [];<br>}</pre><p>The practical effect: code that type-hints the concrete ModuleHandler class was silently skipped for years. It gets checked now, so you may see new loadIncludes.* errors in code that never changed. Those are real findings, not regressions.</p><h4>Opting out of class resolver narrowing</h4><p>ClassResolverInterface::getInstanceFromDefinition(Foo::class) narrows to Foo. Usually right, but the class resolver checks the container first, and a service definition can substitute an entirely different class. With the narrowed type, this defensive assertion gets flagged as always-true:</p><pre>$foo = $this-&gt;classResolver-&gt;getInstanceFromDefinition(Foo::class);<br>assert($foo instanceof Foo);</pre><p>The narrowing stays on by default because it is correct for the overwhelming majority of code. If you want your assertions to keep meaning something:</p><pre>parameters:<br>   drupal:<br>       classResolverReturnType: false</pre><h4>Supporting 2.0.x</h4><p>2.1.0 introduces new errors by default. So 2.0 is not abandoned.</p><p>If you hit a bug on 2.0.x, <a href="https://github.com/mglaman/phpstan-drupal/issues">open an issue</a> and note the version. When you are ready to move to 2.1, the <a href="https://github.com/mglaman/phpstan-drupal/releases/tag/2.1.0">release notes</a> walk through every behavior change with its opt-out.</p><h4>Thanks</h4><p>donquixote for the LoadIncludes fix, Niklan for the detailed report that shaped classResolverReturnType, and <a href="https://www.fame.fi/">Fame Helsinki</a> for sponsoring the project. If phpstan-drupal saves your team time, <a href="https://github.com/sponsors/mglaman">consider sponsoring</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d467e4f580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic type expressions in Drupal config schema]]></title>
            <link>https://mglaman.medium.com/dynamic-type-expressions-in-drupal-config-schema-4c7b8d0ecd11?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7b8d0ecd11</guid>
            <category><![CDATA[drupal]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 13:18:54 GMT</pubDate>
            <atom:updated>2026-04-07T13:18:54.472Z</atom:updated>
            <content:encoded><![CDATA[<p>Drupal’s config schema YAML supports dynamic expressions inside square brackets that resolve to values from the surrounding configuration data at runtime. Most developers have seen them — [%parent.type] in field formatter schema is a classic example — but few understand exactly how they work or when to use them.</p><p>I found a Todoist task from December 4th, 2024: \Drupal\Core\Config\TypedConfigManager::replaceVariable blog post. (Yeah, you do not want to see my &quot;Overdue&quot; list.) I have no memory of what I was working on that day or why I went deep on this. But past-me clearly thought it was worth documenting, so here we are. If you&#39;ve ever stared at [%parent.type] in a schema file and just accepted it as magic — this one&#39;s for you.</p><p>This post covers the mechanics, the available expression tokens, and three patterns: resolving a schema type from a sibling value, keying sequence items as associative arrays, and resolving a schema type from within the element itself. The constraint system uses the same resolution logic without brackets. The <a href="https://www.drupal.org/docs/drupal-apis/configuration-api/configuration-schemametadata#dynamic-types">Configuration API documentation</a> covers dynamic types at a higher level — this post goes deeper into how resolution actually works.</p><p><strong>Drupal 11 note:</strong> TypedConfigManager::replaceVariable() and TypedConfigManager::replaceName() were deprecated in Drupal 10.3 and removed in Drupal 11. The logic moved to Drupal\Core\Config\Schema\TypeResolver, which is marked @internal. The YAML syntax itself is unchanged — only the PHP implementation was refactored.</p><h4>The mechanics</h4><p>Before diving into the internals, here’s the pattern in its simplest form. Given this schema:</p><pre>field_formatter:<br>  type: mapping<br>  mapping:<br>    type:<br>      type: string<br>    settings:<br>      type: field.formatter.settings.[%parent.type]</pre><p>When the stored config has type: text_default, the settings property resolves its schema type to field.formatter.settings.text_default. The expression [%parent.type] is replaced at runtime with the sibling value.</p><p>When Drupal processes a config schema definition, TypedConfigManager::buildDataDefinition() builds the schema definition for each element. Before looking up the schema type, it collects contextual data for the current element:</p><ul><li>%parent — the parent typed data object</li><li>%key — the element&#39;s key within its parent</li><li>%type — the schema data type of the current element</li></ul><p>It then calls TypeResolver::resolveDynamicTypeName(), which scans the type string for [expression] patterns and replaces each one with the resolved value from TypeResolver::resolveExpression().</p><pre>// Drupal\Core\Config\Schema\TypeResolver<br><br>public static function resolveDynamicTypeName(string $name, mixed $data): string {<br>  if (preg_match_all(&quot;/\[(.*)\]/U&quot;, $name, $matches)) {<br>    $replace = [];<br>    foreach (array_combine($matches[0], $matches[1]) as $key =&gt; $value) {<br>      $replace[$key] = self::resolveExpression($value, $data);<br>    }<br>    return strtr($name, $replace);<br>  }<br>  return $name;<br>}</pre><p>resolveExpression() walks a dot-separated path through the data. When it encounters %parent, it switches the data context to the parent element&#39;s values and adds %parent, %key, and %type into scope. This is recursive — %parent.%parent.%type resolves two levels up.</p><h4>Expression tokens</h4><p>TokenResolves to%parentThe parent element (switches data context)%keyThe current element&#39;s key in its parent — most useful in sequences, where keys are unknown to the schema and the key itself carries meaning (e.g. third_party_settings)%typeThe schema data type of the current element — only valid after %parent</p><p>Tokens are combined with dots: %parent.targetEntityType resolves to the targetEntityType sibling value. %parent.%key resolves to the parent element&#39;s key within its own parent.</p><h4>Dynamic type resolution</h4><p>The most common use is constructing a schema type name from a sibling value. Field formatters use this to map each formatter plugin’s type value to its settings schema:</p><pre># core/config/schema/core.entity.schema.yml<br><br>field_formatter:<br>  type: mapping<br>  mapping:<br>    type:<br>      type: string<br>      label: &#39;Plugin ID&#39;<br>    settings:<br>      type: field.formatter.settings.[%parent.type]<br>      label: &#39;Settings&#39;<br>    third_party_settings:<br>      type: sequence<br>      sequence:<br>        type: field.formatter.third_party.[%key]</pre><p>When Drupal builds the schema for settings, %parent points to the field_formatter mapping, and %parent.type resolves to the value of the type key — e.g. text_default. The schema type becomes field.formatter.settings.text_default. Each plugin module can define field.formatter.settings.my_formatter_id: in its own schema file.</p><p>The sequence example uses %key. In a mapping, the schema defines the type of data stored by each named key. In a sequence, the keys are unknown to the schema — a single schema definition applies to every item regardless of what key it&#39;s stored under. third_party_settings stores data keyed by module name, and %key resolves to that key at schema build time. So a third-party settings entry from my_module resolves to field.formatter.third_party.my_module, letting each module define its own schema for its own data.</p><h4>Resolving from within the element, not the parent</h4><p>The expressions above use %parent to walk up the tree. You can also resolve a value from within the current element&#39;s own data by referencing a key directly — no %parent needed.</p><p>Block visibility conditions demonstrate this:</p><pre># core/modules/block/config/schema/block.schema.yml<br><br>block.block.*:<br>  type: config_entity<br>  mapping:<br>    plugin:<br>      type: string<br>      label: &#39;Plugin&#39;<br>      constraints:<br>        PluginExists:<br>          manager: plugin.manager.block<br>          interface: Drupal\Core\Block\BlockPluginInterface<br>    settings:<br>      type: block.settings.[%parent.plugin]<br>    visibility:<br>      type: sequence<br>      label: &#39;Visibility Conditions&#39;<br>      sequence:<br>        type: condition.plugin.[id]<br>        label: &#39;Visibility Condition&#39;</pre><p>settings uses [%parent.plugin] — the value of plugin is a sibling, so you need %parent to reach it.</p><p>visibility is a sequence. Each item in the sequence is itself a mapping that contains an id key. When Drupal builds the schema for a sequence item, the expression [id] resolves against that item&#39;s own data — no %parent required. A condition stored as { id: request_path, pages: /foo } produces a schema type of condition.plugin.request_path.</p><p>The distinction: use %parent.key when the value you need is in the parent (a sibling property). Use key directly when the value is inside the element being typed.</p><h4>Dynamic constraint arguments</h4><p>Constraints often need context that isn’t contained in the constrained property itself. Without dynamic expressions, you’d need a separate schema definition for every entity type to validate that a bundle value is valid. The same resolution logic that drives type expressions is available to constraint option values — without the square brackets.</p><p>The canonical example is core.entity_view_display.*.*.*:</p><pre># core/config/schema/core.entity.schema.yml<br><br>core.entity_view_display.*.*.*:<br>  type: config_entity<br>  label: &#39;Entity display&#39;<br>  mapping:<br>    targetEntityType:<br>      type: string<br>      label: &#39;Target entity type&#39;<br>    bundle:<br>      type: string<br>      label: &#39;Bundle&#39;<br>      constraints:<br>        EntityBundleExists:<br>          entityTypeId: &#39;%parent.targetEntityType&#39;</pre><p>The bundle property carries an EntityBundleExists constraint. That constraint needs to know which entity type to check bundles against. Rather than hard-coding it, entityTypeId: &#39;%parent.targetEntityType&#39; tells the constraint to resolve targetEntityType from the parent mapping at validation time.</p><p>When TypedConfigManager::buildDataDefinition() processes the bundle element, it passes the current data and its parent context into resolveExpression(). The string %parent.targetEntityType walks up to the parent mapping and reads the targetEntityType value from the actual config data — e.g., node.</p><p>The result: a single schema definition validates the bundle value against the correct entity type for any core.entity_view_display.*.*.* config object, with no duplication. The same pattern applies to core.entity_form_display.*.*.*.</p><h4>What you can’t do</h4><p><strong>Expressions fail silently.</strong> If targetEntityType is missing from the config data, resolveExpression() returns the original expression string unchanged rather than throwing an error. The constraint then receives the literal string %parent.targetEntityType as its entityTypeId option. The constraint will still fail, but with a confusing error about an entity type that doesn&#39;t exist rather than a clear message about the missing value.</p><p><strong>%type is only valid after </strong><strong>%parent.</strong> The expression %type alone throws a \LogicException. It must be %parent.%type or deeper.</p><p><strong>Square brackets are only for </strong><strong>type values.</strong> Constraint option strings use the %parent.key syntax without brackets. Putting brackets in a constraint option value won&#39;t trigger dynamic resolution.</p><p><strong>TypeResolver is </strong><strong>@internal.</strong> Don&#39;t call TypeResolver::resolveExpression() directly from contrib or custom code. If you need to traverse the typed data tree in PHP — for example, inside a constraint validator — use the typed data API directly through the TypedDataInterface methods available on the validated object.</p><h4>Summary</h4><p>Dynamic expressions give config schema three capabilities: constructing a schema type from a sibling value ([%parent.type]), keying sequence items as associative arrays ([%key]), and constructing a schema type from within the element itself ([id]). Constraint option values use the same resolution logic without brackets, letting a single schema definition validate a property against context that lives elsewhere in the config object.</p><p>The practical takeaway: when a config property’s valid values depend on a sibling property, reach for %parent.siblingKey in a constraint option. When a config property&#39;s schema type depends on a sibling value, use [%parent.siblingKey] in the type field. Core uses both patterns extensively — now you understand why they work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7b8d0ecd11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Drupal’s chained fast backend keeps APCu cache consistent across your web servers]]></title>
            <link>https://mglaman.medium.com/how-drupals-chained-fast-backend-keeps-apcu-cache-consistent-across-your-web-servers-36a8dd6a19db?source=rss-ca6843159bba------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a8dd6a19db</guid>
            <category><![CDATA[drupal]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Matt Glaman]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 12:38:50 GMT</pubDate>
            <atom:updated>2026-03-31T12:38:50.528Z</atom:updated>
            <content:encoded><![CDATA[<p>Drupal’s cache.backend.chainedfast makes your site faster without any configuration. All you need is to have APCu on your server. It shows up in the bootstrap, config, and discovery cache bins, and most developers never think about it or even know it is being leveraged.</p><p>The chained-fast backend combines two backends: a <strong>fast, inconsistent backend</strong> (APCu, local to each web server process) and a <strong>consistent backend</strong> (the database, which is shared across all servers). APCu alone is dangerous in a multi-server environment because each server has its own copy of the data; invalidations on one server don’t propagate to others. The chained backend solves this with a <strong>last-write timestamp</strong>.</p><p>Every write to a chained bin records a timestamp in the consistent backend and writes data to both backends. On a read, ChainedFastBackend checks APCu first, but before returning the cached item, it compares the item&#39;s creation timestamp against the stored last-write timestamp. If the item was written <em>before</em> the last write timestamp, it&#39;s considered stale and discarded. The backend then falls back to the database, fetches the current item, and populates APCu to keep future reads fast.</p><p>This design has one significant consequence: <strong>every write to a chained bin invalidates all other items in that bin</strong>. When the write timestamp advances, anything in APCu with an older timestamp becomes stale on the next read. That’s why Drupal restricts the chained fast backend to bins like bootstrap, config, and discovery, which have infrequent writes and very frequent reads. Using it on a high-write bin would cause constant APCu cache misses, negating any performance benefit.</p><p>The write path is direct: data is sent to APCu and the database simultaneously, and the last-write timestamp is updated. If APCu is unavailable, ChainedFastBackendFactory returns only the consistent database backend with no chaining at all; zero configuration required. This is covered in depth, along with BackendChain, custom bin definitions, and the full render cache pipeline, in <a href="https://leanpub.com/understanding-drupal-complete-guide-caching-layers/"><em>Understanding Drupal: The Complete Guide to Caching Layers</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a8dd6a19db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>