This change harmonizes server document ID generation regardless of whether
it happens inside of a method or not, by using Alea in both cases.
This cuts time of inserting small documents outside of methods
on the server by over 30%, and more importantly makes it easier to be
confident in benchmarking numbers.
---
BACKGROUND
When calling `coll.insert()` on the server within methods, we use the Alea PRNG
(which is fast, can be seeded, and not cryptographically secure) to generate
the `_id` field for the newly created document (unless an `_id` field was
explicitly passed).
The reason we use Alea is so that we can seed the PRNG from the client, as to
ensure consistently chosen IDs for methods that create multiple documents and
run on both client and server.
Prior to this change, when calling `coll.insert()` on the server *not* inside
methods, we'd use Node's cryptographically secure `crypto.getRandomBytes()`
which is slower (due to allocating buffers that need to cross from JS
into native code).
With this change, we always use Alea when generating a document ID.
---
CRYPTOGRAPHICALLY SECURE IDS STILL AVAILABLE
If an app wants to guarantee using a cryptographically secure PRNG
when generating IDs, just generate IDs yourself:
`coll.insert({_id: Random.id(), ...})`.
`Random.id()` still uses a CSPRNG (unless you're on IE, or
on the server and not enough entropy has been collected, which is
basically never the case).
If you *want* the faster Alea algorithm, use `Random.fast.id()`
(The `Random.fast` object has all the same methods as on `Random`)
---
BENCHMARK RESULTS
Here are the measured times for inserting 5000 documents, before
and after this change (on my machine):
Benchmark | Before | After
--------------------------------- | ------ | ------
direct insert from `meteor shell` | 2179ms | 1520ms
a method called from a browser | 1617ms | 1570ms
a method called from the server | 1491ms | 1487ms
direct insert from the server | 2272ms | 1445ms
(The benchmark can be found here:
f32ea073b7/benchmark2.sh)
This means node's crypto.randomBytes on the server, and
window.crypto.getRandomValues on the client. If node's crypto.randomBytes throws
an exception, we fall back to crypto.pseudoRandomBytes. If
window.crypto.getRandomValues isn't supported by the browser, we fall back to
the alea generator that we had been using previously.
For repeatable unit test failures with "random" data it's useful to be
able to create deterministic random number sequences.
Introduce `Random.create(seed...)` which returns a object with the
`Random` API (`id()`, `choice()`, etc.) initialized with the passed
seed(s).