Some Bits: Nelson's log

15 posts in January 2016

Mac sound capture, take 2

Awhile ago I wrote up some notes on recording League of Legends videos using OBS. I still mostly follow that horribly manual workflow, but I was having a hard time getting sound to work reliably. I think I have it sorted out now.

  1. Install Matt Ingalls’ SoundFlower 2.0b2 from GitHub
  2. Reboot. Not clear this is necessary, but I think it may be.
  3. Follow these instructions for configuring audio. However, Soundflowerbed is no longer included. Fortunately you can ignore that if you Audio MIDI Setup yourself (standard Mac software)

The key thing here is you use Audio MIDI Setup to create a new “Multi-Output Device”. That’s a virtual sound device that can send output to more than one place, in this case both “Built-in Output” (your speakers) and “Soundflower (2ch)” (the capture device).

Then you use the Sound preference panel to tell the Mac to play output to that new Multi-Output Device. Now every sound your Mac plays will both come out the speakers and be sent to SoundFlower.

Then you set up OBS to accept audio input from the SoundFlower device.

Unfortunately setting the default sound output to Multi-Output Device will break the volume control from the Mac keyboard. You can still set the volume for each output in the Sound panel though, just be sure to leave Multi-Output Device selected when you’re done. You want to modulate actual volume using Internal Speakers’ control. Set the Soundflower and Multi-Output Device volume to maximum, so that sound is passed through at full volume to OBS.

In previous versions of this setup I found cases where OBS could record audio correctly, but only if it was launched after the program playing the sound. No idea what that was about. I don’t think that’s happening any more.

If you’re serious about doing more fancy audio routing, the commercial Loopback program is pretty good. At $75 though it’s a bit pricy for what I’m doing.

CNAMEs at a DNS root

It’s common wisdom that you can’t use a CNAME at the root of your domain. http://www.example.com can be a CNAME pointing to something, but example.com can’t. That makes hosting websites on naked domains awkward. Only confusingly you actually can do this, it’s just a bad idea. And some DNS services make it look like you’re doing it in a good way, but really they’re faking it. It’s all pretty confusing but I think I understand what’s going on in detail. This post was motivated by this Hacker News thread.

A reading from the holy text, RFC 1034

A CNAME RR identifies its owner name as an alias, and specifies the corresponding canonical name in the RDATA section of the RR. If a CNAME RR is present at a node, no other data should be present; this ensures that the data for a canonical name and its aliases cannot be different. This rule also insures that a cached CNAME can be used without checking with an authoritative server for other RR types.

So if you make example.com a CNAME, you can’t put any other DNS records on it. AFAIK you can actually do this and it will work as well as a CNAME will. The problem is you often want other DNS entries at the apex domain. You want an MX entry so you can redirect mail at example.com. You want a TXT entry to verify you own the domain name to various services. You might want special funky records for DNSSEC or other stuff. It really doesn’t work to make your apex domain an alias for some other domain.

Confusingly, a lot of the big DNS providers do let you set up a CNAME at the apex domain. But behind the scenes they aren’t really serving it as a CNAME; it’s more of a synthetic alias implemented by their DNS server. Typically it looks up the destination host address and quickly substitutes that IP in with an A record for your apex domain. That breaks the end-to-end principle of the DNS lookups, which causes problems for geographic load balancing, fast cache expiry, and probably DNSSEC. But it’s not a terrible solution.

Here’s a list of some of the DNS vendors’ aliasing technology

Long story short, if you want to serve a website from an apex domain it requires compromises and/or protocol fiddling.

Looking at all this I wonder if the world would be well served with a special DNS entry just for web servers. It’s weird to put something application specific in DNS, but there’s a strong precedent in MX entries, for mail delivery. Probably a bad idea to extend that to the web, but maybe it’d all some useful tricks?

 

sqlite3 vs postgres: uneasy feeling

I continue to write my LoL Slack bot with sqlite3. I can live with the primary drawback of sqlite3, which is that writes require a database level lock (ie: no table or row locking). In normal use I should only ever have one writer to the database anyway. But I still have a nagging feeling I should use “a real database”. Ie: Postgres

