This commit is a subset of the changes proposed in https://github.com/discourse/discourse/pull/17379.