CORS is dumb. CORS is here to stay. CORS has a bit of usefulness. As my daughter opined recently, cry me a river, build a bridge, and get over it.

After spending days on it, I now have a five minute fix for CORS in a dev environment where the frontend is split from the backend during development.

GIVEN:

  • a server that serves up your RESTful API using backend data
  • that same server, serving up your nicely bundled front end, after you bake it for prod
  • https in prod, and http in dev
  • a modern front end development environment that maximizes your local web development speed while also bundling it tight for prod ( 💕 Vite 💕 )

You may have been sailing along with that sweet setup for a while now. But then one day, CORS arrives in your neighborhood. Perhaps you realize your Node front end can now use native fetch(), how nice (at first). Or your browser just got updated and all of a sudden it’s very unhappy serving your JWT tokens. Any way you get there, you will probably hit CORS issues. They tell you you are a bad person for trying to reach your backend from your frontend. Bad dev!

The problem is that is actually now blocked as a cross-site request. This blockage is now ubiquitous. How else can you still get to your favorite awful monster sites if they are sideloading dozens of malware ads? Why should megasite be responsible for the ads they serve? Let the browser block them! We need to protect the sheeple!! But i digress…

To fix your CORS issues, quickly, you simply add proxying to your Vite environment. The proxy takes all your backend calls, sends them off, and when they return, gently stuffs all the weird painful CORS headers you need in the response to keep your frontend from having a seizure.

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    // For back end calls, make sure to use the API prefix.
    // Our vite dev environment will proxy those calls to the back end,
    // and return them to us, with fetch's xss concerns disabled via CORS:
    //    front -> proxy -> back -> proxy -> (ADD CORS) -> front
    proxy: {
      '/api': {
        'target': 'http://backend:8080',
        changeOrigin: true,
      },
    },
    port: 8008,
  },
})

Beautiful. In addition to that, if you can just slightly touch your server side cookie header to make it fit the CORS rulebook, you can get all that cross-site protection in prod, and never deal with a CORS issue in local dev again:

if (dev_environment) {
    cookie_header += " SameSite=Lax;";
  } else {
    cookie_header += " Secure; SameSite=Strict;";
  }

The internet has officially crossed over from a source of generally good information to a floating island landfill of outdated plastic shrapnel.

Just trying to find “today’s” best-practice for simply fetching data in a React app turns into an exhausting ritual of filtering for hours. Thank goodness for subreddit and stack overflow ratings metadata, and this answer in particular, and tools like npmtrends.

No one can ever say that software development is boring…

A better Trader has been a work-in-progress project of mine for a very long time. The web UI was done in vanilla javascript, with old school imports, and PHP-style server-generated html, then added jQuery, then bootstrap, then started removing jQuery, then moved towards more-static html with JSON payloads for the data, then pined for better node imports, then then then. You get the point.

I went too long without a rewrite, so I recently became a weekend warrior skeletoning up the next gen web ui. Parts include:

  • Vite due to its blazing hot-loading, tree-shaking, polyfilling goodness
  • React because it’s good enough and gets the job done
  • Bootstrap because I won’t have time to finish the mobile apps for a while

For my UIs, D3 is the most important library there is. So the skeleton is based on responsively displaying a handful of some of Mike Bostock’s greatest hits (imho). This was quite important to me because D3 examples have been somewhat obfuscated when they were migrated to Observables notebooks. The skeleton makes it much easier for me to quickly get working D3 examples by copying Mike’s Observables code into a cozy little container with all the bells and whistles in place.

Let me know what you think of it.

Live Demo | GitLab | GitHub | Wiki

In c++, all a sort operation needs is a lessThan function. Complex sorts are EASY:

struct AnalyzerJobs_lessthan
{
    bool operator()(const AnalyzerJob* left, const AnalyzerJob* right) const
    {
        assert(left ->psq_->second && left ->psq_->second->p_shared_aps_ && left ->psq_->second->p_shared_aps_->p_ad_);
        assert(right->psq_->second && right->psq_->second->p_shared_aps_ && right->psq_->second->p_shared_aps_->p_ad_);

        // Primary sort
        // Critical jobs first
        // If only one is critical, it wins.
        if (left ->psq_->second->p_shared_aps_->bCriticalAnalysisNeeded() != right->psq_->second->p_shared_aps_->bCriticalAnalysisNeeded())
            return left ->psq_->second->p_shared_aps_->bCriticalAnalysisNeeded();

        // Secondary sort
        // If only one has never been analyzed, it wins.
        if (left->psq_->second->p_shared_aps_->bAnalyzed() != right->psq_->second->p_shared_aps_->bAnalyzed())
            return right->psq_->second->p_shared_aps_->bAnalyzed();

        // Tertiary sort by reverse timestamp of last analysis.
        double lefttime  = left ->psq_->second->p_shared_aps_->analysis_finished_timestamp_;
        double righttime = right->psq_->second->p_shared_aps_->analysis_finished_timestamp_;
        return (lefttime > righttime);
    }
};

You’d think JavaScript would keep that battle-tested methodology, but they decided it would be better to expect a result from the sort function of [ -1, 0, 1 ]. I’m assuming so they can eek out a bit of performance when sorting arrays that have a large number of “equal” items. Seems an outlier case to optimize for, but it probably puts it on some slightly higher score on some manic benchmark.

So for even the simplest sort, you have to do this stupidity:

myArray.sort(( a, b ) => ( a.value > b.value ? 1 : -1 ));

It seems to work as long as the sign is right, so this is also possible:

myArray.sort(( a, b ) => ( a.value - b.value ));

Also, remember that JavaScript provides all kinds of “helpful” dangerous ugly default conversions. Cest la vie. I have to remember though – I’ve used c++ style comparisons in JavaScript sort functions more than once, and that shit don’t fly. ok byeeeee!

Browsers are here to own our desktops. But they will never deliver the absolute horsepower of a natively-coded world-class desktop app or game.

These days, when you try to run one, you will find it is crippled by the browser’s 100 open tabs (admit it, you have that many open…). And lord knows you don’t want to close them all.

I am the user. I am the king. Not the last 20 sites I happened to browse, each of which is allowed to take a huge chunk of our system resources for whatever task they deem important. Once you’ve rabbit-holed down a few holes, you have given your entire system resources to them.

Don’t put up with this. OWN YOUR OWN SYSTEM.

To really take it back when you need to play a game, work in your DAW, or play a 4k video at high frame rate, you need that browser to give up ALL its resources. And in linux, that is super easy.

  • Find the parent browser process pid:
ps ax --forest| grep "[0-9][\_ ]*/usr/lib/firefox/firefox$"
  • “STOP” it. This is the magic that tells linux to just stop serving the parent process and all its children, stripping all CPU allocation from the tasks, without actually closing anything (especially your precious tabs scattered across all your virtual desktops). It’s amazing, it will freeze your browser in its tracks in an instant:
kill -STOP #pid-from-previous-step#
  • Start your powerhouse desktop app and do your thing.
  • When you’re done, you can “CONTINUE” the stopped process, kicking off the CPU to immediately start servicing all that javascript again:
kill -CONT #pid-from-previous-step#

I’ve scripted this up so I can press a media key to “stop” firefox and start up Kodi with beautiful performance. Here’s my javascript “continue” script, which uses my rad-scripts tooling:

#!/usr/bin/env node
import * as rs from 'rad-scripts';
const ffPs = rs.run_command_sync('ps ax --forest| grep "[0-9][\_ ]*/usr/lib/firefox/firefox$"');
const ffProcId = +( ffPs.trim().split(' ')[ 0 ] );
console.log( `Parent firefox pid = ${ffProcId}` );
rs.run_command_sync_to_console(`kill -CONT ${ffProcId}`);