The nervousness is I’m writing more complex code that’s wedded to sqlite. I’m using sqlite’s upsert equivalent, for which there is no standard syntax. I’m also using sqlite’s Python convenience feature of not using cursor objects. And just now I’m starting to pay attention to Python’s weird transactional semantics, which I suspect might be different in Postgres. In short my code has been dating sqlite for awhile but now things are getting serious and I’m getting commitment anxiety. Also Postgres has some alluring features I could use, like JSON and array types.

The underlying question is whether Postgres is really “better” for my kind of application. I suspect not, and part of why I stick with sqlite is to test that assumption, but the cost of being wrong is getting higher. The flip side is managing a Postgres daemon is still a PITA. Particularly on Ubuntu where upgrading is scary.

tuple vs list

One small thing in Python3 that continues to confound me is how dict.values, dict.keys, and zip all don’t return real collections but instead iterables. That means you have to wrap them first in a tuple or list if you want to array index the output. It’s not a huge deal, but it’s a nuisance.

So which is better? Tuple or list? Tuple should be in theory, because it’s immutable it should be a little more efficient. Seems to be that way in practice too.

$ python3 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.266 usec per loop
$ python3 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.331 usec per loop

$ python2 -m timeit 'tuple({"a":1}.values())[0]'
1000000 loops, best of 3: 0.227 usec per loop
$ python2 -m timeit 'list({"a":1}.values())[0]'
1000000 loops, best of 3: 0.256 usec per loop

(You know, every time I do a timeit on python2 vs python3, python3 is measurably slower. Some of that is due to Unicode but I don’t think that’s all of it.)

Python HTTP mocking

I need to do a better job mocking out HTTP requests to allow me to test all this web API code I’ve written. Right now I rolled my own bad mocking around a wrapper for all the REST calls, but I think it makes more sense just to mock at the HTTP level.

A quick Google search reveals three modern libraries: requests-mock, responses, and httpretty. After literally tens of minutes I’m left with the opinion any would work. responses-mock looks like the most mature and complete product. I like responses for its simplicity. The main differences between the three are the mechanism they use to intercept HTTP calls. I believe httpretty is the only one that works with an HTTP library other than Requests. OTOH why would you use any other HTTP library in Python?

Update: since doing this exercise I started using requests-mock. I’m quite happy with it.

Some detailed notes below, then my test code.

requests-mock: mocks out Requests by installing a Transport Adapter. (I’m endeared, because I came up with a similar technique on my own for Java back in 2000 or so.) Has detailed support for matching full URLs or parts of URLs or specific query strings or URL regexps. Supports all HTTP methods. Responses can be text, JSON, byte strings, or callbacks. Has a way to inspect which URLs were called. Has great docs.

Responses: mocks out Requests using the unittest.mock library, patching requests’ send function. Supports matching on regex, but no special support for query strings in URLs. Responses can be text or JSON or callbacks. Supports all HTTP methods. Optionally throws an error if not all URLs were accessed. No fancy docs, but the code is easy to read. Motivation in this blog post.

httpretty: works by monkey patching sockets. that’s terrifying, but kinda neat because it can mock out HTTP from sources other than Requests. Oddly they don’t have official Python 3 support (it seems to work though). I didn’t look at all its features in detail.

(BTW, unittest.mock was new to me, a very nice standard library for monkey patching any Python library for unit test mocking. That could come in handy in lots of places.)

Here’s my test / sample code.

#!/usr/bin/env python3

import requests, unittest
import requests_mock, responses, httpretty

def fetch():
    "The method we'll be mocking"
    r = requests.get('https://www.somebits.com/robots.txt')
    return r.text

class TestStuff(unittest.TestCase):
    def test_real(self):
        self.assertEqual(107, len(fetch()))

    def test_requests_mock(self):
        with requests_mock.Mocker() as m:
            m.get('https://www.somebits.com/robots.txt', text='nelson-requests-mock')
            self.assertEqual('nelson-requests-mock', fetch())

    def test_responses(self):
        with responses.RequestsMock() as r:
            r.add(responses.GET, 'https://www.somebits.com/robots.txt', 'nelson-responses-mock')
            self.assertEqual('nelson-responses-mock', fetch())

    def test_httpretty(self):
         httpretty.enable()
         httpretty.register_uri(httpretty.GET, "https://www.somebits.com/robots.txt", 'nelson-response-httpretty')
         self.assertEqual('nelson-response-httpretty', fetch())
         httpretty.disable()

if __name__ == '__main__':
    unittest.main(exit=False)

    # Verify the environment is left clean
    assert 107 == len(fetch())
    print("Real requests are working again.")

