Refactor various parts of the `/sync` handler.