<?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 Shawn Nystrand on Medium]]></title>
        <description><![CDATA[Stories by Shawn Nystrand on Medium]]></description>
        <link>https://medium.com/@the-webhamster?source=rss-8fd6f38c47bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yOOiWsOQprAUSAFZRqbKSw.png</url>
            <title>Stories by Shawn Nystrand on Medium</title>
            <link>https://medium.com/@the-webhamster?source=rss-8fd6f38c47bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:59:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@the-webhamster/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[“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll]]></title>
            <link>https://the-webhamster.medium.com/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d9e899c4333</guid>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Wed, 25 Nov 2026 13:01:04 GMT</pubDate>
            <atom:updated>2026-11-25T13:01:04.157Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a tiny scheduled job that asks “what’s playing right now?” grew into a year-by-year dashboard of top tracks, albums and artists, and how the numbers are actually calculated.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xbMiK9gfO2pOu1AWRhwIMQ.jpeg" /></figure><blockquote>This is the seventh in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. Links to other articles can be found at the end.</blockquote><p>Every December, streaming services hand you a “year in review.” It’s lovely, and it’s also theirs: a fixed set of charts, delivered once a year, with no way to ask a follow-up question. What if I wanted my top artists for <em>this year to date</em>? Or to compare this year to last year, any time, not just in December?</p><p>I built my own. It’s a small module of my personal dashboard that I call <strong>Spotify Insights</strong>: a dedicated section with its own theme, showing the music I’ve actually listened to, ranked by year. This article covers what it does and how it works under the hood (including a few places where the numbers are more approximate than they look).</p><p>The origin story is short. It began as an experiment in automatically building playlists from radio stations. Along the way I discovered the music service has an endpoint that reports what you’re playing <em>right now</em>. So I started saving it. I kept the data because I’m a data hoarder, and one day I realized I had enough of it to do statistics.</p><h3>What it does</h3><p>The module is a single page with its own look: a dark green-accented theme and its own header, separate from the rest of the site. It was designed to mimic the Spotify UI. It has two zones.</p><p>1. <strong>A year-by-year stats area</strong>. A row of year buttons runs across the top (one per year with data, plus “All-Time”). Pick a year and you get four panels:</p><ul><li><strong>Stats: </strong>Unique artists, unique tracks, unique albums, plus a mini bar chart of the top five artists</li><li><strong>Top Tracks:</strong> The 40 most-played tracks, ranked, with album art, artist, album, release year and a play-count badge</li><li><strong>Top Albums:</strong> The 40 most-played albums</li><li><strong>Top Artists:</strong> The 40 most-played artists, with artist photos and a link to each artist’s page</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2yFs4vtFjh8lE6_AXhhcKQ.png" /></figure><p>2. <strong>A live area at the bottom</strong>. <em>Recently Played Tracks</em> shows the last 100 tracks, newest first, each with how long ago it played and its all-time play count. Next to it, a list of my public playlists, each with its cover art, description and a play button that opens it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ozeZVpibZ_BngFMc38rBmQ.png" /></figure><p>Everything refreshes every minute, and the layout adapts. On a phone, the year panels and the playlist list are hidden entirely and you get just the live feed, since a 40-row ranking isn’t a good phone experience. Where lists are shown on small screens, they’re trimmed to ten or twenty rows.</p><p>For visitors who aren’t logged in, a banner at the top explains the project in a few lines and invites them to look around. The module is deliberately a showpiece, not a private tool.</p><h3>How the data gets there</h3><p>Everything starts with one scheduled job that runs <strong>every two minutes</strong>:</p><pre>public function now_playing(): void {<br>    $last_hash = $this-&gt;_settings-&gt;get_setting(SPOTIFY_NOW_PLAYING_SETTING_NAME);<br>    if (!$last_hash) { return; }<br><br>    $ret = $this-&gt;_spotify_api-&gt;now_playing_for_user();<br>    if (!$ret || $ret[&#39;md5_hash&#39;] === $last_hash) { return; }     // nothing new<br><br>    // (optionally post it to a social account, behind a feature flag)<br>    $this-&gt;_save_now_playing_to_db($ret);<br>    $this-&gt;_settings-&gt;save_setting(SPOTIFY_NOW_PLAYING_SETTING_NAME, $ret[&#39;md5_hash&#39;]);<br>}</pre><p>Walking through it:</p><ol><li><strong>Ask the music service what’s playing</strong>. The API call returns the current item with its artist, album, release date, cover art, link and ids. It returns nothing when nothing is playing, and when the “item” is an ad or a podcast episode (no artist), the code treats that as “nothing to record.”</li><li><strong>Fingerprint it.</strong> The job builds an MD5 hash from title, artist and album and compares it to the last one it stored. If it matches, the same song is still playing and nothing happens. This is what stops a four-minute song from being counted two or three times by a two-minute poll.</li><li><strong>Save it.</strong> A new hash means a new song, so it’s recorded.</li><li><strong>Remember the fingerprint</strong>, so the next poll can compare.</li></ol><h3>One row per track, per year</h3><p>This is the key design decision, and it shapes everything the module can and can’t do. The listening table does not store a row <em>per play</em>. It stores a row <strong>per track per year</strong>, with a counter:</p><pre>$track = SpotifyPlaylist::get_track_by_artist_song_stats_year($ret[&#39;artist&#39;], $ret[&#39;track&#39;], date(&#39;Y&#39;))-&gt;first();<br>if ($track) {<br>    $track-&gt;date_played = $this-&gt;convert_timestamp(time());<br>    $track-&gt;play_count++;<br>} else {<br>    $track = new SpotifyPlaylist;<br>    // artist, song, album, art, release year, track url + id...<br>    $track-&gt;play_count = 1;<br>    $track-&gt;stats_year = date(&#39;Y&#39;);<br>}<br>$track-&gt;save();</pre><p>The first time a track appears in a calendar year, a row is created with a play count of 1 and a stats_year of the current year. Every later play that year increments the counter and refreshes date_played to now. So date_played really means <em>last played</em>.</p><p>The consequence is a table that stays small. Roughly 14,000 rows describe about 26,000 plays across nearly two years. The cost is that I know <em>how often</em> I played each track in a year, but not <em>when each play happened</em>. For now, I’m good with that but I may re-visit that design decision in the future.</p><h3>Artist photos, fetched once</h3><p>The app also wants an artist photo for the “Top Artists” panel. When a play is saved, the job asks a lookup service for the artist, which checks a local artist lookup table first and only calls the music API if the artist isn&#39;t there:</p><pre>public function load_artist_data(string $artist_id): ?SpotifyArtistLookup {<br>    return SpotifyArtistLookup::get_by_artist_id($artist_id)-&gt;first()<br>        ?? $this-&gt;_load_artist_from_spotify_api($artist_id);<br>}</pre><p>One API call per <em>new</em> artist, ever. A couple of thousand artists are cached now. After a new artist is seen once, the photo is a local database read forever.</p><h3>How the numbers are calculated</h3><p>The statistics are plain SQL aggregates over that one table, which is why the module is cheap to run. Four queries do almost all the work.</p><p><strong>Top artists</strong> sums the play counters by artist:</p><pre>self::_stats_query($year)<br>    -&gt;selectRaw(&#39;artist, MAX(date_played) as date_played, SUM(play_count) AS aggregate_count&#39;)<br>    -&gt;groupBy(&#39;artist&#39;)<br>    -&gt;orderByDesc(&#39;aggregate_count&#39;)<br>    -&gt;offset($offset)-&gt;limit($limit)-&gt;get();</pre><p><strong>Top albums</strong> and <strong>top songs</strong> are the same shape, grouped by album (with artist, art and year) or by song. The base query is shared, and a year filter is added only when a year is selected:</p><pre>private static function _stats_query($year) {<br>    $query = DB::table(&#39;spotify_playlist&#39;);<br>    if ($year) {<br>        $query-&gt;where(&#39;stats_year&#39;, &#39;=&#39;, $year);<br>    }<br>    return $query;<br>}</pre><p>“All-Time” is simply <em>no year filter</em>. A tiny normalizer maps the string All-Time to null before it reaches the query. The year buttons themselves come from SELECT DISTINCT stats_year ... ORDER BY stats_year DESC, with &quot;All-Time&quot; appended at the end, so a new year&#39;s button appears automatically on the first play of January.</p><p><strong>The headline numbers</strong> are counts: distinct artists, distinct albums and the number of track rows for the year.</p><h3>Cache the aggregates</h3><p>Aggregating thousands of rows on every page view, for every panel, for every year, would be wasteful, and the answers barely change minute to minute. So every statistics query goes through one helper that caches its result for five minutes, keyed by the query’s name and its arguments:</p><pre>private static function _cached_stats(string $key, array $args, \Closure $query) {<br>    return Cache::remember(&#39;spotify_playlist_stats_&#39; . $key . &#39;_&#39; . md5(json_encode($args)), 300, $query);<br>}</pre><p>Five minutes is the sweet spot for this data: new plays land every few minutes anyway, so a few minutes of staleness is invisible, but it turns dozens of aggregate queries into a handful.</p><h3>The “recent” list with all-time counts</h3><p>The recently played list has a nice optimization. For each page of tracks, it needs each track’s total play count across all years. Doing that per row would be an N+1 query problem. Instead the model collects every track id on the page and fetches all their totals in <strong>one grouped query</strong>, then attaches them:</p><pre>$aggregate_counts = DB::table(&#39;spotify_playlist&#39;)<br>    -&gt;whereIn(&#39;spotify_track_id&#39;, $track_ids)<br>    -&gt;groupBy(&#39;spotify_track_id&#39;)<br>    -&gt;selectRaw(&#39;spotify_track_id, SUM(play_count) AS aggregate_count&#39;)<br>    -&gt;pluck(&#39;aggregate_count&#39;, &#39;spotify_track_id&#39;)-&gt;all();</pre><p>(A dedicated index on the track-id column was added to make this lookup fast.)</p><h3>The front end</h3><p>The page is built with the same card-and-poll components as the rest of the dashboard, each a small single-file Livewire component that asks the controller for its data and refreshes every sixty seconds. A shared list template renders a row for three different display types (track, album, artist), with a numbered rank badge. The top three get a bolder badge, and the rest a quieter one.</p><p>The year switcher is the one place where I used Alpine.js. All the year panels are rendered at once, and a tiny piece of client-side state decides which is visible:</p><pre>&lt;div x-data=&quot;{ activeYear: &#39;{{ $this-&gt;years[0] }}&#39; }&quot;&gt;<br>    @foreach ($this-&gt;years as $year)<br>        &lt;button @click=&quot;activeYear = &#39;{{ $year }}&#39;&quot; ...&gt;{{ $year }}&lt;/button&gt;<br>    @endforeach<br><br>    @foreach ($this-&gt;years as $year)<br>        &lt;div x-show=&quot;activeYear === &#39;{{ $year }}&#39;&quot;&gt; ... panels for that year ... &lt;/div&gt;<br>    @endforeach<br>&lt;/div&gt;</pre><p>Switching years is instant, with no server round trip, because everything is already on the page. The trade-off, which I’ll list below, is that every year’s panels exist in the page whether you look at them or not.</p><p>The “Top Artists” mini chart in the stats card is pure HTML and CSS, with no charting library: a row per artist, each with a bar whose width is the artist’s plays divided by the top artist’s plays (with a minimum so even a small bar is visible). It’s a fine reminder that a bar chart is just a div with a percentage width.</p><h3>Where the numbers are approximate</h3><p>A stats page that looks authoritative should be honest about what it measures. Here‘s how I work out what I’m tracking.</p><p><strong>A “play” is a change of song, detected by polling</strong>. The job looks every two minutes. That means:</p><ul><li>A song skipped within about two minutes may never be seen.</li><li>Playing the same song twice in a row counts once, because the fingerprint doesn’t change.</li><li>A song that’s still playing across polls counts once, which is what I want.</li></ul><p>So play counts are a good <em>relative</em> measure (this artist is clearly ahead of that one) and a slightly conservative <em>absolute</em> one.</p><p><strong>Tracks are matched by artist and title, not by track id</strong>. The row-matching query looks for the same artist and song name within a year. A live version, a remaster and the original, if they share a title, would be merged into a single row.</p><p><strong>“Unique tracks” is really “track rows.”</strong> The headline count is a row count. Within one year that equals unique tracks, because there’s one row per track per year. But under “All-Time,” a song played in two different years has two rows and is counted twice.</p><p><strong>Artists are grouped by name text.</strong> An artist credited under slightly different spellings would be split, and only the first-credited artist on a track is stored, so collaborations credit one name.</p><p>None of these invalidate the module. They’re the kind of thing worth knowing when someone asks, “is that exactly right?” The answer is “close, and consistently so.”</p><h3>Rough edges in the implementation</h3><p>Beyond the semantics, a few engineering notes.</p><ul><li><strong>Every year’s panels mount and poll.</strong> With three year buttons (two years plus All-Time), twelve statistics components are on the page and each polls every minute, even the ones hidden behind a tab. This something I’ll have to address in the future.</li><li><strong>Large text columns.</strong> Song, album, art and URL are stored as long text. That makes grouping and indexing on them heavier than it needs to be, and the grouped queries lean on temporary tables. Bounded varchar columns, and a composite index on year plus artist, would help as the table grows.</li></ul><h3>Lessons</h3><ol><li><strong>Start recording earlier than you think you need to.</strong> I saved aggregates, not events, and I can never recover the timing I didn’t keep. If in doubt, log the event and aggregate later.</li><li><strong>A poll plus a fingerprint is a cheap event detector.</strong> A hash of title, artist and album turns “what’s playing now” into “something changed.”</li><li><strong>Cache the expensive aggregates, not the cheap rows.</strong> Five minutes of caching on the grouped queries is the whole performance story.</li><li><strong>Normalize “all” as “no filter.”</strong> One nullable year parameter serves every year and the all-time view with the same query.</li><li><strong>Batch the lookups.</strong> One grouped query for a page of rows beats one per row.</li><li><strong>Know what your numbers mean.</strong> Write down the ways a metric is approximate, before someone asks.</li><li><strong>A bar chart is a div with a width.</strong> You don’t always need a chart library.</li><li><strong>Let a showpiece look like one.</strong> A dedicated theme and a friendly intro banner turned a pile of tables into something people enjoy looking at.</li><li><strong>Your own data compounds.</strong> Every new table in the project (weather, home sensors, radio history) makes the old ones more interesting.</li></ol><p>It began as a side effect of an experiment with playlists. Nearly two years in, it’s the section of the site I’d miss the most, and the best argument I know for saving the data even when you’re not sure what you’ll do with it.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li><a href="https://medium.com/@the-webhamster/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li><a href="https://medium.coderun.ca/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li><a href="https://medium.coderun.ca/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li><li>“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d9e899c4333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History]]></title>
            <link>https://the-webhamster.medium.com/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/be587a3c68fb</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 13:01:04 GMT</pubDate>
            <atom:updated>2026-11-25T14:40:50.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I scrape what dozens of radio stations are playing, match it to Spotify, and let play counts decide what earns a spot in a playlist that updates itself.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJ_JteH382nS8NBJnfzD0g.jpeg" /></figure><blockquote>This is the sixth in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. Links to other articles can be found at the end.</blockquote><p>I love discovering music, and I’m lazy about curation. I don’t want to hunt for good songs, and I certainly don’t want to maintain playlists. But there are people who spend their entire working lives choosing great music: radio programmers and DJs. Their choices are public, the “now playing” information is published somewhere, and most stations expose it as a little JSON endpoint to feed their own websites and apps.</p><p>So I built a system that listens to the DJs for me. It polls what dozens of stations are playing, matches each song to Spotify, remembers how often each one turns up, and when a song proves itself by showing up often enough, it quietly adds the song to a Spotify playlist for that station. The playlists update themselves, forever, with no input from me.</p><p>It’s one of my favourite parts of my personal data-aggregation project, because it’s a small system with a satisfying amount of cleverness and a few good traps. Here’s how it works.</p><h3>The big picture</h3><pre> station &quot;now playing&quot; endpoints       Spotify API<br>   (terrestrial, satellite,            (search, track<br>    internet radio)                     and artist data)<br>          │                                   ▲<br>          ▼                                   │<br>   ┌─────────────┐   normalize    ┌───────────┴──────────┐<br>   │  scrapers   │ ─────────────► │  match song → track  │<br>   └─────────────┘                └───────────┬──────────┘<br>                                              ▼<br>                                   ┌─────────────────────┐<br>                                   │ play-history table  │  count plays<br>                                   │ (one row per song,  │  per station<br>                                   │  per station)       │<br>                                   └───────────┬─────────┘<br>                                               │  ≥ 10 plays, not yet added<br>                                               ▼<br>                                   ┌─────────────────────┐<br>                                   │ add to Spotify      │ ─► playlists<br>                                   │ playlist, mark done │<br>                                   └─────────────────────┘</pre><p>Four ideas hold it together:</p><ol><li><strong>Poll</strong> every station every few minutes and record what’s playing.</li><li><strong>Normalize</strong> the messy text so the same song looks the same everywhere.</li><li><strong>Match</strong> each song to a Spotify track and cache the result.</li><li><strong>Promote</strong> a song to a playlist once its play count crosses a threshold.</li></ol><h3>Step 1: listening to the radio, politely</h3><p>Every station is a row in a table of <em>sources</em>: a name, a short code, a type (terrestrial radio, satellite radio, or an internet radio network), an active flag, the URL of its now-playing feed, and the id of the Spotify playlist it feeds. Today that’s about 50 stations: 15 terrestrial radio stations, 26 satellite radio channels and 8 channels from an internet radio network.</p><p>Each type gets its own scraper, and they’re scheduled a minute apart so they don’t all fire at once:</p><pre>// every 3 minutes, offset by a minute per scraper<br>&#39;radio_scraper&#39;  =&gt; &#39;0,3,6,9,...,57 * * * *&#39;<br>&#39;satrad_scraper&#39; =&gt; &#39;1,4,7,10,...,58 * * * *&#39;<br>&#39;web_station_scraper&#39;   =&gt; &#39;2,5,8,11,...,59 * * * *&#39;</pre><p>Three minutes is roughly the length of one song, so that cadence catches most tracks without hammering anyone’s servers.</p><h3>Every station speaks a different dialect</h3><p>You might hope the world’s radio stations agree on a “now playing” format. They do not. Here are the shapes I’ve dealt with, all for the same two facts (artist and title):</p><ul><li>a JSON array whose first element has artist, title and album</li><li>a content list with the track nested under content_elements[0]</li><li>ID3-style field names (TPE1 for artist, TIT2 for title, TALB for album)</li><li>a results array with artist, song, album</li><li>one response that covers a dozen stations at once, which you have to search by call letters</li><li>plain artist_name / song_name fields</li><li>JSONP, where the JSON is wrapped in a function call, which means a regex to extract it before you can parse it</li><li>a single string like &quot;Artist - Title&quot; that you have to split yourself</li></ul><p>My radio scraper handles this with a match expression on the station code. Each arm is a tiny adapter that extracts the same three fields:</p><pre>$response = match ($station_code) {<br>    &#39;wkrp&#39;, &#39;wreq&#39; =&gt; $this-&gt;_try_build_response($code, $name, $id,<br>        $data[0]-&gt;artist ?? &#39;&#39;, $data[0]-&gt;title ?? &#39;&#39;, $data[0]-&gt;album ?? null),<br>    &#39;kacl&#39; =&gt; $this-&gt;_try_build_response($code, $name, $id,<br>        $data[0]-&gt;TPE1 ?? &#39;&#39;, $data[0]-&gt;TIT2 ?? &#39;&#39;, $data[0]-&gt;TALB ?? null),<br>    &#39;wnyx&#39; =&gt; $this-&gt;_try_build_response($code, $name, $id,<br>        $data-&gt;results[0]-&gt;artist ?? &#39;&#39;, $data-&gt;results[0]-&gt;song ?? &#39;&#39;, $data-&gt;results[0]-&gt;album ?? null),<br>    default =&gt; /* artist_name / song_name */,<br>};</pre><p>Everything downstream sees one clean shape. Adding a station with a weird format means adding one arm. This is the same principle I use for all scraping: <strong>normalize at the edge.</strong></p><h3>The first trick: don’t count a song twice</h3><p>When you poll every three minutes and a song lasts four, you’ll see most songs twice. If you counted each sighting as a play, every number in the system would be inflated. Two layers of protection solve it:</p><ol><li><strong>Within a run</strong>, a hash of station + song + artist is kept, so the same track is never processed twice in one pass.</li><li><strong>Across runs</strong>, a track that was seen within the last three hours is ignored:</li></ol><pre>if (strtotime($ret-&gt;date_played) &gt;= time() - 10800) {   // 3 hours<br>    return;<br>}</pre><p>That second rule has an interesting side effect. A “play” in my system means <em>a distinct sighting at least three hours after the last one</em>. A song a station plays every day counts once a day. A song a station plays on heavy rotation four times a day counts at most a few times. I’m measuring how consistently a song appears in a station’s programming, not a precise play count, and for curation, that’s actually what I want.</p><h3>Step 2: cleaning up the text</h3><p>Here’s where the fun starts. The same song arrives in many disguises:</p><ul><li>Song Title (2011 Remaster)</li><li>Song Title - Remastered 2009</li><li>Song Title - Single Version</li><li>Song Title - From the &quot;Some Movie&quot; Soundtrack</li><li>Artist (Live @ [network name]) or Artist EXCLUSIVE</li><li>jam bands, whose “artist” field sometimes arrives as Band 7.4.25, with the show date glued on</li></ul><p>If I search Spotify for those literally, I get nothing, or the wrong thing. So there’s a layer of cleaning functions:</p><pre>$patterns = [<br>    &quot;/\(\d+ Remaster\)/&quot;, &quot;/\(\d+ Digital Remaster\)/&quot;, &quot;/Remastered \d+/&quot;,<br>    &quot;/Single Version/&quot;, &quot;/Edit/&quot;,<br>    &#39;#- From (&quot;).*?(&quot;) Soundtrack#&#39;, &#39;#- From .*?#&#39;, &quot;/ - /&quot;,<br>    // ...<br>];<br>$track = preg_replace($patterns, &quot;&quot;, $track);</pre><p>And a second function normalizes for <em>comparison</em>: transliterate accents to plain ASCII, lowercase, strip punctuation and a few words like and the, collapse whitespace:</p><pre>public function strip_text_from_input($input) {<br>    // &quot;Beyoncé&quot; -&gt; &quot;beyonce&quot;, not &quot;beyonc &quot;<br>    $output = strtolower((new UnicodeString((string) $input))-&gt;ascii()-&gt;toString());<br>    $output = str_replace([&quot;v/&quot;, &quot;w/&quot;, &quot;and the&quot;, &quot;&amp; the&quot;], &quot; &quot;, $output);<br>    $output = preg_replace(&#39;/[^A-Za-z0-9 ]/&#39;, &quot; &quot;, $output);<br>    return trim(preg_replace(&#39;/\s+/&#39;, &#39; &#39;, $output));<br>}</pre><p>These lists grew organically: every pattern in there is a scar from a specific wrong match I noticed. If you build something like this, expect to keep adding to yours.</p><p>The transliteration step is a later fix, and a good example of a bug hiding in plain sight. The original version stripped every non-ASCII character, so “Beyoncé” became beyonc and could never equal the beyonce in somebody else&#39;s data. Symfony&#39;s string component (already installed with Laravel) turns accents into their plain equivalents before the regex runs. It has a side effect: Cyrillic and CJK names used to collapse to an empty string, and now become Latin approximations (&quot;Москва&quot; becomes moskva). Names made only of symbols still end up empty, so anywhere I compare normalized names I still refuse to let a blank string count as a match.</p><h3>Step 3: the matcher (my favourite function)</h3><p>Now I have a cleaned artist and title. How do I decide that a Spotify search result is the same song?</p><p>Exact string comparison fails constantly: “Breakin’” vs “Breaking”, “The Cure” vs “Cure”, or the station and Spotify disagreeing on a feature credit. Real fuzzy-matching libraries exist, but I wanted something small and predictable, so I wrote a word-overlap scorer.</p><p>The first version compared each input word against the candidate <em>string</em> with str_contains(). That was cheap and forgave &quot;breakin&quot; vs &quot;breaking&quot;, but it was too forgiving. &quot;he&quot; matched inside &quot;the&quot;, &quot;love&quot; matched inside &quot;glove&quot;, and an empty token (from a doubled space) matched everything, so two blank strings counted as a perfect match. Here&#39;s the current version, which compares whole words:</p><pre>public function evaluate_match($input, $match) {<br>    $sources = $this-&gt;_match_tokens((string) $input);<br>    $matches = $this-&gt;_match_tokens((string) $match);<br><br>    if (!$sources || !$matches) {<br>        return false;                              // nothing to compare, nothing matches<br>    }<br><br>    $reliability = 0;<br>    foreach ($sources as $source) {<br>        foreach ($matches as $candidate) {<br>            if ($this-&gt;_words_match($source, $candidate)) {<br>                $reliability++;<br>                break;<br>            }<br>        }<br>    }<br><br>    $score  = $reliability / count($matches) * 100;<br>    $target = count($sources) / count($matches) * 100;<br>    if ($target &gt; 100) {<br>        $target = 65;                              // sane cap for lopsided lengths<br>    }<br>    return $score &gt;= $target;<br>}<br><br>private function _words_match(string $a, string $b): bool {<br>    if ($a === $b) {<br>        return true;<br>    }<br>    $shortest = min(strlen($a), strlen($b));<br>    if ($shortest &lt; 3) {<br>        return false;                              // short words must match exactly<br>    }<br>    if (str_starts_with($a, $b) || str_starts_with($b, $a)) {<br>        return true;                               // &quot;breakin&quot; ~ &quot;breaking&quot;<br>    }<br>    return $shortest &gt;= 5 &amp;&amp; levenshtein($a, $b) &lt;= 1;   // &quot;colour&quot; ~ &quot;color&quot;<br>}</pre><p>_match_tokens() transliterates to ASCII, lowercases, and splits on anything that isn&#39;t a letter or digit, dropping empty pieces.</p><p>In words: for each word in the input, look for a counterpart among the candidate’s <em>words</em>. Two words count as the same if they’re identical, if one is a prefix of the other (at least three letters), or, for longer words, if they differ by a single edit. Count the hits, and express that as a percentage of the candidate’s word count. The bar to clear is the ratio of the two strings’ lengths, so the more the lengths differ, the more the matcher has to see, with a hard cap of 65% when the input is longer than the candidate. A short string must be mostly contained in the candidate, and similar-length strings must overlap closely.</p><p>That scoring rule didn’t change; only what counts as a “hit” did. It’s still not mathematically elegant, and I wouldn’t claim it’s the best approach. But it has useful properties: it forgives small spelling variants, it behaves sensibly when one side has extra words, and I can read it in a minute and debug it by hand. I apply it to <strong>both</strong> the artist and the title before accepting a match, so a famous title by a different artist doesn’t slip through.</p><p>I did consider a fuzzy-search library. The ones I looked at are built to rank many candidates, not to answer “is this the same song?”, and none of them know about “feat.” credits or radio-network suffixes, which my cleaning functions already handle. So I kept my own scorer and fixed its weak spots instead.</p><h3>Searching Spotify</h3><p>A Spotify search request is built from the cleaned strings:</p><pre>/v1/search?type=track,artist&amp;limit=50&amp;q=track:&lt;title&gt;+artist:&lt;artist&gt;</pre><p>The code then walks the results and returns the first one where both artist and title pass the matcher. It also skips results with no artist or no name, since local files and odd uploads show up in search results.</p><h3>Cache the answer, always</h3><p>Looking a song up on Spotify costs an API call, and radio stations repeat themselves a lot. So the very first thing the system does is check <strong>its own history</strong>: has any station already played this song, and did I already resolve it to a Spotify track?</p><pre>$ret = $this-&gt;find_track_in_database($track, $artist);   // full-text search of my history<br>if ($ret) {<br>    return $this-&gt;_build_result_from_db($ret);           // no API call<br>}<br>$spotify_track = $this-&gt;_search_track_artist($track, $artist);</pre><p>A fulltext index over artist and title columns makes that lookup quick. After a few weeks, the vast majority of lookups never touch Spotify at all. The cache is the table I was already building. It’s a nice example of <strong>history doing double duty</strong>.</p><p>And there’s a practical reason for this. Earlier versions just used the Spotify API and as this project grew I <strong>lost sight of the usage</strong> and actually got two Spotify API accounts <strong>banned</strong> because of the increase in traffic as I added stations and features! The lesson is, be nice when you’re leveraging other people’s parts! If you have a way to avoid making a call and still get the same data then do that.</p><p>The result of a match is stored right on the track row: the Spotify track id, a “clean” artist and title as Spotify spells them, the album, the album art URL and the release year. Currently around <strong>84% of the roughly 250,000 distinct station tracks I’ve collected have been matched to a Spotify track</strong>. The rest are things Spotify doesn’t carry, or songs where my cleaning wasn’t enough.</p><h3>Step 4: earning a spot in a playlist</h3><p>Now the part that makes it curation instead of logging. Each song, per station, gets a <strong>play count</strong>. Once it hits a threshold, the song gets added to that station’s Spotify playlist:</p><pre>const TRACK_ADD_TO_SPOTIFY_THRESHOLD = 10;<br><br>if (!$update<br>    || !$update-&gt;spotify_track_id                       // must be matched to a real track<br>    || $new_play_count &lt; TRACK_ADD_TO_SPOTIFY_THRESHOLD // must have earned it<br>    || $update-&gt;status != TRACK_STATUS_NEW              // must not already be handled<br>    || !$spotify_playlist) {                            // station must have a playlist<br>    return;<br>}</pre><p>Why ten? Because a song a station plays once might be a novelty, a request, or a special show. A song that keeps coming back over weeks is part of that station’s identity. The threshold is a cheap, effective stand-in for “this is genuinely representative of what this station plays”, and it filters out ads, jingles and one-offs that happen to match something on Spotify.</p><p>Each track row has a <strong>status</strong>: new, found (meaning it&#39;s been added to a playlist), or hide (excluded from display). That state machine is what makes the whole thing idempotent. A track is added exactly once, then marked, so the next run skips it.</p><h3>Dedup before adding</h3><p>Before adding, the system checks whether the song has <em>already</em> been added from this station, by Spotify ID first and then by cleaned title and artist as a fallback:</p><pre>public function search_for_track_added_to_playlist(object $track, array $playlist_source_ids): bool {<br>    if (PlaylistTracks::search_playlist_tracks_for_added_track_by_id($track-&gt;spotify_track_id, $ids)-&gt;isNotEmpty()) {<br>        return true;<br>    }<br>    return PlaylistTracks::search_playlist_tracks_for_added_track($track-&gt;clean_song, $track-&gt;clean_artist, $ids)-&gt;isNotEmpty();<br>}</pre><p>The second check matters because the same recording can have different Spotify ids across albums, reissues and compilations. If it’s already there under another id, it’s marked as handled without a duplicate.</p><p>An important design choice: <strong>I track what’s in the playlists in my own database, not by asking Spotify</strong>. Reading a whole playlist back from the API on every run would be slow, rate-limited and unnecessary. Ask me how I know. This is actually one of the main reasons I got those Spotify API accounts banned. At one point I thought I was being clever and I was scanning entire 5000+ track playlists to see if a track was already in there every time I went to try and add a track. Oops!</p><p>The cost is that if I manually delete a track from a playlist in the Spotify app, my database doesn’t know. For a hands-off system, that’s an acceptable trade.</p><h3>Playlists of playlists</h3><p>Individual station playlists are fun, but the real payoff is combining stations. Some stations belong to families, such as the “modern rock” group and the “active rock” group. When a track earns its place in one station’s playlist, the scraper checks whether the station belongs to a group, and if so also adds the track to the group’s shared playlist, after checking that none of the group’s other stations already added it:</p><pre>if (in_array($station_code, self::MODERN_ROCK_CODES)) {<br>    $this-&gt;_add_track_to_modern_rock_playlist($update);<br>}<br>if (in_array($station_code, self::ACTIVE_ROCK_CODES)) {<br>    $this-&gt;_add_track_to_active_rock_playlist($update);<br>}</pre><p>So a track that five different modern-rock stations each play over time lands in the combined playlist exactly once, and the combined playlist reflects consensus across stations, not one station’s habits. As of this writing, one of those merged playlists had over <strong>3400 tracks</strong> in it since I created the idea of the genre group playlist in December 2024. And <em>I didn’t manually add a single one</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZ3h-GdnsPtuDcc1cS3mFw.png" /></figure><h3>Bulk-building an artist playlist</h3><p>The history table has a second use. Because every song I’ve ever matched is indexed by artist, I can build a playlist for any artist on demand. An API endpoint takes an artist name and a playlist id, full-text searches the history for that artist, de-duplicates by Spotify id, applies the fuzzy matcher again to weed out false hits, and adds everything:</p><pre>$tracks = PlaylistTracks::get_tracks_by_artist_and_spotify_id($this-&gt;strip_text_from_input($artist));<br>foreach ($tracks as $track) {<br>    if (!in_array($track-&gt;spotify_track_id, $added) &amp;&amp; $this-&gt;evaluate_match($artist, $track-&gt;clean_artist)) {<br>        $this-&gt;_spotify_api-&gt;add_track_to_playlist($playlist_id, $track-&gt;spotify_track_id);<br>        $added[] = $track-&gt;spotify_track_id;<br>    }<br>}</pre><p>“Every track by this artist that has been played on any station I track” in one call.</p><h3>Talking to Spotify without losing your mind</h3><p>The integration with Spotify itself is small, but it has some lessons worth sharing.</p><p><strong>OAuth, once.</strong> I authorize the app through the standard authorization-code flow, with scopes for reading the currently playing track and modifying playlists. A random state value is stored in cache and compared with hash_equals() on the callback, and a comment in the code reminds me why both sides must be non-empty, so two missing values can&#39;t &quot;match&quot; as null equals null.</p><p><strong>Refresh tokens do the real work</strong>. The refresh token lives in the settings table. Each run, the service looks for a cached access token, and if there isn’t one, trades the refresh token for a new one and caches it for its lifetime minus a minute of safety margin. If Spotify rotates the refresh token in the response, the new one is saved.</p><p><strong>Expect the token to die</strong>. Refresh tokens can be revoked or expire. When that happens, Spotify returns an invalid_grant error. My code notices, clears the cached tokens, and sets a flag so it only alerts once. It sends me a text that says to visit the re-authorization page. Visiting it runs the flow again, clears the flag and everything resumes. I&#39;d rather get one clear text than discover a month later that playlists stopped growing.</p><p><strong>Be tolerant about missing tokens</strong>. Every API method starts with if (!$this-&gt;_auth_token) return null;. If Spotify auth is down, the scrapers still record play history. They just can&#39;t match or add tracks until I fix it, and they fill in the missing Spotify data on later sightings (tracks with no Spotify id get another look each time they&#39;re seen).</p><p><strong>A caution on Spotify’s API</strong>. Spotify has changed parts of its Web API over the years, restricting some endpoints and changing others. Check the current documentation before you copy any request shape from this article.</p><h3>The other half: my own listening</h3><p>The same machinery tracks what <em>I’m</em> listening to. A job runs every two minutes, asks Spotify’s “currently playing” endpoint what I’m hearing, and records it:</p><ul><li>It makes a hash of the title, artist and album, and skips the update if it’s unchanged since the last poll, so a long song isn’t counted repeatedly.</li><li>It ignores ads and podcast episodes, which come back with no track item.</li><li>A track already played this year has its play count incremented. Otherwise a new row is created, with stats keyed by year so I can ask “what did I listen to most in 2025?”</li><li>It looks up the artist once, caches their image and id in a lookup table, and never asks again.</li><li>Optionally, behind a feature flag, it posts “what I’m listening to right now” to a social account.</li></ul><p>That personal history feeds back into the system in a fun way. A separate scraper checks MusicBrainz for albums releasing in the next six months, but <strong>keeps only releases from artists in my listening history</strong>. So the “upcoming albums” panel on my dashboard only shows releases I’d actually care about. The query is rate-limited to about one request a second, as the service requests, and it ignores artists whose names normalize to an empty string (symbol-only names, for example), so two of them can’t falsely “match” each other.</p><p>In the end, this is how my listening history is integrated into my dashboard web application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*UpEPkJ9JMz8YZiGtHFnvmg.png" /></figure><p>A future article will further explore what I do with this data. It’s actually pretty cool. I built my own “Real-Time Spotify Wrapped”!</p><h3>What it looks like at scale</h3><p>A snapshot from my database:</p><ul><li>About <strong>250,000 distinct station tracks recorded</strong>, going back to an earlier version of the system that launched in 2020 (this started as a pandemic project)</li><li>Roughly <strong>84%</strong> matched to Spotify</li><li>About <strong>123,000</strong> promoted to a playlist</li><li>About <strong>32,000</strong> distinct station tracks seen at least once in the last week alone</li><li>A listening history of about <strong>3,400 artists</strong> and 2,200 cached artist lookups</li></ul><p>The number I find most interesting is the ratio between stations. Some stations promote the majority of what they play, because they have a tight, repetitive rotation. Others promote a small slice, because they have enormous, adventurous catalogues where almost nothing repeats ten times. The threshold quietly adapts to each station’s character, with no special-casing at all.</p><h3>What I’d do differently</h3><ul><li><strong>Batch the adds.</strong> Spotify accepts multiple tracks per request, and mine sends one at a time. It’s simple and it works at my volumes, but it’s wasteful.</li><li><strong>A smarter matcher for the long tail.</strong> The word-overlap scorer is great for 90% of cases, and the remaining few percent (live versions, medleys, “feat.” credits) would benefit from something more careful.</li><li><strong>Per-station thresholds.</strong> Ten plays is a good default, but a low-rotation station might deserve a lower bar.</li></ul><h3>Lessons</h3><ol><li><strong>Normalize at the edge</strong>. Eight station formats become one internal shape, and everything after that is simple.</li><li><strong>Make your history your cache</strong>. The table you’re building anyway can save you most of your API calls.</li><li><strong>Define “a play” to fit your goal</strong>. A three-hour cool-off turned a noisy poll into a meaningful consistency signal.</li><li><strong>Let thresholds do the curating</strong>. “Seen ten times” is a cheap, surprisingly good proxy for “representative”.</li><li><strong>Use status fields to make jobs idempotent</strong>. New, found, hidden: three states and no duplicates.</li><li><strong>Keep the matcher small and readable</strong>. A simple scorer I understand beats a sophisticated one I can’t debug.</li><li><strong>Plan for the OAuth token to die</strong>. Detect it, alert once, make the fix a single click.</li><li><strong>Let your own data steer other features</strong>. Listening history decides which upcoming albums I see.</li></ol><p>It started as a way to avoid maintaining playlists. It became a quiet system that listens to dozens of radio stations, keeps score, and leaves me with playlists that are always a little better than they were last week.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li><a href="https://medium.coderun.ca/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li><a href="https://medium.com/@the-webhamster/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li><a href="https://medium.com/@the-webhamster/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li>Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</li><li><a href="https://medium.coderun.ca/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333">“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be587a3c68fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop One Broken Feed From Killing Your Whole Scraper Run]]></title>
            <link>https://the-webhamster.medium.com/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/781708eaa75e</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Thu, 12 Nov 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-11-25T14:41:34.050Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Two small patterns, step isolation and per-source health tracking, that keep a data-aggregation app working when individual sources inevitably fail.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQunA4zYc0dSIwacoThE5Q.jpeg" /></figure><blockquote>This is the fifth in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. Links to other articles can be found at the end. This article discusses how I fixed issues with the scrapers to keep one failing source from bringing down the whole thing.</blockquote><p>If you aggregate data from more than a handful of external sources, something is <em>always</em> broken. A feed changes format. A server times out. An API starts rate-limiting you. A site goes away and never comes back.</p><p>The question isn’t how to prevent failures. It’s how to make sure that:</p><ol><li>One failure doesn’t stop everything that comes after it, and</li><li>You find out about a <em>persistently</em> broken source, without being buried in noise from the occasional blip.</li></ol><p>I solved those two problems with two small patterns. Neither is clever, but together they changed my project from “something is broken” to “this one thing is broken, and I know which.”</p><h3>Problem 1: the domino effect</h3><p>A typical scheduled job looks like this:</p><pre>public function __invoke() {<br>    (new WeatherScraper)-&gt;scrape();<br>    (new ThermostatScraper)-&gt;collect();<br>    (new CityOpenDataScraper)-&gt;scrape();<br>    (new CentralBankScraper)-&gt;scrape();<br>    (new SpaceForecastScraper)-&gt;scrape();<br>    (new ArticlesScraper)-&gt;scrape();<br>    (new TVScraper)-&gt;scrape();<br>}</pre><p>If the thermostat API throws on line two, the other five never run. The failure of one cheap, unimportant scraper has silently taken out everything after it. The more steps you add, the worse this gets, and the <em>order</em> of your list quietly becomes a priority ranking you never meant to create.</p><p>The obvious fix is wrapping every line in its own try/catch. That works, but it’s noisy and easy to forget on step number nine. And swallowing the exception creates a new problem: your job now “succeeds” even though half of it failed, so your monitoring never notices.</p><h3>The pattern: run everything, then fail once, loudly</h3><p>I pulled this into a small trait. A job declares its steps as a named list, and the trait runs them all:</p><pre>trait CronSteps {<br>    protected function run_steps(array $steps): void {<br>        $failures = [];<br>        foreach ($steps as $name =&gt; $step) {<br>            try {<br>                $step();<br>            }<br>            catch (Throwable $e) {<br>                $failures[] = $name . &#39;: &#39; . $e-&gt;getMessage();<br>                $this-&gt;log_event(&#39;error&#39;, $name, $e-&gt;getMessage());<br>            }<br>        }<br>        if ($failures) {<br>            throw new RuntimeException(<br>                count($failures) . &#39; step(s) failed - &#39; . implode(&#39; | &#39;, $failures)<br>            );<br>        }<br>    }<br>}</pre><p>And a job becomes:</p><pre>class CronHourly {<br>    use CronSteps;<br><br>    public function __invoke() {<br>        $this-&gt;run_steps([<br>            &#39;weather&#39;          =&gt; fn() =&gt; (new WeatherScraper)-&gt;scrape(),<br>            &#39;thermostat&#39;       =&gt; fn() =&gt; (new ThermostatScraper)-&gt;collect(),<br>            &#39;cities_open_data&#39; =&gt; fn() =&gt; (new CityOpenDataScraper)-&gt;scrape(),<br>            &#39;central_bank&#39;     =&gt; fn() =&gt; (new CentralBankScraper)-&gt;scrape(),<br>            &#39;space_forecast&#39;   =&gt; fn() =&gt; (new SpaceForecastScraper)-&gt;scrape(),<br>            &#39;articles&#39;         =&gt; fn() =&gt; (new ArticlesScraper)-&gt;scrape(),<br>            &#39;tv&#39;               =&gt; fn() =&gt; (new TVScraper)-&gt;scrape(),<br>        ]);<br>    }<br>}</pre><p>Look at what this buys you:</p><ul><li><strong>Every step runs</strong>, regardless of what happened to the ones before it.</li><li><strong>Each failure is logged individually</strong>, with the step name, so you can see exactly what broke.</li><li><strong>The job still fails</strong> at the end, with a single exception that summarizes every failed step. Anything watching the job (a monitor, an alerting wrapper, your exception tracker) sees a failed run, exactly as it would have before.</li><li><strong>Named steps</strong> double as documentation, and the names show up in the failure message.</li></ul><p>The important design decision is the last one. Isolation without a final throw is how you build a system that looks healthy while rotting. This pattern gives you the resilience of “keep going” <em>and</em> the honesty of “something went wrong”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9MnB33hR9iJ4hRhLvEHrg.png" /><figcaption>On the front-end I can see this report on my cron health</figcaption></figure><h3>Problem 2: the source that’s been dead for a week</h3><p>Step isolation handles failures at the <em>job</em> level. But many of my steps are really loops over dozens of individual sources, like news feeds or radio stations. Inside one “articles” step, a single feed can fail every run for weeks while the other 59 feeds work fine. The step as a whole mostly succeeds, so no job-level alarm ever fires.</p><p>I needed to track health per source, and I needed to avoid two opposite mistakes:</p><ul><li><strong>Too jumpy.</strong> Alerting on a single failed fetch means getting texted every time a server hiccups.</li><li><strong>Too eager to give up.</strong> Automatically disabling a source after a few failures sounds sensible, but it means a temporary network problem quietly and permanently removes a perfectly good feed. I actually shipped this mistake. The scraper was too aggressive about disabling sources that were slow or briefly unavailable, and I only noticed because content from certain places had vanished.</li></ul><h3>The pattern: count consecutive failures against a threshold</h3><p>A small service tracks one row per source, identified by a stable (type, key) pair, for example (&#39;news_source&#39;, &#39;42&#39;):</p><pre>public function record_result(string $source_type, string $source_key, string $source_label,<br>                              bool $success, ?string $error_message = null,<br>                              int $alarm_threshold = 50): void {<br>    $health = SourceHealth::get_by_type_and_key($source_type, $source_key)-&gt;first()<br>        ?? new SourceHealth([&#39;source_type&#39; =&gt; $source_type, &#39;source_key&#39; =&gt; $source_key]);<br>    $health-&gt;source_label = $source_label;<br><br>    if ($success) {<br>        $health-&gt;consecutive_failures = 0;<br>        $health-&gt;last_success_at = Carbon::now();<br>        $health-&gt;is_alarmed = false;      // recovered: re-arm<br>        $health-&gt;save();<br>        return;<br>    }<br><br>    $health-&gt;consecutive_failures++;<br>    $health-&gt;last_failure_at = Carbon::now();<br>    $health-&gt;last_error_message = $error_message ? substr($error_message, 0, 2000) : null;<br><br>    if (!$health-&gt;is_alarmed &amp;&amp; $health-&gt;consecutive_failures &gt;= $alarm_threshold) {<br>        $health-&gt;is_alarmed = true;<br>        $health-&gt;alarmed_at = Carbon::now();<br>        $health-&gt;save();<br>        $this-&gt;notify(&quot;{$source_label} has failed {$health-&gt;consecutive_failures} consecutive times.&quot;);<br>        return;<br>    }<br><br>    $health-&gt;save();<br>}</pre><p>The scraper just reports each attempt, record_result(..., success: true) or false with the error, and the service handles the rest.</p><p>What makes this work:</p><ul><li><strong>Consecutive, not total.</strong> A success resets the counter to zero. A source that fails one run in ten never alarms. A source that fails every single run eventually does. That’s the difference between “flaky” and “dead”.</li><li><strong>A configurable threshold.</strong> Different sources deserve different patience. A feed polled every few minutes can afford a higher count than one polled daily. My default is deliberately high, because I’d rather be a little late than cry wolf.</li><li><strong>Alarm once.</strong> The is_alarmed flag means you get exactly one notification when the threshold is crossed, not one per run after that.</li><li><strong>Automatic re-arming.</strong> The next success clears the flag, so if the source breaks again next month you’ll hear about it again.</li><li><strong>Nothing is ever deleted.</strong> The service doesn’t disable anything. It <em>surfaces</em> the problem (a text to opted-in admins and an entry on a monitoring page) and leaves the decision to a human. Automatic removal is a destructive action on weak evidence, and I’ve been burned by it.</li><li><strong>The last error is kept.</strong> last_error_message means the monitoring page tells you <em>why</em> it&#39;s failing, not just that it is: a 404 means the feed moved, a timeout means the server is struggling, a parse error means they changed the format.</li></ul><h3>How the two patterns fit together</h3><p>Think of it as two layers of defence:</p><p><strong>Step isolation.</strong> Did the whole job get through its list?</p><p><strong>Source health.</strong> Is this specific feed or station healthy over time?</p><p>Step isolation protects the <em>run</em>. Source health protects the <em>long term</em>. A third layer sits above both: a monitor that records every job’s outcome and alerts on failure or silence, which I’ve written about separately.</p><h3>Lessons that generalize</h3><ol><li><strong>Never let list order decide what survives.</strong> If step three can kill step four, you’ve created a hidden priority system.</li><li><strong>Isolate, but don’t hide.</strong> Catching exceptions is fine as long as you re-raise a summary. A job that swallows failures is worse than one that crashes.</li><li><strong>Measure persistence, not events.</strong> One failure is noise. Fifty in a row is a signal.</li><li><strong>Make alarms edge-triggered.</strong> Notify on the transition into a bad state, clear on recovery, and stay quiet in between.</li><li><strong>Detect automatically, decide manually.</strong> Machines are good at noticing that something is wrong, and humans are better at deciding whether to remove a source.</li><li><strong>Keep the last error.</strong> A failure count without a reason sends you straight back to reproducing the problem by hand.</li></ol><p>The code for both is under 150 lines. The payoff has been far larger than that, mostly in the form of problems I found on day one instead of day nine.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li><a href="https://medium.coderun.ca/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li><a href="https://medium.com/@the-webhamster/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li>Stop One Broken Feed From Killing Your Whole Scraper Run</li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li><li><a href="https://medium.coderun.ca/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333">“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=781708eaa75e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a News Briefing Agent: Heuristics First, LLM Second]]></title>
            <link>https://the-webhamster.medium.com/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7dc60d0562</guid>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 13:56:02 GMT</pubDate>
            <atom:updated>2026-11-25T14:45:07.774Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I use plain PHP to boil thousands of daily headlines down to a handful of topics, then hand only those to an AI agent that writes my news briefing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMkDLeN_OLh8H45kQvBPiQ.jpeg" /></figure><blockquote>This is the fourth in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. Links to other articles can be found at the end.</blockquote><p>I keep a personal dashboard that pulls in data from a lot of places: weather, sports scores, launch schedules, new releases, and news. That’s what’s the basis of this whole series of articles. The news part, though, is the one I kept coming back to, because I wanted one thing from it: <strong>a quick answer to “what actually matters today?”</strong> without opening thirty tabs or doomscrolling a dozen feeds.</p><p>Every hour, a scheduled job pulls articles from a long list of news sources, grouped into sections (national, world, business, technology, sports, and so on). That gives me thousands of headlines and blurbs a day. Volume isn’t the hard part. Turning a pile of headlines into five or so real topics per section is.</p><h3>The whole pipeline at a glance</h3><pre>RSS feeds (200+ sources, grouped into sections)<br>        |<br>        |  hourly scrape<br>        |<br>        v<br> news_articles table ............ thousands of titles + blurbs per day<br>        |<br>        |  phrase extraction -&gt; corroboration scoring -&gt; noise filters<br>        |<br>        v<br> news_trending_topics table ..... ~5 topics per section, snapshotted<br>        |<br>        |  GET /api/news/trending/digest   (open, read-only JSON)<br>        |<br>        v<br> Scheduled Claude routine ....... reads the digest, applies a rules file  <br>        |<br>        |<br>        v<br> A short, linked briefing ....... posted once in the morning,<br>                                  plus an &quot;anything new?&quot; check later</pre><p>Everything above the endpoint is deterministic PHP I can debug with a breakpoint. Everything below it is a language model working on a payload small enough to read in one go.</p><h3>Why not an ML model for the first pass?</h3><p>I could have used embeddings, topic modelling, or an LLM call per article. I didn’t, for three reasons:</p><ol><li><strong>Cost.</strong> Running models over thousands of articles every hour adds up quickly for a hobby project.</li><li><strong>Explainability.</strong> When a topic looks wrong, I want to point at a line of code and fix it, not retrain something.</li><li><strong>Good enough is good enough.</strong> I only needed a reasonable first pass. I could hand the <em>result</em> to an LLM later, on a much smaller input.</li></ol><p>So the goal was an ML-free, low-cost way to surface the key topics. Is it perfect? No. Is it a surprisingly good first step? Yes. It runs in plain PHP against the database I already had.</p><h3>The core idea: trust corroboration, not volume</h3><p>Here’s the insight the whole thing rests on:</p><blockquote>If many <strong>independent</strong> outlets write about the same phrase, it’s probably a real story. If one outlet repeats a phrase over and over, it’s probably boilerplate.</blockquote><p>So instead of counting words, I extract <strong>short phrases</strong> (2 to 4 words) from each article’s title and description, then score each phrase mostly by <strong>how many distinct sources used it</strong>.</p><p>Why phrases and not single words? A lone noun makes a poor topic label. “Trump” is vague, while “Interest Rate Decision” is a topic. Real phrases also recur verbatim across independently written articles. The accidental ones, like a phrase made by stripping a stopword out of the middle of a sentence, almost never do, so they sink to the bottom without any special handling.</p><h3>Step 1: turn text into candidate phrases</h3><p>Each title and description is decoded, stripped of stopwords and short or numeric tokens, then sliced into every 2-, 3- and 4-word window:</p><pre>$significant = [];<br>foreach ($words as $word) {<br>    $norm = mb_strtolower($word);<br>    if (mb_strlen($norm) &lt; 3 || is_numeric($norm) || in_array($norm, STOPWORDS, true)) {<br>        continue;<br>    }<br>    $significant[] = $word;<br>}<br><br>for ($n = 2; $n &lt;= 4; $n++) {<br>    for ($i = 0; $i &lt;= count($significant) - $n; $i++) {<br>        $display = implode(&#39; &#39;, array_slice($significant, $i, $n));<br>        $phrases[mb_strtolower($display)] = [&#39;display&#39; =&gt; $display, &#39;n&#39; =&gt; $n];<br>    }<br>}</pre><p>Keying the array by the lowercased phrase means repeats inside one article collapse automatically.</p><h3>Step 2: the scoring formula</h3><pre>$score = ($source_count * 3) + $capped_article_count + ($n - 2);</pre><ul><li><strong>Distinct sources count triple.</strong> Cross-source corroboration is the main signal.</li><li><strong>Article count is secondary, and capped.</strong> No single source can contribute more than 3 articles to a phrase’s score. If one outlet stamps the same byline on 40 articles, it can’t out-rank a phrase that ten different outlets each mentioned once. The true article count is still reported, it just doesn’t inflate the score.</li><li><strong>Longer phrases get a small bonus.</strong> “Donald Trump” beats “Trump” on a tie. The bonus only breaks near-ties and never overrides real cross-source signal.</li></ul><h3>The part that actually took the time: fighting noise</h3><p>The formula above gets you maybe 60% of the way. The rest is a series of fixes for the ways real feeds mislead you. Each of these came from looking at bad output and asking “why is <em>that</em> trending?”</p><p>1. <strong>HTML entities leak into text.</strong> Plenty of feeds put &amp;nbsp; and &amp;quot; straight into descriptions. Left alone, nbsp becomes a &quot;word&quot;. Worse, a decoded non-breaking space doesn&#39;t match PCRE&#39;s \s in default mode, so it quietly glues two words together. The fix is to decode entities and normalize every Unicode space variant to a plain space <em>before</em> tokenizing.</p><p>2. <strong>Outlets name themselves.</strong> Many feeds pad every title or description with their own brand (“… — CityNews Montreal”). Left alone, that self-referential boilerplate “trends” every single day. Any candidate phrase that overlaps the article’s own source organization is dropped for that article.</p><p>3. <strong>Syndicated duplicates pose as corroboration.</strong> Co-owned local affiliates often run the exact same wire story under their own source entries and URLs. That looks like five outlets agreeing, when it’s really one story copied five times. Before scoring, articles whose titles match after normalizing case, punctuation and whitespace are collapsed into one, keeping the copy with the longest description.</p><p>4. <strong>One article shouldn’t fill the leaderboard.</strong> Once an article is picked as the representative link for a topic, it’s removed from the pool for every other topic in that section. Otherwise a single busy article could occupy several of the five slots by producing many overlapping phrases.</p><p>5. <strong>Generic phrases span unrelated stories. </strong>A phrase like “police officer” can show up in two completely different stories and glue them together. So a phrase must contain at least one word that is actually <em>capitalized as a name</em> somewhere in that day’s coverage. Names of people and places identify a story. Generic nouns don’t.</p><p>6. <strong>Same story, different phrase. </strong>A single headline gets sliced into several windows that share no words with each other, so “Prime Minister welcomes visitor” and “discuss Arctic security energy” are opposite ends of one headline. The fix is to compare the <em>sets of articles</em> behind each phrase. If two phrases are backed by nearly the same articles (85% or more of the smaller set), they’re the same story and only the higher-scoring one survives. A looser 50% overlap counts only if the phrases also share a word, and possessives are stripped first so “Clancy” and “Clancy’s” match.</p><p>One honest note on that last fix: my first version was fully transitive, clustering every pair and keeping one phrase per cluster. It sounded more thorough, but generic phrases became hubs that chained unrelated stories together, and one of the two stories vanished. I tested it, confirmed the regression and reverted. The shipped version only compares each candidate against phrases already <em>kept</em>.</p><h3>Picking the winners</h3><p>Selection runs in two passes. First it takes candidates with real support, meaning at least two articles or two sources. If that doesn’t fill the section, it relaxes the rule and tops up from the rest. That way a quiet section still gets a few topics, but strong ones always go first.</p><h3>What it doesn’t do well</h3><p>I’d rather you hear this from me:</p><ul><li>It has <strong>no semantic understanding</strong>. “Rate cut” and “borrowing costs fall” are the same story to a human and unrelated strings here.</li><li>The thresholds (the 3x weight, the cap of 3, the 85% and 50% ratios) are <strong>hand-tuned</strong> against my particular mix of sources. Yours would need adjusting.</li><li>Phrase labels are sometimes <strong>awkward fragments</strong> rather than clean headlines.</li><li>A slow news day can produce <strong>weak topics</strong> because there isn’t much corroboration to find.</li></ul><p>It’s a heuristic, and it behaves like one. But it’s fast, free to run, easy to debug, and the output is good enough to be useful, which brings me to the second half.</p><h3>Cache it, then hand it to an LLM</h3><p>Scoring thousands of articles on every request would be wasteful, so a job runs at 45 minutes past the hour, eight times a day (I started with every hour and cut it back once I saw the extra runs weren’t changing the answer), and <strong>snapshots the results</strong> into a news_trending_topics table, replacing that day&#39;s rows per section. Reads come from the snapshot, and only fall back to a live computation if no snapshot exists yet.</p><p>Each stored topic carries:</p><ul><li>the topic phrase and its score,</li><li>article_count and source_count,</li><li>one representative article: title, description, link and outlet.</li></ul><p>I also built a <strong>digest method</strong> that packages the whole day, grouped by section and ordered by score, with each topic’s representative article text cleaned of markup and double-encoded entities. The point is that an LLM can read the entire day in one request instead of me paying it to read thousands of articles.</p><h3>Closing the loop: an open endpoint for a Chief of Staff agent</h3><p>The last piece is what made the whole thing worthwhile. I expose the digest as a simple read-only JSON endpoint:</p><pre>GET /api/news/trending/digest</pre><pre>{<br>  &quot;date&quot;: &quot;2026-10-21&quot;,<br>  &quot;sections&quot;: {<br>    &quot;business&quot;: [<br>      {<br>        &quot;topic&quot;: &quot;Interest Rate Decision&quot;,<br>        &quot;score&quot;: 31,<br>        &quot;article_count&quot;: 9,<br>        &quot;source_count&quot;: 7,<br>        &quot;article&quot;: {<br>          &quot;title&quot;: &quot;...&quot;,<br>          &quot;text&quot;: &quot;...&quot;,<br>          &quot;link&quot;: &quot;https://...&quot;,<br>          &quot;organization&quot;: &quot;...&quot;,<br>          &quot;published&quot;: &quot;2026-10-21 09:12:00&quot;<br>        }<br>      }<br>    ]<br>  }<br>}</pre><p>It is deliberately open and contains nothing personal. It’s only public news metadata that I’d be happy to have anyone read, which makes it very easy to consume. If no snapshot exists for the day, it returns a 404 instead of making something up.</p><p>On the other end, I’m building a <strong>Chief of Staff agent project</strong> in Claude. A scheduled Claude routine fetches the digest each morning and writes a short briefing, along the lines of “here are the three things in each section worth your attention, and here are the links if you want to dig in.” The routine does the part I’d have found expensive to do with ML at scale: <em>reading comprehension and summarisation</em>. The heuristic does the part that’s cheap to do deterministically: <em>deciding what’s worth reading</em>.</p><p>That division of labour is the real lesson for me:</p><blockquote>Use cheap, transparent code to cut thousands of items down to a handful, then spend your model budget only on that handful.</blockquote><p>The LLM never sees the thousands of raw articles. It sees a handful of representative ones per section (five at most), already ranked by independent corroboration, with the boilerplate and duplicates already stripped. The prompt stays small and the briefing stays relevant.</p><p>In the end, every morning my Chief of Staff provides me this news digest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*d6EZGUJMOqWSI6D7BD3sSQ.png" /></figure><h3>What it saves: the rough numbers</h3><p>I checked, because “cheaper” is easy to claim. The busiest recent day in my development database holds ~<strong>3,500 articles</strong> and roughly around a <strong>million characters</strong> of titles and descriptions. At the usual rule of thumb of roughly four characters per token, that’s around <strong>240,000 tokens</strong> just to <em>read</em> the day once, before the model writes a word. Running a model per article would mean ~3,500 calls a day, and my scoring job runs eight times a day, so a per-article design multiplies that again.</p><p>An average digest is around <strong>50 KB</strong>, roughly <strong>12,400 tokens</strong>: about <strong>19 times smaller</strong> than the raw day, in a single request, once or twice a day. These are rough estimates, not billing data, so plug in your own model’s pricing. The ratio is the point.</p><h3>The routine is a rulebook, not a clever prompt</h3><p>Here is something I didn’t expect: the LLM portion of this process needed just as much iteration as the heuristic. The routine is driven by a plain-text rules file that I keep editing as I see real output, the same “look at bad output and ask why” loop as before. A few of the rules, and the failure each one came from:</p><p><strong>Only use what’s in the payload.</strong> No outside knowledge and no guessing. If a topic’s headline and its article text disagree, the briefing says so briefly instead of smoothing it over. Links are only allowed if they appear in the payload, and a link that was truncated gets swapped for another item’s link on the same story, or dropped. I would rather have a bullet with no link than one with an invented link.</p><p><strong>Dedupe again, across sections.</strong> The heuristic removes duplicates <em>within</em> a section, but the same story still shows up under several of them: a Ukraine talks story under Europe, politics and the US, or a lottery jackpot under two different topic phrases. The routine merges these and shows the story once, in the section where it scores highest. This is a nice example of the split working: the code can’t tell that two differently worded topics are the same story, but a model reading both articles can.</p><p><strong>Let the scores set the layout.</strong> Sections are ordered by the total score of their items. Top sections get four or five bullets, quieter ones get one to three. The ranking work I did in PHP carries straight through to how much space each section gets, so the briefing leads with what the most outlets were covering.</p><p><strong>Editorial filters live in the rules, not the code.</strong> The digest includes everything, but the briefing only covers the sections I care about, and it specifically leaves out sports, celebrity news, trivia columns and product leaks. Those aren’t things I particularly care about in my briefing. Your mileage may vary. New sections that appear in the feed later are left out until I add them. Keeping this in a text file means a change of mind is a one-line edit, not a deploy.</p><p><strong>Flag a lopsided section.</strong> If a section leans heavily on one outlet, the briefing says so. It’s a cheap way to carry the corroboration idea from the scoring step all the way to the reader.</p><p><strong>A strict format beats a good one.</strong> My first sample was paragraphs, and it was harder to skim than the thing it was replacing. Now every section is bullets: one story per bullet, a short bold label, what happened, and a link. The whole thing is capped at around 25 bullets with a one-line footer of story and section counts. Constraints on length are what keep a briefing a briefing.</p><h3>Knowing when to stay quiet</h3><p>The scheduling taught me more than the prompt did. I started with the routine running every hour through the workday, then spent a few days nudging the minute offsets around so it didn’t collide with my other morning briefing. Eventually I looked at what it was producing and cut it to <strong>two runs a day</strong>: a full digest first thing in the morning, and a change check in the early afternoon. I learned that the important stories of the day rarely, if ever, change after the morning feed (and certainly not hourly), so the other runs were just noise.</p><p>The afternoon run doesn’t repost anything. It compares the feed against what has already been posted that day and only reports <strong>new stories </strong>that have appeared as trending stories since the morning (so a breaking major story from around 10AM would likely show up in the afternoon run). A reordering, a score change or a story dropping off the list doesn’t count as a change. If nothing is new, it posts nothing at all. Silence is the right output most days, and it’s the property that keeps me reading the thing that does show up.</p><p>Failure handling follows the same philosophy. If the endpoint errors, times out or returns no sections, the routine posts one short line saying so, and never invents a digest. If the afternoon check fails but the morning run worked, it stays quiet, since there’s nothing useful to add. It also skips weekends and statutory holidays, because a briefing about a day off is just clutter.</p><h3>The unglamorous details</h3><ul><li><strong>The payload is not tiny</strong>. A typical digest is about <strong>50–60 KB</strong>. That is far smaller than thousands of raw articles, and it usually fits in a single fetch. The routine still checks that the response reached the end of the last section, and falls back to a second read if it didn’t. It’s easy to claim a pipeline is lightweight and forget to check.</li><li><strong>Keep scheduled copies in sync.</strong> Because the morning and afternoon runs are separate scheduled tasks with the same instructions, any format change has to be made in both. A single source-of-truth rules file helps, but you still have to remember the copies.</li></ul><h3>Takeaways if you want to build something similar</h3><ol><li><strong>Weight by distinct sources, not raw counts.</strong> Corroboration is a much better signal of “real story” than repetition.</li><li><strong>Cap per-source influence.</strong> It’s a one-line defence against a whole class of boilerplate noise.</li><li><strong>Deduplicate syndicated content before you score.</strong> Otherwise copies masquerade as agreement.</li><li><strong>Look at bad output and ask why. </strong>Almost every rule above is a scar from a specific wrong result.</li><li><strong>Snapshot the expensive computation</strong> and serve reads from the snapshot.</li><li><strong>Put the LLM at the end of the pipeline, not the start.</strong> Let simple code shrink the problem first.</li></ol><p>It won’t replace a real NLP pipeline, and it isn’t trying to. But for a personal project it turns a firehose of feeds into a short, reasonable list of what matters today, for the price of a few cron jobs and some careful regex.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li><a href="https://medium.coderun.ca/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li>Building a News Briefing Agent: Heuristics First, LLM Second</li><li><a href="https://medium.coderun.ca/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li><li><a href="https://medium.coderun.ca/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333">“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7dc60d0562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get]]></title>
            <link>https://the-webhamster.medium.com/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/27561f108755</guid>
            <category><![CDATA[news]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 14:01:04 GMT</pubDate>
            <atom:updated>2026-11-18T13:36:33.984Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How I pull thousands of headlines a day from around the world with plain PHP and cURL, the traps I hit along the way, and what the data looks like at the other end.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1-yUFpWEkx7jlyJ6saogw.jpeg" /></figure><blockquote>This is the third in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. Links to other articles can be found at the end. This article discusses how I built a news scraper to fetch headlines and make them organized and sortable for display.</blockquote><p>News is the noisiest data source in my personal data-aggregation project, and the one I’ve spent the most time on. A typical day brings in 5,000 to 8,000 new articles from more than 200 sources, across more than a dozen sections. The pipeline that does it is not exotic: a scheduled job, a list of feeds, cURL and a database. But getting it to be <em>reliable</em> took years of fixes.</p><p>This is a tour of how it works and what it produces. If you’re thinking about building your own aggregator, I hope it saves you some of those fixes.</p><h3>What I’m collecting (and what I’m not)</h3><p>First, the scope. For each article I store:</p><ul><li>the <strong>title</strong></li><li>the <strong>description</strong> (the short blurb a feed provides)</li><li>the <strong>link</strong> back to the original</li><li>the <strong>publish date</strong></li><li>which <strong>source</strong> it came from</li></ul><p>That’s all. I don’t download or store full article text. This is a deliberate choice, not a limitation:</p><ul><li>Feeds are published so that people can find the original. Headlines and a short blurb with a link back is what they’re for.</li><li>Titles and descriptions are all my later analysis needs. A trending-topics algorithm works on headline phrases, and a daily briefing needs a summary and a link.</li><li>It keeps storage small and the pipeline fast.</li></ul><h3>How sources are organized</h3><p>Each source is a row with an organization name, a feed URL, and a small hierarchy that describes where it belongs:</p><ul><li><strong>taxonomy</strong>: the main section (world, canada, us, europe, business, sports, technology...)</li><li><strong>child taxonomy</strong>: a sub-region (for example a province, a US region, or a country)</li><li><strong>locality</strong>: a specific city, for local outlets</li></ul><p>The section tree looks like this:</p><pre> private const SECTIONS = [<br>        &#39;world&#39; =&gt; [&#39;title&#39; =&gt; &#39;World&#39;, &#39;children&#39; =&gt; null],<br>        &#39;canada&#39; =&gt; [&#39;title&#39; =&gt; &#39;Canada&#39;, &#39;children&#39; =&gt; [<br>            &#39;atlantic&#39; =&gt; [&#39;title&#39; =&gt; &#39;Atlantic&#39;, &#39;children&#39; =&gt; null],<br>            &#39;quebec&#39; =&gt; [&#39;title&#39; =&gt; &#39;Quebec&#39;, &#39;children&#39; =&gt; null],<br>            &#39;ontario&#39; =&gt; [&#39;title&#39; =&gt; &#39;Ontario&#39;, &#39;children&#39; =&gt; null],<br>            &#39;manitoba&#39; =&gt; [&#39;title&#39; =&gt; &#39;Manitoba&#39;, &#39;children&#39; =&gt; null],<br>            &#39;saskatchewan&#39; =&gt; [&#39;title&#39; =&gt; &#39;Saskatchewan&#39;, &#39;children&#39; =&gt; null],<br>            &#39;alberta&#39; =&gt; [&#39;title&#39; =&gt; &#39;Alberta&#39;, &#39;children&#39; =&gt; null],<br>            &#39;bc&#39; =&gt; [&#39;title&#39; =&gt; &#39;British Columbia&#39;, &#39;children&#39; =&gt; null],<br>            &#39;north&#39; =&gt; [&#39;title&#39; =&gt; &#39;North&#39;, &#39;children&#39; =&gt; null],<br>        ]],<br>        &#39;us&#39; =&gt; [&#39;title&#39; =&gt; &#39;United States&#39;, &#39;children&#39; =&gt; [<br>            &#39;northeast-us&#39; =&gt; [&#39;title&#39; =&gt; &#39;Northeast&#39;, &#39;children&#39; =&gt; null],<br>            &#39;southeast-us&#39; =&gt; [&#39;title&#39; =&gt; &#39;Southeast&#39;, &#39;children&#39; =&gt; null],<br>            &#39;midwest-us&#39; =&gt; [&#39;title&#39; =&gt; &#39;Midwest&#39;, &#39;children&#39; =&gt; null],<br>            &#39;southwest-us&#39; =&gt; [&#39;title&#39; =&gt; &#39;Southwest&#39;, &#39;children&#39; =&gt; null],<br>            &#39;pacific-us&#39; =&gt; [&#39;title&#39; =&gt; &#39;Pacific&#39;, &#39;children&#39; =&gt; null],<br>        ]],<br>        &#39;europe&#39; =&gt; [&#39;title&#39; =&gt; &#39;Europe&#39;, &#39;children&#39; =&gt; [<br>            &#39;united-kingdom&#39; =&gt; [&#39;title&#39; =&gt; &#39;United Kingdom&#39;, &#39;children&#39; =&gt; null],<br>            &#39;france&#39; =&gt; [&#39;title&#39; =&gt; &#39;France&#39;, &#39;children&#39; =&gt; null],<br>            &#39;switzerland&#39; =&gt; [&#39;title&#39; =&gt; &#39;Switzerland&#39;, &#39;children&#39; =&gt; null],<br>            &#39;germany&#39; =&gt; [&#39;title&#39; =&gt; &#39;Germany&#39;, &#39;children&#39; =&gt; null],<br>            &#39;russia&#39; =&gt; [&#39;title&#39; =&gt; &#39;Russia&#39;, &#39;children&#39; =&gt; null],<br>            &#39;sweden&#39; =&gt; [&#39;title&#39; =&gt; &#39;Sweden&#39;, &#39;children&#39; =&gt; null],<br>            &#39;netherlands&#39; =&gt; [&#39;title&#39; =&gt; &#39;Netherlands&#39;, &#39;children&#39; =&gt; null],<br>            &#39;ireland&#39; =&gt; [&#39;title&#39; =&gt; &#39;Ireland&#39;, &#39;children&#39; =&gt; null],<br>            &#39;italy&#39; =&gt; [&#39;title&#39; =&gt; &#39;Italy&#39;, &#39;children&#39; =&gt; null],<br>        ]],<br>        &#39;asia-pacific&#39; =&gt; [&#39;title&#39; =&gt; &#39;Asia-Pacific&#39;, &#39;children&#39; =&gt; [<br>            &#39;australia&#39; =&gt; [&#39;title&#39; =&gt; &#39;Australia&#39;, &#39;children&#39; =&gt; null],<br>            &#39;japan&#39; =&gt; [&#39;title&#39; =&gt; &#39;Japan&#39;, &#39;children&#39; =&gt; null],<br>            &#39;china&#39; =&gt; [&#39;title&#39; =&gt; &#39;China&#39;, &#39;children&#39; =&gt; null],<br>            &#39;india&#39; =&gt; [&#39;title&#39; =&gt; &#39;India&#39;, &#39;children&#39; =&gt; null],<br>        ]],<br>        &#39;politics&#39; =&gt; [&#39;title&#39; =&gt; &#39;Politics&#39;, &#39;children&#39; =&gt; null],<br>        &#39;business&#39; =&gt; [&#39;title&#39; =&gt; &#39;Business&#39;, &#39;children&#39; =&gt; null],<br>        &#39;sports&#39; =&gt; [&#39;title&#39; =&gt; &#39;Sports&#39;, &#39;children&#39; =&gt; null],<br>        &#39;arts&#39; =&gt; [&#39;title&#39; =&gt; &#39;Arts&#39;, &#39;children&#39; =&gt; null],<br>        &#39;technology&#39; =&gt; [&#39;title&#39; =&gt; &#39;Technology&#39;, &#39;children&#39; =&gt; null],<br>        &#39;lifestyle&#39; =&gt; [&#39;title&#39; =&gt; &#39;Lifestyle&#39;, &#39;children&#39; =&gt; null],<br>        &#39;travel&#39; =&gt; [&#39;title&#39; =&gt; &#39;Travel&#39;, &#39;children&#39; =&gt; null],<br>    ];</pre><p>The sources themselves are seeded from a JSON file through an upgrade step, so a fresh install can rebuild the whole list with one command. At the moment there are about 215 sources: roughly 185 plain RSS feeds that are active, plus 24 queries against a news-search API that fill in places RSS doesn’t cover.</p><p>This structure matters more than it looks. Because every article is tied to a source and every source to a section, I can ask questions like “what’s trending in business today?” or “what’s the local coverage in this region?” with a single join.</p><h3>The schedule</h3><p>A scheduled job runs every 30 minutes. It’s wrapped in monitoring and uses withoutOverlapping() with an explicit lock expiry, so a slow run can&#39;t pile up on the next one and a crashed run can&#39;t silently block the job for a day.</p><p>Each run does two things:</p><ol><li><strong>API sources</strong>, but only occasionally. The news-search API’s free tier allows 250 requests a day, and each active query consumes one request. With 24 queries, I can afford about 10 passes a day, so the code only calls the API on the top of the hour between 8am and 6pm. Ten passes of 24 queries is 240 requests, which sits just under the cap. This is a good example of making a quota a <em>structural</em> property of the schedule, rather than something you check at runtime.</li><li><strong>RSS sources</strong>, every time. This is the interesting part.</li></ol><h3>Fetching feeds: parallel, polite and diagnosable</h3><p>My first version fetched feeds one at a time with file_get_contents(). It worked, until it didn&#39;t. Two problems surfaced, and the fix to each shaped the current design.</p><h3>Problem 1: it was slow</h3><p>Two hundred feeds fetched serially, each with its own latency, adds up. The fix is to fetch in batches of ten in parallel using curl_multi:</p><pre>foreach ($sources-&gt;chunk(10) as $batch) {<br>    $responses = $this-&gt;_fetch_rss_feeds($batch-&gt;all());<br>    foreach ($batch as $source) {<br>        // parse, store, and record the outcome for this source<br>    }<br>}</pre><p>Batching, rather than firing all 200 at once, keeps memory use sane and avoids hammering the network (or any single host) with a flood of simultaneous connections. Ten at a time was the sweet spot for me.</p><h3>Problem 2: some feeds started blocking me</h3><p>This one was subtle. A few feeds sat behind a CDN or web application firewall that intermittently throttled or blocked my requests. The feeds were fine in a browser. What gave me away, I eventually worked out, was that file_get_contents() sends <em>no User-Agent at all</em>, and when I sent identical-looking requests on a perfectly regular 30-minute rhythm, the pattern looked like automated traffic and got flagged.</p><p>The fix was to look like a normal client: a standard browser-style User-Agent, normal Accept and Accept-Language headers, gzip/deflate enabled, HTTP/2, sensible timeouts, and a cap on redirects.</p><pre>CURLOPT_CONNECTTIMEOUT =&gt; 5,<br>CURLOPT_TIMEOUT        =&gt; 20,<br>CURLOPT_MAXREDIRS      =&gt; 5,<br>CURLOPT_ENCODING       =&gt; &#39;&#39;,            // accept gzip/deflate<br>CURLOPT_HTTP_VERSION   =&gt; CURL_HTTP_VERSION_2TLS,</pre><p>A word on etiquette: that is a trade-off. Looking like a browser keeps overzealous bot filters from misclassifying a harmless feed reader, but it isn’t the same as identifying yourself. If you’re building something like this, read each site’s terms, stick to the feeds they publish for syndication, keep your request volume modest, and use the next trick, which is the single best thing you can do for both of you.</p><h3>The best trick: conditional requests</h3><p>Most feeds don’t change every 30 minutes. Re-downloading and re-parsing an unchanged feed wastes bandwidth for you and for them.</p><p>HTTP has a solution built in. When a server sends a feed, it usually includes an ETag and/or Last-Modified header. I store both per source. On the next poll I send them back as If-None-Match and If-Modified-Since. If nothing changed, the server replies 304 Not Modified with no body, which is tiny and cheap.</p><pre>if ($source-&gt;http_etag) {<br>    $request_headers[] = &#39;If-None-Match: &#39; . $source-&gt;http_etag;<br>}<br>if ($source-&gt;http_last_modified) {<br>    $request_headers[] = &#39;If-Modified-Since: &#39; . $source-&gt;http_last_modified;<br>}</pre><p>A 304 is treated as a <em>healthy</em> result: reset the failure count, skip parsing entirely, move on. About a third of my sources currently support this and have validators stored. It&#39;s a small thing that makes the whole process lighter.</p><h3>Make failures diagnosable</h3><p>When a fetch fails, I record <em>why</em>: a cURL error string (“Operation timed out”, “Could not resolve host”) or the HTTP status (“HTTP 403”). Early on, failures were silently discarded, and I’d end up with a source that was “broken” with no hint as to whether it was a typo in the URL, a blocked request, or a dead server. A failure that carries its reason is a failure you can fix in a minute.</p><h3>Cleaning and parsing: the messy middle</h3><p>A feed in the wild is not tidy. I’ve seen:</p><ul><li>HTML tags and CDATA wrappers inside titles and descriptions</li><li>HTML entities that are doubly encoded, so &amp;amp;nbsp; instead of a space</li><li>smart quotes and en-dashes in various encodings</li><li>emoji in descriptions</li><li>items with no title but a description, or the reverse</li><li>dates in several formats, and the occasional date in the future</li></ul><p>So there’s a two-stage process: a <strong>cleaner</strong> that normalizes raw feed text, and a <strong>parser</strong> that pulls out channel and item fields (title, link, description, date, author, category, media thumbnail and so on).</p><p>A few of the rules are worth calling out:</p><ul><li><strong>Fill in the gaps.</strong> If an item has no title but has a description, a trimmed description becomes the title. If it has a title but no description, the title is the description. Without this, those items would be dropped as junk.</li><li><strong>Skip items that aren’t articles. </strong>Anything with no title or link is rejected. So are items whose “title” is just a URL.</li><li><strong>Don’t trust future dates.</strong> If an article claims to be published in the future (a time-zone mistake or a bad feed), I replace the date with the time I fetched it.</li><li><strong>Find the image anywhere.</strong> Thumbnails show up as paired tags, as self-closing media:thumbnail tags, or inside media:content, so the parser tries all of them.</li><li><strong>Strip emoji and markup, and decode entities</strong> on the way into the database, so what’s stored is plain text.</li><li><strong>Filter obituaries.</strong> Many local newspapers syndicate paid obituary listings in the same feed as the news. A pattern that matches “obituary” and life-span ranges like “(1951–2026)” drops them. They’re not news, and they’d otherwise pollute every analysis downstream.</li></ul><h3>A confession about the parser</h3><p>The parser uses regular expressions rather than a proper XML library. That sounds heretical, and in general I’d say use a real parser. The reason I got here is practical: a surprising number of real-world feeds are <em>not valid XML</em>. Unescaped ampersands, stray control characters and truncated documents will make a strict parser throw away an entire feed, while a forgiving regex pass extracts the items it can. For my purposes, an imperfect parse of a broken feed beats no parse at all. If your sources are all well-behaved, you don’t need this.</p><h3>Storing it: idempotent by design</h3><p>Because the job runs every 30 minutes and most articles will be seen many times, writing has to be idempotent. Each article gets a stable key (a hash of its link for RSS, or the API’s own id), a unique constraint on that key, and an upsert:</p><pre>NewsArticles::upsert(<br>    $rows,<br>    [&#39;unique_id&#39;],                           // the key to match on<br>    [&#39;date&#39;, &#39;title&#39;, &#39;description&#39;, &#39;link&#39;] // what to refresh if it already exists<br>);</pre><p>If I see the same article again, nothing is duplicated. If a publisher edits the headline, the stored copy is updated. Writing a batch in one statement per source is also much faster than inserting row by row.</p><p>Keying on a hash of the link was a decision I’d make again. The link is the one thing every feed reliably provides, and it’s what makes an article <em>that</em> article. Feeds that use unstable GUIDs or recycle IDs can’t confuse it.</p><p>Old data is purged after about six months.</p><h3>Watching it: health, not just success</h3><p>A scraper of this scale is always partly broken, so every source reports into a health tracker after each attempt. A source that fails once or twice is ignored. A source that fails continuously across a long stretch raises an alarm to me and appears on a monitoring page, along with its last error message. A success clears the count.</p><p>The scraper also keeps its own failure counter on each source, and after a long unbroken run of failures it deactivates the source. I raised that threshold to 50 consecutive failures after an earlier, much more trigger-happy version removed good feeds during temporary network problems. At the moment, of about 215 sources, around 209 are active and 6 have been switched off after prolonged failure.</p><h3>What it actually gets</h3><p>Here’s a snapshot from my own database, so you can calibrate:</p><ul><li><strong>About 215 sources</strong>, around 209 of them active</li><li><strong>Roughly 5,000 to 8,000 new articles per day</strong> on a typical full day</li><li><strong>A bit over 600,000 articles</strong> in the table in total, of which about <strong>99.7% have a usable description</strong></li><li>About <strong>170 articles per source per week</strong> on average, though the spread is huge: some sources publish a few items a day, and one prolific feed produced thousands in a week</li></ul><p>That last point is worth sitting with. Volume is wildly uneven, and by section it’s uneven too. Over a recent week, one regional section produced the most articles, while a section I think of as “big”, like politics, produced far fewer than several others. If you analyze this data without thinking about that skew, whichever sources publish most will drive your conclusions. (It’s exactly why my trending-topics algorithm caps how much any single source can contribute to a topic’s score.)</p><h3>How I Use It</h3><p>The major use of this data right now is on my personal dashboard web application. It appears like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pUZAY7Cius811YuiyRiLQ.png" /></figure><p>There are other things I’m doing with it that will be explored in later articles, including passing distilled data off to a LLM for summary.</p><h3>Lessons</h3><ol><li><strong>Fetch in parallel, in batches.</strong> Ten at a time gave me most of the speed with none of the pile-on.</li><li><strong>Use conditional requests.</strong> ETag and Last-Modified turn most polls into a near-free 304.</li><li><strong>Look like a reasonable client.</strong> A missing User-Agent and a perfectly regular rhythm can get a harmless request blocked.</li><li><strong>Record why things fail.</strong> An error message turns hours of guessing into a minute of fixing.</li><li><strong>Be forgiving in what you parse and strict in what you store.</strong> Real feeds are messy, but your database shouldn’t be.</li><li><strong>Make writes idempotent.</strong> A stable key plus an upsert means you can run the job as often as you like.</li><li><strong>Design around your quotas.</strong> If an API allows 250 calls a day, bake that into the schedule so you can’t exceed it.</li><li><strong>Expect skew.</strong> A handful of prolific sources can dominate any count, so build your analysis to be robust to that.</li><li><strong>Store only what you need.</strong> Headlines, blurbs and links are enough for almost everything I do, and they keep the system small, fast and respectful.</li></ol><p>None of this is glamorous, and that’s the lesson. A news aggregator isn’t hard because of any one clever technique. It’s hard because there are two hundred feeds, each one slightly broken in its own way, and the system has to keep working anyway.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li>Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</li><li><a href="https://medium.com/@the-webhamster/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li><a href="https://medium.coderun.ca/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27561f108755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire]]></title>
            <link>https://the-webhamster.medium.com/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/44110eb3eb80</guid>
            <category><![CDATA[livewire]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 15:35:37 GMT</pubDate>
            <atom:updated>2026-11-25T14:42:37.333Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Single-file components, self-refreshing cards, per-user personalization and a shared design system, all driven from PHP.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M7yYF4WmDGy8WrMzL-yNQg.png" /></figure><blockquote>This is the second in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. The first article is <a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">here</a>. This article discusses the front-end technology I used to build it. Future articles will deep-dive into the back-end technology too.</blockquote><p>My personal dashboard’s home page shows about 25 live panels at once: weather, a news feed, sports scores, what’s playing, upcoming launches, a comic, and more. Each one has its own data, its own refresh rate, and its own personalization. A few years ago I’d have reached for a JavaScript single-page app plus a JSON API.</p><p>This time I didn’t. I built the entire front end with <strong>Livewire</strong>, a <strong>Laravel</strong> library that lets you write interactive components in PHP and handles the browser round trips for you. There’s no build step for components, no client-side state management, and almost no hand-written JavaScript.</p><p>This article walks through how the dashboard is put together, what worked, and what I’d change. If you work in Laravel and you’ve never built anything substantial with Livewire, I hope it shows what’s possible.</p><h3>The stack in one paragraph</h3><p>Laravel on the backend. <strong>Livewire 4</strong> for components. <strong>Tailwind CSS v4</strong> with <strong>DaisyUI</strong> for the look, and a charting component from the <strong>MaryUI</strong> library for graphs. <strong>Alpine.js</strong> (which ships with Livewire) for the small client-side bits. <strong>Vite</strong> bundles the CSS and one tiny JS file. There are about <strong>100 component files</strong>, and every page of the site is assembled from them.</p><h3>The core idea: a page is just a shell</h3><p>Routes point straight at views, with no controller in between:</p><pre>Route::view(&#39;/&#39;, &#39;pages.dashboard&#39;)-&gt;name(&#39;dashboard&#39;);<br>Route::view(&#39;news&#39;, &#39;pages.news&#39;)-&gt;name(&#39;news&#39;);<br>Route::view(&#39;weather&#39;, &#39;pages.weather&#39;)-&gt;name(&#39;weather&#39;);</pre><p>A page view does almost nothing. It wraps itself in a layout and arranges components:</p><pre>&lt;x-layouts::main.app :title=&quot;__(&#39;Home&#39;)&quot;&gt;<br>    &lt;div class=&quot;grid grid-cols-12 gap-4 xl:gap-6&quot;&gt;<br>        &lt;livewire:weather.dashboard.forecast /&gt;<br>        &lt;livewire:weather.dashboard.temperature-chart /&gt;<br>        &lt;livewire:news.city-headlines :city_id=&quot;$pref_city_id&quot; /&gt;<br>        &lt;livewire:spotify.dashboard.recent-tracks :limit=50 /&gt;<br>        &lt;livewire:sports.dashboard.consolidated-scoreboard /&gt;<br>    &lt;/div&gt;<br>&lt;/x-layouts::main.app&gt;</pre><p>The home page is a series of themed sections (“Around You”, “Quick Bits”, “Tunes &amp; Teams”, “Queued Up”), and each section is a 12-column CSS grid of components. That’s the whole page. Everything interesting happens inside the cards.</p><h3>Single-file components</h3><p>Livewire 4 lets a component live in <strong>one file</strong>: PHP class on top, Blade template underneath. Here’s a trimmed real example, the weather forecast card:</p><pre>&lt;?php<br>use App\Services\Core\UsersSettingsService;<br>use App\Traits\WeatherForecastCard;<br>use Livewire\Component;<br><br>new class extends Component {<br>    use WeatherForecastCard;<br><br>    public bool $show_city_in_title = true;<br><br>    public function mount(bool $show_city_in_title = true) {<br>        $this-&gt;show_city_in_title = $show_city_in_title;<br>        $settings = app(UsersSettingsService::class)-&gt;get_settings(auth()-&gt;id());<br>        $this-&gt;city_id = $settings[&#39;pref_my_city&#39;];<br>        $this-&gt;get_data();<br>    }<br>};<br>?&gt;<br><br>&lt;div class=&quot;card-surface flex flex-col col-span-full xl:col-span-3&quot;<br>     wire:poll.600s=&quot;get_data&quot;&gt;<br>    &lt;header&gt;...&lt;/header&gt;<br>    @if(!empty($this-&gt;data))<br>        @include(&#39;partials.main.forecast-body&#39;, [&#39;data&#39; =&gt; $this-&gt;data])<br>    @else<br>        &lt;div class=&quot;text-sm text-muted&quot;&gt;Weather data is not available yet.&lt;/div&gt;<br>    @endif<br>&lt;/div&gt;</pre><p>I love this format for dashboards. When I want to change a card, everything about it (what it loads, how often it refreshes, how it looks) is in one place on one screen. The files are organized into folders by domain (weather, news, sports, space, music), and the tag name mirrors the path, so &lt;livewire:weather.dashboard.forecast /&gt; lives in weather/dashboard/forecast.blade.php. That makes components easy to find.</p><p>Every card has the same anatomy:</p><ol><li>mount() runs once when the card is created. It reads the user&#39;s settings and loads the first batch of data.</li><li>get_data() (my naming convention) fetches fresh data and assigns it to public properties.</li><li>The template renders those properties.</li><li>A wire:poll attribute on the root element calls get_data() on a timer.</li></ol><p>That’s it. Twenty-five cards, one pattern.</p><h3>Self-refreshing cards: poll at the speed of your data</h3><p>wire:poll is the magic that makes a dashboard feel alive. Add wire:poll.30s=&quot;get_data&quot; to an element and Livewire re-calls that method every 30 seconds and swaps in the changed HTML. No websockets, no JavaScript.</p><p>The part I’m proudest of is that<strong> each card polls at the speed its data actually changes</strong>. Across the app, I use these intervals:</p><p><strong>30 seconds</strong>: Now-playing music and the admin monitoring panel</p><p><strong>60 seconds</strong>: The music-stats pages (albums, artists, tracks, overall stats)</p><p><strong>5 minutes</strong>: Sports scoreboards</p><p><strong>10 minutes</strong>: Weather, news headlines, sensor charts, article feeds</p><p><strong>15 minutes</strong>: Traffic events, flights overhead, local headlines, community posts</p><p><strong>1 hour</strong>: Things that barely change: comics, “today in history”, upcoming launches, movies, TV and album releases</p><p>The rule is simple: <strong>never poll faster than the backend can produce new data</strong>. My scrapers run on a schedule, so a card that polls every 5 seconds just asks the same question over and over. About 40 polling declarations exist across the app, and the most common interval is hourly. A dashboard with 25 cards on a 30-second timer would hammer the server for no benefit.</p><p>Livewire also helps here: as I understand its documentation, it throttles polling when the browser tab is in the background, so a dashboard left open overnight shouldn’t generate traffic the way a naive setInterval loop would. (Check the current docs for the exact behaviour.)</p><h3>Personalization: one dashboard, many users</h3><p>The dashboard is the same code for every visitor, but it renders differently for each one. Two mechanisms make that work.</p><p><strong>1. Settings with defaults.</strong> Each user has key/value preferences: home city, which news sections they follow, which sports leagues and favourite teams, and so on. A small service merges stored values over a set of defaults:</p><pre>public function get_settings(?int $user_id = null): array {<br>    $result = [];<br>    if ($user_id) {<br>        foreach (UserSettings::get_by_user_id($user_id) as $setting) {<br>            $result[$setting-&gt;name] = $this-&gt;_decode($setting-&gt;value);<br>        }<br>    }<br>    return array_merge(self::DEFAULT_SETTINGS, $result);<br>}</pre><p>The trick is the ?int $user_id = null. A guest has no id, gets only the defaults, and the dashboard still renders fully. There&#39;s no special &quot;logged-out&quot; code path. Logged-out users simply see the default configuration.</p><p><strong>2. Components read the settings themselves.</strong> The dashboard page looks up the user’s home city once and passes it down as a prop (:city_id=&quot;$pref_city_id&quot;), so multiple &quot;around you&quot; cards stay consistent. Individual cards read what they need. The headlines card builds its list of sections from the user&#39;s pref_news_sections. The scoreboard reads pref_sports_leagues and highlights favourite teams with a heart. Whole sections can be switched off:</p><pre>@if(app(UsersSettingsService::class)-&gt;get_settings(auth()-&gt;id())[&#39;pref_dashboard_news&#39;] ?? true)<br>    &lt;livewire:news.dashboard-headlines /&gt;<br>@endif</pre><p>The settings screen is itself a Livewire component, and a lovely example of how little code a form needs. Public properties hold the preferences, wire:model binds them to inputs, and one save_content_settings() method persists everything:</p><pre>&lt;form wire:submit=&quot;save_content_settings&quot;&gt;<br>    &lt;select wire:model=&quot;pref_my_city&quot;&gt; ... &lt;/select&gt;<br>    &lt;input type=&quot;checkbox&quot; wire:model=&quot;pref_dashboard_news&quot; class=&quot;toggle toggle-primary&quot;/&gt;<br>&lt;/form&gt;</pre><p>No API endpoint, no fetch call, no form serialization code.</p><h3>Authorization: components are endpoints</h3><p>A subtle point that catches people out: every public method on a Livewire component can be called from the browser. A component isn’t just a view. It’s an API surface.</p><p>So gating a page with route middleware isn’t enough. My admin monitoring panel checks the permission <strong>inside the component</strong>, both when it loads and in the method that refreshes it:</p><pre>public function mount(): void {<br>    abort_unless(auth()-&gt;user()?-&gt;hasPermission(&#39;is_admin&#39;), 403);<br>    $this-&gt;load();<br>}<br><br>public function load(): void {<br>    abort_unless(auth()-&gt;user()?-&gt;hasPermission(&#39;is_admin&#39;), 403);<br>    // ...<br>}</pre><p>The defence has layers:</p><ul><li><strong>Route middleware</strong> (permission:is_admin) keeps people out of the page.</li><li>@can <strong>checks in templates</strong> hide sections a user shouldn&#39;t see.</li><li>abort_unless <strong>inside the component</strong> means that even someone who crafts a request to the component directly can&#39;t get data.</li></ul><p>The rule of thumb: authorize in the component, and treat the other layers as convenience.</p><h3>Components that talk to each other</h3><p>Most cards are self-contained, but the news page needs coordination. It shows a grid of sections. Click “Regions” on one and the page drills into its child sections. Click “Sources” and it shows the individual outlets. A search box filters everything.</p><p>This is built with three tools:</p><p><strong>Events</strong>. A child dispatches an event and the parent listens:</p><pre>// child<br>public function drill_into_children(): void {<br>    $this-&gt;dispatch(&#39;drill-into&#39;, key: $this-&gt;section_key);<br>}<br><br>// parent<br>#[On(&#39;drill-into&#39;)]<br>public function drill_into(string $key): void {<br>    $this-&gt;drill_down = $key;<br>    $this-&gt;source_view = null;<br>}</pre><p><strong>Reactive props</strong>. The search text lives in the parent. Children declare it #[Reactive], so when the parent&#39;s value changes, every child updates without being re-mounted. The input is debounced so I&#39;m not querying on every keystroke:</p><pre>&lt;input wire:model.live.debounce.400ms=&quot;search&quot; placeholder=&quot;Search headlines…&quot; /&gt;</pre><p><strong>Keys</strong>. When rendering lists of components in a loop, each needs a unique :key (for example &#39;child-&#39;.$child_key). Without keys, Livewire can&#39;t tell which child is which when the list changes, and you get stale or mixed-up data.</p><p>On the dashboard, the same cards behave slightly differently, because the “drill into” event triggers a redirect to the full news page instead of switching views in place. One component, two behaviours, and the difference is a single listener.</p><p>The URL stays honest too: the news page reads ?section= and ?sources= from the request in mount(), so a drilled-in view can be linked and bookmarked.</p><h3>Responsive design without a second codebase</h3><p>I built the layout mobile-first with Tailwind classes, and a few small patterns handle the rest.</p><ul><li><strong>Grid spans:</strong> col-span-full xl:col-span-4 means a card fills the row on small screens and takes a third of it on wide ones.</li><li><strong>Hiding cards:</strong> hidden sm:flex removes the detailed scoreboard on phones, where it&#39;s too wide to be useful.</li><li><strong>Scrollable cards:</strong> xl:max-h-150 overflow-y-auto caps a card&#39;s height on large screens, so a long list doesn&#39;t push the layout around.</li><li><strong>Trimming data on small screens.</strong> A news card normally shows 50 headlines. On a phone that’s a wall of text, so it asks for fewer on load using Alpine:</li></ul><pre>&lt;div x-data x-init=&quot;if (window.innerWidth &lt; 640) $wire.set_limit(&#39;5&#39;)&quot;&gt;</pre><p>Alpine reads the viewport, calls a Livewire method on the server, and the component re-renders with five items. It’s two lines and avoids duplicating components for mobile.</p><h3>Charts from PHP</h3><p>Charts are built in the component’s PHP, as a Chart.js configuration array. The component fetches data, shapes it into a config and hands it to the chart component:</p><pre>$this-&gt;chart = [<br>    &#39;type&#39; =&gt; &#39;line&#39;,<br>    &#39;data&#39; =&gt; [<br>        &#39;labels&#39; =&gt; $data[&#39;time&#39;],<br>        &#39;datasets&#39; =&gt; [[<br>            &#39;label&#39; =&gt; &#39;Temperature&#39;,<br>            &#39;data&#39; =&gt; $data[&#39;temp&#39;],<br>            &#39;fill&#39; =&gt; true,<br>            &#39;tension&#39; =&gt; 0.4,<br>            &#39;pointRadius&#39; =&gt; 0,<br>        ]],<br>    ],<br>];</pre><pre>&lt;x-chart wire:model=&quot;chart&quot; /&gt;</pre><p>Because the chart is just a public property, the polling mechanism updates it for free. Every poll rebuilds the array and the chart redraws. I never touch a charting library’s API directly.</p><h3>One design system, five looks</h3><p>The site is really several small apps: the main dashboard, a music-stats section, a finance section and two small novelty tools. They share infrastructure but each has its own look, so each has:</p><ul><li>its own <strong>layout</strong> (a header plus a slot), and</li><li>its own <strong>theme</strong> stylesheet.</li></ul><p>Underneath, everything uses one set of tokens. DaisyUI themes are defined in CSS as variables (primary, secondary, base colors, and so on), and a custom card-surface class defines what a card looks like, so every card in every app inherits the same border, background and radius. Switching themes changes the variables, and all 100 components pick it up without edits.</p><p>Dark mode is a second theme for the main app. A tiny inline script in the document head decides which theme to use <em>before the first paint</em>, from the saved preference or else the operating system setting:</p><pre>var stored = localStorage.getItem(&#39;theme&#39;);<br>var dark = stored ? stored === &#39;dark&#39; : window.matchMedia(&#39;(prefers-color-scheme: dark)&#39;).matches;<br>if (dark) { html.setAttribute(&#39;data-theme&#39;, &#39;main-dark&#39;); }</pre><p>Without it, dark-mode users get a bright flash on every page load while the real theme loads. The toggle button is a small Alpine component that flips the attribute and saves the choice.</p><h3>Sharing code between cards</h3><p>When two components need the same logic, there are three tools, and I use all of them.</p><ul><li><strong>Traits</strong> for shared component behaviour. Several weather cards use one trait that provides the city id, the data array and the get_data() method. The cards differ only in their templates and in how they find the city.</li><li><strong>Blade partials</strong> for shared markup. The forecast body is a partial used by the dashboard card and the full weather page.</li><li><strong>Reusable components </strong>for shared UI, such as a header with an icon and title.</li></ul><h3>Testing components</h3><p>Livewire makes components easy to test, because you can mount one and assert on its state without a browser. I have two kinds of tests:</p><ul><li><strong>Smoke tests</strong> render every page against an empty database, to catch broken templates.</li><li><strong>Data tests</strong> seed a realistic database (a user, a city, news articles, a game, tracks) and mount every read-only component against it, so the formatting code actually runs on real-looking rows.</li></ul><p>The second kind exercises code paths the empty-database smoke tests never reach, because the data-formatting code only runs when there are rows to format.</p><h3>Mistakes and what I’d change</h3><p><strong>Cards call controllers.</strong> Many components fetch data through app(SomeController::class)-&gt;get_something(), reusing the methods my API already had. It was fast to build, but it blurs the layering: a controller is an HTTP concern, and a component shouldn&#39;t depend on one. If I started over, components would call the services directly and the controllers would be thin wrappers over the same services.</p><p><strong>Public properties are part of the page</strong>. Everything in a public property is serialized into the HTML and sent back and forth on every round trip. A card with a 50-item array of tracks adds real weight to every poll. It also means a <strong>public property is visible to the user</strong>, so never keep anything sensitive in one. Keep public state minimal.</p><p><strong>No lazy loading yet.</strong> The home page mounts about 25 components in one request, so the first paint waits for the slowest card. Livewire supports deferring components until after the initial load. That’s the obvious next improvement, and it’d make the page feel faster without changing any data code.</p><p><strong>Every card polls independently.</strong> Twenty-five cards means up to twenty-five separate requests per interval cycle. They’re spread out by their different intervals, but a shared, batched refresh could cut traffic. For a personal project it hasn’t mattered.</p><p><strong>Settings reads are repeated.</strong> Several components fetch the same user settings on mount. Caching the settings per request would remove the duplication.</p><h3>What I’d tell you before you build one</h3><ol><li><strong>Use one pattern for every card.</strong> mount, get_data, wire:poll. Consistency lets you add a card in minutes.</li><li><strong>Poll at the speed of the data.</strong> If the backend updates hourly, an hourly poll is correct.</li><li><strong>Authorize inside components.</strong> Anything public is callable.</li><li><strong>Give guests defaults.</strong> A settings service that merges over defaults means no separate logged-out code path.</li><li><strong>Use events and reactive props for coordination</strong>, and give looped components keys.</li><li><strong>Keep public state small</strong>. It travels with every request.</li><li><strong>Put design decisions in tokens.</strong> One card style and a few CSS variables beat 100 hand-styled components.</li><li><strong>Test with realistic data</strong>, not just empty states.</li></ol><p>I expected Livewire to feel like a compromise compared with a JavaScript framework. Instead, it felt like deleting an entire layer of the project. There’s no API contract to keep in sync, no client state to reconcile, and a new card is one file. For a data-heavy dashboard where the interesting work is on the server anyway, that trade has been a very good one.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li><a href="https://medium.coderun.ca/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3">One Dashboard to Rule Them All: What I Built, Why, and How</a></li><li>A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</li><li><a href="https://medium.com/@the-webhamster/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li><a href="https://medium.com/@the-webhamster/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li><a href="https://medium.coderun.ca/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li><li><a href="https://medium.coderun.ca/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333">“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44110eb3eb80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One Dashboard to Rule Them All: What I Built, Why, and How]]></title>
            <link>https://the-webhamster.medium.com/one-dashboard-to-rule-them-all-what-i-built-why-and-how-8a4b0f9314f3?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a4b0f9314f3</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 15:28:17 GMT</pubDate>
            <atom:updated>2026-11-25T14:42:09.268Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A tour of a personal data-aggregation project: what it does, why it exists, and the architecture behind it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZ3XojOQTyBrzF9VTGUZoA.png" /></figure><blockquote>This is the first in a series of articles about the data aggregation project I’ve been building. Most of the work happened over the last year, though the project has gone through several iterations since its birth as a project to kill some time during the early days of the pandemic. This opening piece is an overview of what it ultimately became. Several follow-up articles will take a deeper look at its individual components.</blockquote><p>Every morning I used to open the same handful of tabs: weather, sports scores, the news, what’s launching into space, what’s coming out on TV, new albums, the state of the house thermostat. Each one was a different site with its own layout, ads and login. None of them knew about each other.</p><p>So I built one page that knows about all of them.</p><p>This is a tour of that project: what it is, what it does, why I think it was worth building, and how it’s put together. It’s a personal project, and the lessons are the part I’d like to pass on.</p><h3>What it is</h3><p>It’s a self-hosted personal dashboard. Under the hood it’s a data aggregation platform with a web front end:</p><ul><li>A set of scrapers and API integrations run on a schedule and pull in data from more than twenty external sources.</li><li>The results are stored in my own database, normalized into a consistent shape.</li><li>A web dashboard renders it all on a single page.</li><li>A JSON API exposes the same data to other programs.</li><li>A set of scheduled text-message briefings push the most useful bits to my phone.</li></ul><p>The categories of data it collects include: News from many outlets across many sections, plus a “trending topics” computation, Sports Scores for a few leagues, filtered to the teams I follow, Weather for cities I track, TV schedules, movie releases, new albums, now-playing data from several radio sources and streaming services, spaceflight launch schedules, thermostat and sensor readings for my home, articles and posts from selected publications and communities, comics, quotes, recipes, flights overhead, “this day in history”</p><h3>Why it exists</h3><p>I’ll be honest: there are three reasons, and only one of them is “it’s useful”.</p><p><strong>1. It’s useful</strong>. One page replaces a dozen tabs. A glance at it tells me what the day looks like, and the text-message briefings tell me without my having to look. The rule for those is simple: <em>no episodes today? No message.</em> A briefing that only fires when there’s something to say is one you keep reading.</p><p><strong>2. I want to own my data.</strong> When the data lives in my database, I can query it, combine it, keep history, and build on it, which a third-party widget never lets me do. A weather widget shows today’s forecast. My own table lets me ask how the forecast compared to what happened. Having it all in one place is also what made the later AI-agent integration (more on that below) trivial.</p><p><strong>3. It’s a playground.</strong> A project with twenty-odd integrations is a wonderful excuse to practice real-world engineering problems that tutorials skip: flaky upstreams, scheduling, caching, monitoring, testing code that talks to the outside world, and evolving a schema and its data over a year. Every article I have planned about it comes from something that broke.</p><h3>How it’s built</h3><p>It’s a conventional modern PHP stack, on purpose:</p><ul><li><strong>Laravel</strong> for the framework, with scheduling, queues, authentication and the ORM.</li><li><strong>Livewire</strong> and <strong>Blade</strong> for the interface, with a component library built on <strong>Tailwind</strong> and <strong>DaisyUI</strong>. I get a reactive UI without writing a separate JavaScript application.</li><li><strong>Vite</strong> for assets.</li><li>A relational database for everything.</li></ul><p>I chose boring technology deliberately. A project that has to survive a year of me ignoring it should not depend on anything exotic.</p><h3>A strict layering</h3><p>The code is split into layers, and I try hard to keep each one honest:</p><ul><li><strong>Controllers are thin</strong>. They validate input, call exactly one service, and return a response.</li><li><strong>Services hold all the business logic</strong>, grouped by domain (core, financial, scrapers, music, messaging and so on).</li><li><strong>Models are Eloquent models</strong>, organized into namespaces by domain.</li><li><strong>Resources transform models</strong> into API responses, one per model or collection.</li><li><strong>Traits carry cross-cutting behaviour</strong>: a standard response envelope, an HTTP wrapper used by every scraper, audit logging, pagination helpers.</li></ul><p>The payoff is that every new surface is a thin layer over the same services. The dashboard, the JSON API and the text-message briefings all ask the same service the same question. When I fixed a bug in how sports data is computed, all three were fixed at once.</p><h3>Scrapers as a pipeline</h3><p>Each source follows the same recipe:</p><ol><li>A scraper service fetches and normalizes data from one source.</li><li>A small cron class calls the right scrapers at the right frequency.</li><li>The cron is registered with the scheduler and wrapped in monitoring.</li></ol><p>Adding a new source is a repeatable, mechanical act: write the service, write the cron, register it. That repeatability is the reason a project this size stays manageable.</p><h3>The API</h3><p>Every JSON endpoint returns the same envelope: a status code, the app name and version, a result count and the data. Status codes are named constants, not magic numbers. It sounds like overkill for a personal project, but it means any client I write later, whether it’s a script, a widget or an agent, handles every endpoint the same way. Access is controlled with API keys, with finer-grained permissions on sensitive areas, and a few deliberately open, read-only endpoints for public data.</p><h3>Visualizing Data</h3><p>It started as a “how do I?” project to pass the time during the pandemic. I wanted to collect data from a variety of sources, mostly to learn how to tackle different integration problems. That left me with a handful of fragmented applications that all did similar things and data piling up in different databases. That led me to an idea and I began consolidating them into a single one.</p><p>Next, I added an API layer so other apps could consume the data and run their own analysis.</p><p>Then I decided I wanted a dashboard web application, a place to see the current data at a glance and interact with it.</p><p>Six years on, here’s where it ended up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R94fBQeJq0JB2w9GQjbJ2g.png" /><figcaption>My dashboard showing the data I aggregate for my own home city. There are about 15 Canadian cities for whom I aggregate similar data</figcaption></figure><h3>Keeping it alive</h3><p>This is where most of the effort went. Scraping is easy, but staying correct for a year is hard.</p><ul><li><strong>Monitoring.</strong> Every scheduled job reports its outcome. A failure sends me a text, once per outage, and a watchdog catches jobs that stop running altogether.</li><li><strong>Source health.</strong> Individual sources, like a single news feed, track consecutive failures and raise an alarm only when one is persistently dead.</li><li><strong>Resilient jobs.</strong> A job runs all its steps even if one fails, then reports the failures together.</li><li><strong>Image caching.</strong> Remote images are downloaded once, stored locally, and purged when they’re no longer relevant, which makes pages faster and keeps me from hammering other people’s servers.</li><li><strong>Feature flags and settings.</strong> A key/value settings table lets me turn things on and off without a deploy.</li><li><strong>Data upgrades.</strong> One-off backfills and seed data run through a numbered, ordered system separate from schema migrations.</li></ul><h3>Working with AI</h3><p>The project has two relationships with AI tooling, and both have been useful.</p><p><strong>As a collaborator.</strong> I used an AI coding assistant for a lot of the grind: scaffolding the test suite, hunting down edge cases, tracking down bugs. It’s very good at the repetitive, well-defined parts, and it’s the reason a test suite of nearly a thousand tests exists at all. It still needs a human who knows what the system is <em>supposed</em> to do, and guardrails around anything destructive.</p><p><strong>As a consumer.</strong> Because all of the data lives in one place behind a consistent API, I could expose a small, read-only, no-personal-data endpoint for an AI agent. A scheduled routine fetches a daily digest of news and writes me a short briefing. I deliberately kept the expensive, fuzzy part (reading and summarizing) separate from the cheap, deterministic part (deciding what’s worth reading), and only the latter runs on my own infrastructure. I’ll have more on this in a future article.</p><h3>What I’d do differently</h3><ul><li><strong>Monitoring first.</strong> I added it after the pain. It should have come with the second scraper, not the twentieth.</li><li><strong>Tests earlier.</strong> Everything I fixed in the bug sweep was a bug I’d been shipping.</li><li><strong>A more declarative way to define scrapers.</strong> There’s too much boilerplate in each one, and a lot of it could be configuration.</li><li><strong>Safer defaults around automation.</strong> Auto-disabling failing sources seemed sensible and turned out to be a mistake. Surface problems and let a human decide.</li><li><strong>Never run destructive commands from a shell variable.</strong> A subtle shell quirk once pointed a “fresh migration” at the wrong database, and I had to restore from a backup. Check which database a destructive command will hit <em>before</em> you run it, in a separate harmless step.</li></ul><h3>What I’d tell you if you want to build your own</h3><ol><li><strong>Start with one source and one page. </strong>The architecture follows from the second and third source, not the first.</li><li><strong>Normalize at the edge.</strong> Every upstream is weird in its own way. Clean the data when it enters, and the rest of your system gets to be simple.</li><li><strong>Treat operations as a feature.</strong> Monitoring, health tracking, and retries are not “later” work.</li><li><strong>Layer your code so new surfaces are cheap.</strong> The best sign the structure is right is that adding an API endpoint or a text message takes minutes.</li><li><strong>Keep it boring.</strong> Mainstream tools and plain code will still make sense to you in a year.</li><li><strong>Build it for yourself first.</strong> Real daily use is the best bug report there is.</li></ol><p>It started as a way to stop opening so many tabs. A year on, it’s a small, quiet system that collects the things I care about, tells me when something’s wrong, and gives me one place to look. That’s all I wanted from it. As my database grows I’ll be able to do analysis of trends and other interesting types of data analysis.</p><h3>Zooming out: a year of aggregating 20+ data sources</h3><p>The system started a little over a year ago and now has more than 20 scrapers and API integrations: news, sports scores, weather, radio playlists, charts, space launches, movie and album releases, and more. Here’s what I’d tell myself on day one.</p><p><strong>Sources fail constantly, and quietly.</strong> Feeds change format, time out, rate-limit you, or just go away. A scraper that throws an error is the easy case. The hard case is one that “succeeds” and returns nothing. My early versions failed silently, and I only noticed when a dashboard panel looked stale days later. The fix wasn’t better scrapers. It was monitoring: every cron records its outcome and alerts me when it fails or goes overdue, and every individual source tracks its own run of consecutive failures. Build that before you build the twentieth scraper, not after.</p><p><strong>Be careful about disabling things automatically. </strong>My first instinct was to switch off a feed after it failed a few times. That turned out to be too aggressive: a temporary network blip would quietly remove a good source for good. Counting <em>consecutive</em> failures against a threshold, and re-arming on the next success, was a much better answer than a hair-trigger kill switch.</p><p><strong>Isolate failures so one source can’t take down the run.</strong> If step three of a job throws, steps four through ten should still run. Run every step, log each failure, then raise one summary error at the end so monitoring still sees the problem. It’s a small pattern with a big effect on how often “something is broken” turns into “everything is broken”.</p><p><strong>Every upstream has its own idea of “done”.</strong> Sports feeds are my favourite example. Some never mark a game as finished, so the final score never shows. I had to treat a game as final based on other signals. Dates, time zones, encodings, entities, and null fields all behave differently per source. Normalize at the edge and don’t trust any field you didn’t clean yourself.</p><p><strong>Be a good citizen with other people’s bandwidth.</strong> Fetching and caching remote images locally (with short timeouts, a content-type allowlist, and a placeholder on failure) made pages faster and stopped the dashboard from hammering other sites on every load. A purge job then deletes cached files once they’re no longer relevant, such as old articles or movies that have already been released.</p><p><strong>Tests are how you find the bugs you can’t see.</strong> Scrapers are hard to test because they depend on the outside world, so for a long time mine had little coverage. When I finally built out a full suite, with fake HTTP clients, a local fixture server and a real test database, it surfaced dozens of genuine bugs, including a few security issues. Each one got a test written first, skipped, with the correct behaviour spelled out. Then I fixed them in a batch. I’d have saved a lot of grief by starting with that discipline instead of ending with it.</p><p><strong>Version your data changes like your schema.</strong> Seed data, backfills and one-off fixes live in numbered, never-removed upgrade steps, separate from normal migrations. Retired steps stay as no-ops so the numbering never shifts. It’s boring, and it’s why I can rebuild an environment without guessing what state it was in.</p><p><strong>Decide who the consumer is.</strong> Early on this was just an API experiment for me. Then it became a dashboard for me, a set of text-message briefings, and now a feed for an AI agent. Designing each new surface to expose <em>only</em> what it needs (no personal data on the open endpoint, for instance) is much easier when each is a thin layer over the same services, rather than something tangled into the UI.</p><p>The common thread is that aggregation is mostly an operations problem, not a coding problem. Writing a scraper is an afternoon. Knowing it still works six months later, and finding out quickly when it doesn’t, is the real work. The trending-topics heuristic works because I trust the pipeline feeding it, and I trust the pipeline because I can see it.</p><p>Other articles in this series about my personal dashboard project:</p><ol><li>One Dashboard to Rule Them All: What I Built, Why, and How</li><li><a href="https://medium.coderun.ca/a-25-card-dashboard-without-a-javascript-framework-how-i-built-it-with-livewire-44110eb3eb80">A 25-Card Dashboard Without a JavaScript Framework: How I Built It With Livewire</a></li><li><a href="https://medium.com/@the-webhamster/inside-a-news-scraper-fetching-200-rss-feeds-reliably-and-what-you-actually-get-27561f108755">Inside a News Scraper: Fetching 200+ RSS Feeds Reliably, and What You Actually Get</a></li><li><a href="https://medium.com/@the-webhamster/building-a-news-briefing-agent-heuristics-first-llm-second-ad7dc60d0562">Building a News Briefing Agent: Heuristics First, LLM Second</a></li><li><a href="https://medium.coderun.ca/stop-one-broken-feed-from-killing-your-whole-scraper-run-781708eaa75e">Stop One Broken Feed From Killing Your Whole Scraper Run</a></li><li><a href="https://medium.coderun.ca/teaching-a-cron-job-to-curate-music-building-spotify-playlists-from-radio-history-be587a3c68fb">Teaching a Cron Job to Curate Music: Building Spotify Playlists From Radio History</a></li><li><a href="https://medium.coderun.ca/spotify-insights-building-my-own-listening-stats-from-a-two-minute-poll-6d9e899c4333">“Spotify Insights”: Building My Own Listening Stats From a Two-Minute Poll</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a4b0f9314f3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring a fresh MacOS for a developer]]></title>
            <link>https://the-webhamster.medium.com/configuring-a-fresh-macos-for-a-developer-d89214902bb5?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d89214902bb5</guid>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 18:34:27 GMT</pubDate>
            <atom:updated>2025-07-17T18:40:33.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p2GCiNviwX4K5X3IcIatFQ.jpeg" /></figure><p>I got a new MacBook Air M4 for work and needed to configure it to the specifications for the job I do. You probably won’t need everything I have installed, but if you’re looking for what I see as the must-haves for myself feel free to cherry pick from my experiences.</p><p>You can install your own Spotify, IDE’s, and other things. This article is all about what I found are the essentials to be working as a developer in PHP, Python, and AWS.</p><h3>Fix your Terminal</h3><p>Get ITerm2 and OhMyZSH. You won’t regret it.</p><p><a href="https://iterm2.com/downloads.html">Downloads - iTerm2 - macOS Terminal Replacement</a></p><h3>OhMyZSH</h3><p>You’ll want to add this to make your terminal life bearable.</p><pre>sh -c &quot;$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)&quot;          </pre><p>If you edit your .zshrc file here are a few of the aliases I like to add (pop these right at the end of the file):</p><pre># Shortcuts<br>alias ll=&#39;ls -lah&#39;<br>alias lt=&#39;ls -laht&#39;<br>alias reload=&#39;source ~/.zshrc&#39;<br>alias c=&#39;clear&#39;<br>alias h=&#39;history&#39;<br>alias su=&#39;sudo&#39;<br>alias sv=&#39;sudo vi&#39;</pre><p>I also like the ‘gallifrey’ theme for my terminal. Edit this line accordingly (default is ‘robbyrussell’):</p><pre>ZSH_THEME=&quot;gallifrey&quot;</pre><h3>Fix Your Mac</h3><p>I hate the delay for the dock pop-up (the default is 1 second) and it gets me annoyed to wait. Let’s set that to instant. Open your Terminal and paste:</p><pre>defaults write com.apple.Dock autohide-delay -float 0; killall Dock</pre><p>I also hate clutter in my menu bar. I prefer to tuck away things I don’t need to see all the time. To that end “Ice” is the best free menu bar manager I’ve ever used.</p><p><a href="https://github.com/jordanbaird/Ice/releases">Releases · jordanbaird/Ice</a></p><p>Grab the ice.zip file from the latest stable release and install it in your Application folder. Make sure to set it to start at login!</p><h3>Homebrew</h3><p>Install Homebrew. It’s VERY important.</p><pre>/bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p><strong>Node and NPM</strong></p><p>I will need node and npm so I’ll install those with Homebrew. They both get installed via the install for node.</p><pre>brew update<br>brew install node</pre><p>Check the versions to make sure they got installed properly. Versions will vary depending on when you’re reading this.</p><pre>➜  ~ node --version<br>v24.3.0<br>➜  ~ npm -v<br>11.4.2</pre><h4>Install with Brew</h4><pre>brew install wget</pre><h4>MariaDB</h4><p>Install a local MariaDB database</p><pre>brew install mariadb<br>brew services start mariadb</pre><p>The default install will throw password errors at you when you try to run the mariadb_secure_installation script. Change your password first:</p><pre>sudo mysql -u root<br>MariaDB [(none)]&gt; set password for &#39;root&#39;@&#39;localhost&#39; = password(&#39;YOURNEWPASSWORD&#39;);<br>exit</pre><p>Now you should be able to run “mariadb_secure_installation” in the terminal and get yourself all set up.</p><h4><strong>PHP</strong></h4><p>First add the Homebrew taps for PHP:</p><pre>brew tap shivammathur/php<br>brew tap shivammathur/extensions</pre><p>Next, install the PHP versions you want to use (For this install I add several versions for legacy project reasons) but you may just want whatever version is the latest when you’re doing it:</p><pre>brew install shivammathur/php/php@8.1<br>brew install shivammathur/php/php@8.2<br>brew install shivammathur/php/php@8.3<br>brew install shivammathur/php/php@8.4<br><br>brew services start php@8.1<br>brew services start php@8.2<br>brew services start php@8.3<br>brew services start php@8.4</pre><p>Now let’s tweak our PHP configs to make them a little more robust than the defaults allow. You’ll find your php.ini file in the following path: /opt/homebrew/etc/php/<em>VERSION</em>. For the sake of brevity we’ll just do one in this example but if you installed multiple PHP versions, as I did, you’ll just have to roll through each on of them in turn.</p><pre>cd /opt/homebrew/etc/php/8.2<br><br>sudo vi php.ini    </pre><p>OK, now for the lines to change:</p><pre>upload_max_filesize = 50M <br>post_max_size = 50M <br>memory_limit = 512M <br>max_execution_time = 600 <br>max_input_vars = 3000 <br>max_input_time = 1000</pre><p>Search for each of those and change the corresponding value accordingly. Then restart that version of PHP.</p><pre>brew services restart php@8.2</pre><p>Just rinse-and-repeat for any other PHP versions you installed.</p><h4>Composer</h4><p>We’ll need to install Composer to move forward, so let’s do that now with Homebrew:</p><pre>brew install composer    </pre><p>Now make sure Composer is in your $PATH:</p><pre>export PATH=&quot;$PATH:$HOME/.composer/vendor/bin&quot;</pre><p>That’s it! At the terminal prompt type “composer” and you should see the man page:</p><pre>   ______<br>  / ____/___  ____ ___  ____  ____  ________  _____<br> / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/<br>/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /<br>\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/<br>                    /_/<br>Composer version 2.8.9 2025-05-13 14:01:37</pre><p>You’re good to go!</p><h4><strong>Laravel Valet</strong></h4><p>I do all my local development and hosting on Laravel Valet. Let’s get that installed. Run these three commands sequentially:</p><pre>composer global require laravel/valet<br>valet install<br>sudo valet trust</pre><p>To configure and use your Valet please read the article I wrote on it a few years back.</p><p><a href="https://medium.coderun.ca/running-multiple-php-development-sites-using-laravel-valet-on-macos-59d6f8ff4c5e">Running multiple PHP development sites using Laravel Valet on MacOS</a></p><h4>PHPMonitor</h4><p>I’ve found PHP Monitor to be a very useful tool to have install, so let’s install it with Homebrew:</p><pre>brew tap nicoverbruggen/homebrew-cask<br>brew install --cask phpmon</pre><p>You can then open the app in your Applications folder. It tucks neatly in your menu bar. Go to the app settings and set it to start on login.</p><h4>REDIS</h4><p>Alot of the stuff I develop leverages a REDIS cache in production so I also install that on my system so I can use it during development.</p><pre>brew install redis<br>brew services start redis  </pre><p>I also want to install the PHP Redis extension. We already added the shivamathur/extensions tap earlier so let’s install redis for each PHP version.</p><pre>brew install redis@8.1<br>brew install redis@8.2<br>brew install redis@8.3<br>brew install redis@8.4</pre><h4>Python 3.9</h4><p>My development work needs to be locked to Python 3.9 so that’s the version I’m going to install with Homebrew:</p><pre>brew install python@3.9</pre><p>You can validate it with the python3.9 — version command:</p><pre>python3.9 --version<br>Python 3.9.23</pre><p>But I’d rather alias that as “python” instead of “python3.9”. Let’s open our .zshrc file again and go down to our aliases where we’ll add:</p><pre>alias python=&#39;python3.9&#39;</pre><p>Once saved, run your handy ‘reload’ alias and you should be able to do this:</p><pre>python --version<br>Python 3.9.23</pre><h4>AWS Support</h4><p>If you work with AWS, as I do, you will need AWS command line support:</p><pre>curl &quot;https://awscli.amazonaws.com/AWSCLIV2.pkg&quot; -o &quot;AWSCLIV2.pkg&quot;<br>sudo installer -pkg ./AWSCLIV2.pkg -target /</pre><p>Now configure AWS:</p><pre>aws configure</pre><p>That will bring up the configure interface. Fill in the blanks:</p><pre>AWS Access Key ID [None]: YOUSHOULDHAVETHISSAVEDSOMEWHERE<br>AWS Secret Access Key [None]: YOUSHOULDHAVETHISSAVEDSOMEWHERE<br>Default region name [None]: YOURREGION<br>Default output format [None]:</pre><p>Now you should be good to go. I will add to this doc as I find things I may have missed and will welcome your comments. I hope it helped you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d89214902bb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running multiple PHP development sites using Laravel Valet on MacOS]]></title>
            <link>https://the-webhamster.medium.com/running-multiple-php-development-sites-using-laravel-valet-on-macos-59d6f8ff4c5e?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/59d6f8ff4c5e</guid>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Fri, 02 Dec 2022 20:12:29 GMT</pubDate>
            <atom:updated>2022-12-02T20:12:29.846Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qKkV8_Zph1TlMa7_Gdq8eQ.png" /></figure><p>It’s nice to think that all your PHP projects will always be using the same version of PHP and that it’ll always work fine on the latest and greatest version. As developers we know that just isn’t the truth. In my case I’ve been building REST API’s that are up to date with PHP 8.1 but also have legacy projects that still need to be maintained that are presently locked to PHP 7.3. This happens all the time. Sometimes it’s a lack of time. Sometimes it’s a project that is close to EOL so there’s no point — you just need to keep the lights on for a few more months. Or, sometimes you just can’t get buy in on a refactoring project from your bosses.</p><p>In the past I handled this with an Ubuntu VM running multiple versions of PHP and linking the project being served in the NGINX conf file. That led to this article from last year: <a href="https://medium.coderun.ca/running-multiple-versions-of-php-on-ubuntu-server-with-nginx-481f07cfe5a4">Running Multiple Versions of PHP on Ubuntu Server with NGINX</a>. But it’s complicated, there’s maintenance, overhead, extra steps, and dealing with Samba and Linux permissions that slow down your development process, especially on Windows. It was chaotic. It seemed like I was spending more time maintaining an environment and fixing environment issues than developing.</p><p>I do all my development now on a MacBook Pro. When I first got it I started down the path of installing multiple PHP versions, NGINX, and all the stuff I would do on the VM to build a local development environment. But it was still adding overhead to my days. Then I just sort of stopped because I came across a marvel that is <strong>Laravel Valet</strong>. It runs NGINX, takes care of automatically serving your project from a <strong>&lt;folder&gt;.test</strong> local domain with DNSmasq as long as it’s in a directory that your tell Valet to monitor for new folders.</p><p>This was fantastic <em>except</em> that until version 3.0, Valet didn’t support multiple versions of PHP. You could have them installed but you’d need to change the version Valet used globally to use a legacy project:</p><pre>&gt; valet use php@8.1 -- force</pre><p>This posed a huge problem for me because a legacy project tied to PHP 7.3 wants to make a call to a REST API running on PHP 8.1 so I couldn’t do a full up test of the entire system before issuing a pull request. It was, honestly, a huge pain. But then I discovered that version 3.0 of Valet introduced support to run different versions on PHP on a per project basis. Cue: <em>angels singing</em>.</p><p>First, install Homebrew if you haven’t already:</p><pre>&gt; /bin/bash -c &quot;$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)&quot;</pre><p>I also install all my local PHP versions through the Homebrew tap: “shivammathur/php”. Set that up if you don’t already have it in use.</p><pre>&gt; brew tap shivammathur/php</pre><p>Now we should install the latest PHP. As of this writing that is 8.1.13:</p><pre>&gt; brew install shivammathur/php/php@8.1</pre><p>In order to install Valet we’ll need Composer first so…</p><pre>&gt; php -r &quot;copy(&#39;https://getcomposer.org/installer&#39;, &#39;composer-setup.php&#39;);&quot;<br>&gt; php -r &quot;if (hash_file(&#39;sha384&#39;, &#39;composer-setup.php&#39;) === &#39;756890a4488ce9024fc62c56153228907f1545c228516cbf63f885e036d37e9a59d27d63f46af1d4d07ee0f76181c7d3&#39;) { echo &#39;Installer verified&#39;; } else { echo &#39;Installer corrupt&#39;; unlink(&#39;composer-setup.php&#39;); } echo PHP_EOL;&quot;<br>&gt; php composer-setup.php<br>&gt; php -r &quot;unlink(&#39;composer-setup.php&#39;);&quot;<br>&gt; mv composer.phar /usr/local/bin/composer<br>&gt; composer<br><br>   ______<br>  / ____/___  ____ ___  ____  ____  ________  _____<br> / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/<br>/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /<br>\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/<br>                    /_/<br>Composer version 2.4.4 2022-10-27 14:39:29</pre><p>Now we can finally install Valet.</p><pre>composer global require laravel/valet:^3.0<br>valet install</pre><p>Valet 3.0 should now be up and running. Let’s check:</p><pre>valet -V<br>Laravel Valet 3.1.13</pre><p>Now you need to tell it where you want to do your local development from. I do it all in my /Users/webhamster/Development/PHP directory. A simple command will tell Valet to monitor this directory and create NGINX entries. That command is “park”.</p><pre>&gt; cd /Users/webhamster/Development/PHP<br>&gt; PHP ll<br>total 0<br>drwxrwxrwx  29 webhamster  staff   928B 18 Nov  2021 coderun<br>drwxrwxrwx  30 webhamster  staff   960B 23 Nov 11:24 laravel_website<br>drwxr-xr-x   8 webhamster  staff   256B  1 Dec 11:51 legacy_project<br>drwxrwxrwx  30 webhamster  staff   960B 23 Nov 11:25 my-cool-api<br>&gt; valet park</pre><p>So now any folder in here will be accessible locally as &lt;folder&gt;.test as in <strong>http://my-cool-api.test</strong>. By default Valet will use the version of PHP you have defined as the system default. Right now, for me that is PHP 8.1. But you notice that folder in there called “legacy_project”?</p><p>Right now if I try to go to <strong>http://legacy_project.test</strong> it fails all over the place because it’s trying to serve it with PHP 8.1. Yeah, I need that to run on PHP 7.3. So let’s use Homebrew to install PHP 7.3 alongside the current PHP 8.1.</p><pre>&gt; brew install shivammathur/php/php@7.3</pre><p>Next, you can configure the php.ini for your new version. You find the php.ini file in /usr/local/etc/php/&lt;version&gt;. These are the standard settings I change in all my php.ini files:</p><pre>upload_max_filesize = 50M<br>post_max_size = 50M<br>memory_limit = 512M<br>max_execution_time = 600<br>max_input_vars = 3000<br>max_input_time = 1000</pre><p>Now restart the PHP you just configured:</p><pre>&gt; brew services restart php@7.3</pre><p>OK, now we need to tell Valet to serve “legacy-project.test” with PHP 7.3.</p><pre>&gt; cd /Users/webhamster/Development/PHP/legacy_project<br>&gt; valet isolate php@7.3</pre><p>Now if you navigate to <strong>http://legacy_project.test</strong> it should be working just fine being served as PHP 7.3. In addition all your other PHP 8.1 projects should still be working and be served with PHP 8.1. You’re all set. You can install whichever other versions of PHP you may need and follow these same steps to use them.</p><p>If you ever want to check and see which projects you have isolated to separate PHP versions use the “valet isolated” command:</p><pre>&gt; valet isolated<br>+---------------------+-------------+<br>| Path                | PHP Version |<br>+---------------------+-------------+<br>| legacy_project.test | php@7.3     |<br>+---------------------+-------------+</pre><p>I hope this article helped you out. See below for some bonus information.</p><h3><strong>Using Valet to serve secure sites locally</strong></h3><p>By default Valet uses HTTP to serve pages. Locally this is fine, but sometimes you may want to test a site with HTTPS locally. Valet can do this.</p><pre>&gt; valet secure legacy_project<br>Restarting nginx...<br>The [legacy_project.test] site has been secured with a fresh TLS certificate.</pre><p>You will be prompted to allow Valet to make certificate changes to your Mac. But, afterwards you can navigate to <strong>https://legacy-project.test</strong> and it’ll work. Similarly, <strong>http://legacy-project.test</strong> will automatically re-direct you to the HTTPS site. You can undo this with:</p><pre>&gt; valet unsecure legacy_project<br>Restarting nginx...<br>The [legacy_project.test] site will now serve traffic over HTTP.</pre><h3><strong>Installing PHPMonitor</strong></h3><p>I also highly recommend installing PHPMonitor to see what’s happening with PHP on your system. I have it start on login and it sits in my menubar for easy access:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*5KJWjGimX0hYk2RiYsTOJA.png" /></figure><p>To install PHPMonitor just do it via Homebrew.</p><pre>&gt; brew install phpmon</pre><p>And that’s all there is. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59d6f8ff4c5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How-To: AWS Lambda (Python) API Resolvers for AWS AppSync, Amplify, and Angular]]></title>
            <link>https://awstip.com/how-to-aws-lambda-python-api-resolvers-for-aws-appsync-amplify-and-angular-a4c53082b4e3?source=rss-8fd6f38c47bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4c53082b4e3</guid>
            <category><![CDATA[aws-amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws-appsync]]></category>
            <dc:creator><![CDATA[Shawn Nystrand]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 20:52:17 GMT</pubDate>
            <atom:updated>2024-05-10T13:24:38.884Z</atom:updated>
            <content:encoded><![CDATA[<p>The problem: We were developing an Angular application on AWS Amplify that required us to be able to access several external API’s. Yes, you can do this via Angular BUT since Angular is all client-side when you need to use an API Key or another authentication method all your secrets can be accessed by someone looking at your source code. This did not fly with us.</p><p>Back in October 2021 I wrote this article: <a href="https://medium.coderun.ca/accessing-an-external-api-via-aws-appsync-cdb62df0735e">“Accessing an external API via AWS AppSync”</a> with my first run at figuring this out. However, it is a very manual process that doesn’t work for automated Amplify deployments to different development and/or production environments. We needed a method that could deploy this automatically via <em>amplify push</em> and then just have it work. It took several months of ongoing research and many failures but we ultimately hit upon the solution that worked.</p><p>This solution will require an AWS Lambda function (we used Python and I will be showing Python in this article, but you can use Node if you want — you’ll just have to figure that part out for yourself ;), SSM access, and AppSync. I’m going to skip over the basics of AWS Amplify, you can learn those with other tutorials. If you’re here, I’m assuming you’ve at least kicked the tires on Amplify.</p><p>So let’s start with the secret sauce for adding a Lambda function via Amplify. Go to your terminal (in the root of your project source directory) and type:</p><pre>amplify add function</pre><p>What, you thought this would be hard? OK, well, there’s more… You will need to follow the prompts that the Amplify console asks you, here’s how you should answer the questions it poses:</p><pre>? Select which capability you want to add: <strong>Lambda function (serverless function)</strong><br>? Provide an AWS Lambda function name: <strong>mycoolapi</strong><br>? Choose the runtime that you want to use: <strong>Python<br></strong>? Do you want to configure advanced settings? <strong>Yes</strong><br>? Do you want to access other resources in this project from your Lambda function? <strong>No</strong><br>? Do you want to invoke this function on a recurring schedule? <strong>No</strong><br>? Do you want to enable Lambda layers for this function? <strong>No</strong><br>? Do you want to configure environment variables for this function? <strong>Yes</strong></pre><p>Answering “Yes” to the last question will create variables in AWS Systems Manager (SSM) that you will be able to see in the Parameter Store. You will be forced to create one unencrypted variable (for some reason) and then will be able to optionally create a secure variable (great for an API Key). These will be tied to your environment. If you need them to be available across environments you will need to look into creating a variable in Parameter Store with the proper permissions to be viewed across your AWS account.</p><pre>? Enter the environment variable name: <strong>ENVVAR1</strong><br>? Enter the environment variable value: <strong>hello</strong><br>? Select what you want to do with environment variables: <strong>I&#39;m done</strong></pre><pre>You can access the following resource attributes as environment variables from your Lambda function<br>        ENV<br>        REGION<br>        ENVVAR1<br>? Do you want to configure secret values this function can access? <strong>Yes</strong><br>? Enter a secret name (this is the key used to look up the secret value): <strong>MY_COOL_API_KEY</strong><br>? Enter the value for MY_COOL_API_KEY: <strong>[hidden]</strong><br>? What do you want to do? I&#39;m done<br>Use the AWS SSM GetParameter API to retrieve secrets in your Lambda function.<br>More information can be found here: <a href="https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html">https://docs.aws.amazon.com/systems-manager/latest/APIReference/API_GetParameter.html</a><br>? Do you want to edit the local lambda function now? <strong>No</strong><br>Successfully added resource <strong>mycoolapi</strong> locally.</pre><p>Next, you’ll need to go to AWS Systems Manager and into the Parameter Store. In there you’ll find the secret key you created with your API Key (if you did that). It’ll look something like this:</p><pre>/amplify/AWS_HASH_KEY/YOUR_AMPLIFY_ENVIRONEMT/AMPLIFY_mycoolapi_MY_COOL_API_KEY</pre><p>There is an AWS hash key and the name of your current Amplify environment in there in my anonymized string. Now, let’s get our parameter into our Python script as a variable (I’m calling mine x_api_key to match the header I have to send to my API).</p><h3><strong>Let’s build some Python!</strong></h3><p>In your amplify/backend/function directory you should have a directory called ‘mycoolapi’ (or whatever name you used). You’ll want to open the index.py file in the src directory now. It’s just a boilerplate Python file right now so let’s clear out what’s there and start with a blank file.</p><p>First, we need to bring in some libraries and configure a few things so we can get our SSM secret values. Feel free to skip the SSM part if you don’t need an API Key or other secret values to be retrieved from SSM.</p><pre><strong>import </strong>json<br><strong>import </strong>os<br><strong>import </strong>urllib<br><strong>from </strong>urllib <strong>import </strong>request, parse<br><strong>import </strong>boto3<br><strong>from </strong>botocore.config <strong>import </strong>Config<br><br><em># Initialize SSM Client<br></em>region_name <strong>= </strong>os.getenv(<strong>&quot;AWS_REGION&quot;</strong>, <strong>&quot;your_region_here&quot;</strong>)<br>config <strong>= </strong>Config(<br>   retries <strong>= </strong>{<br>      <strong>&#39;max_attempts&#39;</strong>: <strong><em>10</em></strong>,<br>      <strong>&#39;mode&#39;</strong>: <strong>&#39;standard&#39;<br>   </strong>},<br>   region_name <strong>= </strong>region_name<br>)<br>ssm_client <strong>= </strong>boto3.client(<strong>&#39;ssm&#39;</strong>, config <strong>= </strong>config)</pre><pre><em># Get the API Key from SSM<br></em>ssm_name <strong>= </strong>os.getenv(<strong>&#39;SSM_KEY_NAME&#39;</strong>, <strong>&#39;/amplify/AWS_HASH_KEY/YOUR_AMPLIFY_ENVIRONEMT/AMPLIFY_mycoolapi_MY_COOL_API_KEY&#39;</strong>)<br>x_api_key <strong>= </strong>ssm_client.get_parameter(Name<strong>=</strong>ssm_name, WithDecryption<strong>=</strong><em>True</em>)[&#39;Parameter&#39;][&#39;Value&#39;]</pre><p>Now x_api_key as a variable with the value from SSM will be available to use in our Python script. Let’s build the handler method. To clarify, the method <strong>must</strong> be called “handler” and it <strong>must</strong> accept “event” and “context” as the variables.</p><pre># Start handler<br>def handler(event, context):</pre><pre>  <em># Build the Request Opener<br>  </em>opener <strong>= </strong>request.build_opener()<br>  opener.addheaders <strong>= </strong>[<br>    (&#39;x-api-key&#39;, x_api_key),<br>    (&#39;content-type&#39;, &#39;application/json&#39;)<br>  ]<br>  request.install_opener(opener)</pre><pre><em>  # Setup the request object</em><br>  req <strong>= </strong>request.Request(&quot;<a href="https://mycoolapi.test/route_params">https://mycoolapi.test/route_params</a>&quot;)</pre><pre><em>  # Make the call<br>  </em>response <strong>= </strong>request.urlopen(req)</pre><pre>  # Convert the response from a string to a JSON object<br>  data = json.loads(response.read().decode(&#39;utf-8&#39;))</pre><pre>  # Do any data manipulations here<br>  # ...<br>  # End data manipulations</pre><pre>  # Convert data (JSON object) to a string<br>  json_string = json.dumps(data[&#39;data&#39;])<br>  # Build the JSON result object to return<br>  result_obj = {<br>    &#39;statusCode&#39;: response.status,<br>    &#39;body&#39;: json_string<br>  }<br>  # Convert the result object to a string<br>  result_obj_string = json.dumps(result_obj)<br>  # Return the result<br>  return result_obj_string</pre><p>So let’s walk through what’s happening here. First we’re setting the API url as a variable here. This is clearly a fake URL, you will replace that with your real API url, obviously. Then we’re using the <em>urllib</em> library to make the call. This is because the Python 3.8 version currently used for Lambda functions in AWS does not have the standard <em>requests</em> library available to us so we need to use an alternative. It also means some other work massaging the content.</p><p>You can see in <em>opener.addheaders</em> is where we’re including the x_api_key variable we pulled from SSM earlier. Then, once we get the result we’re reading and decoding the response and using <em>json.loads()</em> to load the string as a JSON object.</p><p>I’ll just call your attention to this line. briefly:</p><pre>json_string = json.dumps(data[&#39;data&#39;])</pre><p>In the case of the API I’m working with I know the data I want is in the ‘data’ key of the return from it. Yours may be different, as will other API’s you use. Don’t get stuck here staring at this, it will be different for different API’s.</p><p>After this point I’ve left space to do any additional data manipulation you might have to do before returning this to AppSync. In our case we have none.</p><p>Finally we return the result. You could do this in one method if you want but I find the multiline approach is much better for keeping your code clear and straight. First we convert our JSON object (that may have been manipulated and parsed) back to a string using <em>json.dumps()</em>. Then we build the JSON object we want to return to AppSync and include our data in the ‘body’ value. Then we dump that to a string with <em>json.dumps()</em> again and, finally, return the <em>result_obj_string</em> variable.</p><p>You can play around with the Python, and I recommend that you do. This is a very basic example that doesn’t validate anything and basically assumes success. You’ll probably want to tighten that up.</p><h3><strong>Hooking it together!</strong></h3><p>Next step is to link this Lambda function to your GraphQL in AppSync. In your /amplify/backend/api directory open your schema.graphql file. You will need to add the resolver here, like this:</p><pre>type<strong> </strong>Query {<br>  mycoolapi(mode: String, value: String): String @function(name: <strong>&quot;</strong>mycoolapi-${env}<strong>&quot;</strong>)<br>}</pre><p>You’ll notice I’m passing “mode” and “value” as parameters on the query. We’ll cover those in a second. Save that file and save your index.py file. Now do an <em>amplify push</em> to create everything in the cloud. Once that’s done, head over to AppSync and you should see “mycoolapi” in your query list. Now you can run it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByWPRwJPBXHmVJrEIMLD1w.png" /><figcaption>The query in the query list and being run in AppSync</figcaption></figure><p>As you can see here, “mode” and “value” are variables we can pass to the Lambda function as arguments. In this example, I’m using “mode” to switch between which endpoint to call. And while not in the example, value is a placeholder for any string value I want to pass to another query. Here’s a super basic if/else structure in the Python handler that will accept the passed variable and switch the url variable for you. Use it where we built the request object in the previous Python script example.</p><pre># Switch URL based on mode argument passed from AppSync<br>  if event[&#39;arguments&#39;][&#39;mode&#39;] == &#39;recent_news&#39;:<br>    url = &quot;<a href="https://mycoolapi.test/news/recent">https://mycoolapi.test/news/recent</a>&quot;<br>    req <strong>= </strong>request.Request(url)<br>  elif event[&#39;arguments&#39;][&#39;mode&#39;] == &#39;recent_by_date&#39;:<br>    date = event[&#39;arguments&#39;][&#39;value&#39;]<br>    url = &#39;<a href="https://mycoolapi.test/news/date?date=&#39;">https://mycoolapi.test/news/date?date=&#39;</a> + date<br>    req <strong>= </strong>request.Request(url)<br>  else:<br>   url = &quot;<a href="https://mycoolapi.test/healthcheck">https://mycoolapi.test/healthcheck</a>&quot;<br>   req <strong>= </strong>request.Request(url)</pre><p>So, we can access the passed “mode” variable from the event object, and the same with the “value” variable. Feel free to play around with this concept.</p><p>Your next question is likely, but can I do a POST request this way? Well, yes, yes you can. Here’s a sample elif block (formatted to fit in our if/else logic right above) in our Python script that will do a post:</p><pre>elif event[&#39;arguments&#39;][&#39;mode&#39;] == &#39;fake_post&#39;:<br>  url = &quot;http://mycoolapi.test/development/fake_post&quot;<br>  myvars = {<br>      &#39;value&#39;: event[&#39;arguments&#39;][&#39;value&#39;],<br>      &#39;mode&#39;: event[&#39;arguments&#39;][&#39;mode&#39;]<br>    }<br>  encoded_vars = parse.urlencode(myvars).encode()<br>  req = request.Request(url, data=encoded_vars)</pre><p>We create a JSON object of the variables we passed from AppSync (I’m just using the ones we already have created for this example), then we encode them with <em>urlencode()</em>. The fact that we include them in the <em>request.Request</em> object as the second parameter automatically turns this from a GET to a POST.</p><h3><strong>The Final Step — Front End!</strong></h3><p>Now that we have all this working we will want to display it in the front end of our application. In my case, in Amplify, I’m working with an Angular application. If you’re working in React or some other front-end language you’ll need to figure that out on your own. My example is just Angular.</p><p>I created a new Angular component called “api-test” and set up the component.ts file like so:</p><pre>import {ChangeDetectorRef, Component} from &#39;<a href="http://twitter.com/angular/core">@angular/core</a>&#39;;<br>import {APIService} from &quot;../API.service&quot;;</pre><pre><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-api-test&#39;,<br>  templateUrl: &#39;./api-test.component.html&#39;,<br>  styleUrls: [&#39;./api-test.component.css&#39;]<br>})<br>export class ApiTestComponent  {<br>  public data : any;</pre><pre>constructor(private api:APIService, private ref: ChangeDetectorRef) {<br>    this.api.Mycoolapi(&#39;recent_news&#39;).then((response) =&gt; {<br>      //@ts-ignore<br>      let response_json:Object = JSON.parse(response);<br>      //@ts-ignore<br>      this.data = JSON.parse(response_json[&#39;body&#39;])<br>      this.ref.detectChanges();<br>    })<br>  }<br>}</pre><p>All the standard disclaimers about this just being a simple example apply. You probably don’t want to actually do this in a component constructor, you’ll probably want to build a service that a component function can call but this is just a quick and dirty example to show it working. OK, so we use the APIService that Amplify makes for us, we pass the “mode” variable to it and then do a couple of <em>JSON.parse()</em> passes to get everything into a JSON object and make it available to our HTML class. In our HTML class we have something like this:</p><pre>&lt;div <em>*ngFor</em>=&quot;let <em>news </em>of data&quot;&gt;<br>  &lt;div class=&quot;newslink&quot;&gt;<br>  &lt;a href=&quot;{{news.link}}&quot; target=&quot;_blank&quot;&gt;{{news.title}}&lt;/a&gt; ({{news.organization}})<br>  &lt;/div&gt;<br>  &lt;div class=&quot;articletext&quot;&gt;<br>  {{news.description}}<br>    &lt;/div&gt;<br>  &lt;p&gt;<br>&lt;/div&gt;</pre><p>And the end result in our Angular application?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgUXvIOoqZ7ACi9Ts36R1A.png" /></figure><h3><strong>BONUS: Making your SSM Parameter available across environments</strong></h3><p>This is down here because it may not be something everybody needs but you can make your SSM secret parameter available across Amplify environments (or create a new secure string in SSM Parameter Store to make available across environments). Why? If you’re working on a team (as we are) and every developer has their own environment you might not want to make them create their own copies of an API Key value in SSM, for example.</p><p>So, go to Parameter Store and create a new secure string, give it a name you can use to identify it properly (I’ll call this one “MYCOOLAPI_API_KEY”) and set the API Key (or other secret value) in there. Now, copy the name of your parameter and go to your custom_policies.json file in your amplify/backend/function/mycoolapi directory and change the boilerplate file to look like this:</p><pre>[<br>  {<br>    <strong>&quot;Action&quot;</strong>: [<br>      <strong>&quot;ssm:GetParameter&quot;</strong>,<br>      <strong>&quot;ssm:GetParameters&quot;<br>    </strong>],<br>    <strong>&quot;Resource&quot;</strong>: [<strong>&quot;arn:aws:ssm:AWS_REGION:AWS_ACCOUNT_ID:parameter/MYCOOLAPI_API_KEY&quot;</strong>],<br>    <strong>&quot;Effect&quot;</strong>: <strong>&quot;Allow&quot;<br>  </strong>}<br>]</pre><p>In your Python file change the long amplify created secret ssm name to the one your created (i.e. “MYCOOLAPI_API_KEY”). So on your next <em>amplify push</em>, the Lambda function that gets created will get the ability to read that SSM parameter you just created. As will any other copy of the Lambda created in an other Amplify environment.</p><h3><strong>Thanks for reading!</strong></h3><p>I really hope this has helped you to get a secured API connection into your Amplify Angular project. It took us quite a bit of work to figure out how to do this but we found a way that works in the end.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4c53082b4e3" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/how-to-aws-lambda-python-api-resolvers-for-aws-appsync-amplify-and-angular-a4c53082b4e3">How-To: AWS Lambda (Python) API Resolvers for AWS AppSync, Amplify, and Angular</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>