Two sqlite3 gotchas

Ran into a couple of odd problems when doing database schema migrations on my sqlite3 database.

Transactions don’t work like you’d expect in the sqlite3 command line tool! I wrote a few lines of SQL to create a new table and drop an old one, then fed that script to sqlite with the command line tool like this: sqlite3 my.db < script.sql. I was clever and wrapped my script.sql in a “begin transaction... commit” so that if there were any errors, nothing would be committed. Smart, right? Wrong. sqlite3 will gladly execute line n+1 in a script it’s fed even if line n fails. This makes sense for interactive use, but is a disaster for a script that wants a transaction; the commit at the end will always run. The solution is to put .bail on in the top of your script so any errors cause execution to terminate. See also this discussion.

I was using an “insert or replace” command to be sure I only had one row per key in my database, along with a unique constraint to tell the DB what the key was. Only I didn’t actually add the unique constraint during my migration, because it’s a PITA to do schema changes like that in sqlite3. unique constraints are only hints, right, it’s like a type checker! Well not if you rely on the constraint violation enabling an “insert or replace” to work. Oops.

 

Progress

Still working away on my LoL / Slack bot. Today’s project was rejiggering all the code to use a new synthetic “personId” as the primary identifier. Previously I was using “summonerId”, but that’s only unique to a single region (like North America) and now I need to make the thing work for multiple regions.

Scary code change because it touches all the files and a lot of assumptions. But no changed types; it’s swapping one int for another. My simple test suite paid off in spades here, giving me the confidence my changes worked. So far so good!

I even had to do a database migration, adding a column to a couple of tables. That I just hacked up by hand but it seems to have done the job. I need to do another now to drop the superfluous column. Unfortunately sqlite doesn’t really support dropping columns, will have to do some more complicated stuff involving creating a new table and renaming it.

 

Testing discipline

One of my successes in my professional career has been advocating for unit testing. I helped lead the charge for automated unit test suites inside Google, particularly for our Java code, and that ended up being hugely useful.

I’m nowhere near as disciplined when I’m working alone on my little hacks. It’s still just too much effort to write tests! It feels like twice the work. For a long lived software project with many users, sure, it’s worth the investment. But a one-off hack you’re not going to ever pick up again? Is it even worth the bother of remembering Python’s baroque unittest syntax to set up a test framework? (I have to look that up every... single... time...)

But small hacks have a way of becoming bigger things, vital projects. I’m continuing to work on my Slack / League of Legends integration. I may even get a bunch of new users, I found a community of a few hundred people who could use it! Yay! But I’ve gotten to a point of paralysis where I was afraid to make changes because I couldn’t tell if I would break things other than pushing it to the live system and then see if cron mailed me any errors. Derp.

Unfortunately this project is particularly thorny to test. I’m integrating with two different online APIs (Riot and Slack). I’m also storing data in a database, and I’ve still never seen a good solution for mocking out a stateful database. For now I’m just going with ugly hacks. I’ve put wrappers around the Riot API calls that will load canned data from a pickle, a sort of persistent memoization. And I’m just accepting the test script needs to create a fresh test database and populate it from scratch. That’s not the ideal of unit tests, but it is still some form of useful automated testing.

I already feel relief and confidence from having even something very basic in place. Now I can type “./test.sh” before deploying and at least know if the scripts are going to blow up on some really stupid error. And I have a place now to add more sophisticated tests for correctness.

Update boy what a difference that simple test suite has made. I’ve felt free to make way more aggressive changes to my code now. Without fear.

 

Slack API: channels, groups, IMs

I’m writing a fancy Slack bot to post messages in a Slack for 500+ users. Fun!

There are at least three different kinds of things a Slack bot can post to:

  • Channels. These are the public channels like #general. Find them with channels.list. Bots can’t call channels.join; I think they’re de facto members of all public channels.
  • Groups. These are private channels. The bot has to be invited via /invite, then it can see the group IDs with channels.list.
  • IMs. These are direct messages. You can see all of a bot’s IMs with im.list. I think someone has to message a bot first before the IM channel is created, not sure how a bot can initiate an IM (if at all).

I mostly like the Slack API but it’s a bit warty for things like this. My impression is it’s grown organically and they’ve never gone through and deprecated old stuff. It’s nice that old code keeps working, but it’s a bit confusing if you’re starting now. I’m also really confused about the various kinds of integrations, bots, applications, etc.

