Matrix well-known with Cloudflare

I had a small problem. I had one nginx container up and running only serving matrix .well-known static files.

My matrix server is on matrix.helderferreira.io subdomain and this well-kown files tell other clients and servers where to find the server that handles all matrix traffic from the helderferreira.io domain. This process is called delegation.

Although this image didn't consume much CPU or RAM it trowed some weird errors had an high fluctuation on response times and essentially didn't feel right have to maintain 1 more image just to serve this 2 static files.

As all this domain is proxied behind Cloudflare I took a look at Cloudflare workers free tier. After following the get started guide I came up with code on this repo.

This is the only file that matters:

export async function handleRequest(request: Request): Promise<Response> {
  
  const url = new URL(request.url)

  const headers = {
    headers: {
      "content-type": "application/json;charset=UTF-8"
    }
  }
  
  const serverJson = {
    "m.server": "matrix.helderferreira.io:443"
  }

  const clientJson = {
      "m.homeserver": {
          "base_url": "https://matrix.helderferreira.io"
      },
      "m.identity_server": {
          "base_url": "https://vector.im"
      }
  }
  
  var msg

  if (url.pathname.endsWith("server")) {
    msg  = JSON.stringify(serverJson)
  }

  if (url.pathname.endsWith("client")) {
    msg = JSON.stringify(clientJson)
  }

  if (msg) {
    return new Response( msg , headers);
  } else {
    return new Response('Not Found.', { status: 404 })
  }
  
}

Added the wrangler-action to control the deploy automatically using a GitOps approach and configured route and zone on wrangler.toml

name = "well-known"
type = "javascript"
zone_id = ""
account_id = "6f69eb15ec0a5662919d4bee9cecd014"
route = ""
workers_dev = true
compatibility_date = "2022-01-13"

[build]
command = "npm install && npm run build"
[build.upload]
format = "service-worker"


[env.production]
# The ID of the domain to deploying to
zone_id = "41d286b53b9b0b0b88fb962b7db752ed"

# The route pattern your Workers application will be served at
route = "helderferreira.io/.well-known/matrix/*"

And done!

Average speed:

    time_namelookup:  0.003826
       time_connect:  0.012706
    time_appconnect:  0.000000
   time_pretransfer:  0.012796
      time_redirect:  0.000000
 time_starttransfer:  0.028986
                    ----------
         time_total:  0.029067

Conclusion

+ more stability
+ more speed
+ 1 less image to pull and keep up to date
- New dependency with an external provided created