A better Python object for JSON take 2

I wrote about wanting a better Python object for JSON. Now I’ve tried out a bunch of options, all inadequate, and am clearer what I want.

The best of the libraries I found was addict. Or maybe easydict because it is slightly less magic. dotmap is also OK but has one wrinkle. attrdict was the only one I couldn’t make work well.

I’ve put sample code exercising various libraries in this gist.

Here are the things I want, in order of priority:

  1. Dot access to fields instead of []
  2. Sensible default value for missing keys instead of an exception
  3. Ease of adding new nested values
  4. Ease of serializing to JSON
  5. Small performance hit

All the libraries provide #1, dot syntax for reading keys. The challenge is #2, what happens if the field is missing (like d.noObj in my code). dotmap and addict both return an empty dict {} for missing keys. That’s not a terrible default although I’d prefer None. attrdict.AttrDefault() lets you choose a different default value but has other problems. easydict just throws exceptions for missing keys; making the dot syntax of questionable usefulness.

The tricky thing is #3 and it ties to what happens if you then assign to an empty dict for a missing key. That’s required for convenient syntax for setting a deeply nested value, the ideal syntax of “d.other.nested.thing = 6”. Both dotmap and addict actually create an empty dict value in the data structure the moment you try to read an empty key. That lets nested assignment work, but leaves litter in your data structure. addict edges out dotmap here because it provides a .prune() method to remove them. easydict doesn’t create empty dict values, so nested assignment isn’t convenient but then it’s less magic.

#4, JSON serialization,is not too hard in any system. addict, easydict, and attrdict just let you pass the thing to json.dump(); their objects are subtypes of dict. dotmap requires you explicitly call .toDict().

I did not measure #5, performance. Each library has a different approach to when it copies data, would be worth examining.

I mentioned above I couldn’t make attrdict work for me. That may be my error, not the library’s. It’s neat in that there’s actually two options; AttrDefault, which provides alternate default values, and AttrDict, which is a bit simpler. But AttrDict has a mysterious / confusing design wrinkle for “Recursive attribute access” that’s a n00b trap. And I couldn’t figure out how to JSON serialize an AttrDefault, nor even how to turn it into a normal dict. Maybe I missed something.

Doing this exercise made me wonder about the wisdom of #2, sensible default values. The problem is there’s not a one-size-fits-all default. Often you want it to be None, for simple primitives. But sometimes you might want [] for an empty list or {} for an empty object. If you want to let the programmer choose those values, you might as well go fully verbose and use the dict.get() method with its default value.

I could see using EasyDict in the future if I only wanted to read JSON and weren’t worried about #2, missing values. It’s the least magic. Or else Addict if I also wanted to construct JSON and get empty dicts returned for missing keys.

Update: it strikes me that a lightweight use of JSON schema would be helpful here. If you know what types to expect, you can fill in any missing keys with appropriate empty values. Not sure anyone uses JSON schema in the wild though. I’d want to start with something that auto-infers schema from examples. And I don’t care about validation, just using type expectations as hints on what to do with ambiguity.

Update Nov 2019: see FlexDict. It has solutions for the creating-objects-for-keys problem.

A better Python object for JSON

Python’s default JSON package encodes and decodes to a dict. This works well enough, but I’ve never much loved the dict type in Python. I’d rather it were an Object with attributes. dicts are verbose: data[“foo”] instead of data.foo. Also dicts throw exceptions on unknown keys, when often what I want is it just to return None. So I’m left with data.get(“foo”, None) which is awfully wordy. Basically I want something that’s as convenient and sloppy as Javascript objects.

I asked on Twitter and got some suggestions, none awesome.

Not sure if these imply overhead from copying, etc. Also they may not serialize well in the JSON module, although I imagine you can copy out a dict view on at least one of these. (More overhead!)

A yak that needs shaving. Don’t they all?

Update: see this second post

sqlite upserts, inserts, etc

sqlite has a nifty feature; “on conflict”, aka “insert or”. You apply it to insert and update operators to tell sqlite what to do if the operation would violate a constraint like unique or not null.

I’m using “insert or ignore” to only insert a row if it doesn’t exist.

insert or ignore into mytable(userid) value (23)

You can also use “insert or replace” to do an upsert

insert or replace into mytable(userid, name) value (23, "Joe")

 

Slack API thoughts

I’m working on a Slack integration that marries the Riot games API to the Slack API, for a group of League of Legends gamers I play with. I’ve been doing simple message posting from a cron job for 6 months now and it works great. Now doing fancier stuff.

I’m not a fan of the message formatting options. There’s the basic markup which they call “markdown” even though it’s not markdown. Then you can add attachments which has a bit of a tabular layout to them but it’s not very flexible. I can’t make it look like what I want, so I’m reduced to doing fixed-width formatting of plain text. Ugly. I wish they’d let me do free form HTML but I guess they’re aiming for display consistency so don’t want that.

I am impressed with how easy it is to add basic slash commands though. You can just create a “Configuration” that causes /foo to fire off a POST to the URL of your choice. Done! There’s fancier stuff for installable commands, too.

Last comment; the slackclient.py that looks official is not awesome. There’s no proper release schedule so what’s on PyPI is out of date. And it seems to rely on an odd websockets implementation. I may want to look into alternative Python wrappers if I do anything too complicated. I’ve only been using the REST Web API so far, not any streams.

 

Let’s Encrypt thoughts

I just set up Let’s Encrypt to enable SSL on my weblog server. I did this in the dumbest way possible, just running ./letsencrypt-auto --apache without understanding what it was doing. It went very smoothly and I really admire the turnkey installation that the project has come up with. Here’s a report on the result, and how it looks in Chrome:

Screen Shot 2016-01-06 at 10.46.37 AM

But of course I have some complaints valuable observations.

There’s one usability problem; the certificates expire every three months and they don’t have an automated renewal process yet. They promise one soon.

Also I lied a bit, it didn’t go smoothly, in fact it choked processing my Apache config file. I filed a bug, it’s related to a rewrite rule that is idiosyncratic to me, no big deal. But the bug reports are full of “it failed to parse my Apache file!” with the developers diligently fixing every parse problem. It feels like they’d benefit from a more sloppy parser, something that just extracts the part of the config file they really need and doesn’t try to validate / parse the whole thing. This config management stuff always sucks in software though.

As convenient as the turnkey magic is, it also made me nervous. I wish it printed a little summary of what it did to console. It seems to have installed some Ubuntu packages, munged some config files, generated a key, and reloaded Apache to enable SSL. I’m protective of my server; maybe I should have done a manual install or read the docs first.

Fortunately there are good docs, a little thin, but the basics. They store all the certs in /etc/letsencrypt/. Diffing against a backup I see they add SSL solely by creating new files in /etc/apache2; enable a couple of SSL mods, then create a somebits-le-ssl.conf for the SSL site. Unfortunately that file is a complete copy of the original somebits.conf file only on port 443 with SSL stuff added. I hate to see that duplication of configuration! I wonder if it’s partly my fault for having sloppy config files. Some ideas for doing it right: macros or include files. Of course Let’s Encrypt shouldn’t be doing that for me, but it may be best-practice to do it for myself.

Their logging config in /etc/letsencrypt/options-ssl-apache.conf was not a good match for my carefully managed logs. Their config seems to automatically write any SSL site logs to /var/log/apache2/access.log with a vhost attached. That seems like a reasonable default, but in my case I already have custom logs enabled in each site.conf file that go to different directories. Just a case of Let’s Encrypt’s defaults not being right for me.

Slack API code to look up IM channel

I want to write a Slack bot that sends IM Direct Messages. It’s a bit indirect in Slack. You have to first call im.list to get a list of all the “DM channels” the bot can write to. Then you have to look up the user info for each channel to figure out which person it actually is. Here’s some throwaway code that does that.

Bonus wrapper for the official Python slackclient library to decode the response and throw appropriate exceptions. That library has gotten little love from Slack, it could use some help.

from pprint import pprint
from slackclient import SlackClient
import json

_slack = SlackClient("SECRET")
def slack(*args, **kwargs):
    "Wrapper for Slack API. Manages stub, also decodes responses and raises exceptions"
    rb = _slack.api_call(*args, **kwargs)
    r = json.loads(rb.decode("utf-8"))
    if r.get("ok", False) != True:
        raise Exception("Error making Slack call", r)
    else:
        return r

imList = slack("im.list")
for user in imList['ims']:
    pprint(user)
    info = slack("users.info", user=user['user'])
    pprint(info)