Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/bindings-typescript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@
"fast-text-encoding": "^1.0.0",
"headers-polyfill": "^4.0.3",
"prettier": "^3.3.3",
"pure-rand": "^7.0.1",
"statuses": "^2.0.2",
"url-polyfill": "^1.1.14"
},
Expand Down
2 changes: 2 additions & 0 deletions crates/bindings-typescript/src/lib/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type { ReducerSchema } from './reducer_schema';
import { toCamelCase, toPascalCase } from './util';
import type { CamelCase } from './type_util';
import { Uuid } from './uuid.ts';
import type { Random } from '../server/rng';

/**
* Helper to extract the parameter types from an object type
Expand Down Expand Up @@ -123,6 +124,7 @@ export type ReducerCtx<SchemaDef extends UntypedSchemaDef> = Readonly<{
senderAuth: AuthCtx;
newUuidV4(): Uuid;
newUuidV7(): Uuid;
random: Random;
}>;

/**
Expand Down
1 change: 1 addition & 0 deletions crates/bindings-typescript/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from './query';
export type { ProcedureCtx, TransactionCtx } from '../lib/procedures';
export { toCamelCase } from '../lib/util';
export { type Uuid } from '../lib/uuid';
export { type Random } from './rng';

import './polyfills'; // Ensure polyfills are loaded
import './register_hooks'; // Ensure module hooks are registered
119 changes: 119 additions & 0 deletions crates/bindings-typescript/src/server/rng.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import type { RandomGenerator } from 'pure-rand';
import { unsafeUniformBigIntDistribution } from 'pure-rand/distribution/UnsafeUniformBigIntDistribution';
import { unsafeUniformIntDistribution } from 'pure-rand/distribution/UnsafeUniformIntDistribution';
import { xoroshiro128plus } from 'pure-rand/generator/XoroShiro';
import type { Timestamp } from '../lib/timestamp';

declare global {
interface Math {
random(): never;
}
}

type IntArray =
| Int8Array
| Uint8Array
| Uint8ClampedArray
| Int16Array
| Uint16Array
| Int32Array
| Uint32Array
| BigInt64Array
| BigUint64Array;

/**
* A collection of random-number-generating functions, seeded based on `ctx.timestamp`.
*
* ## Usage
*
* ```
* const floatOneToTen = ctx.random() * 10;
* const randomBytes = ctx.random.fill(new Uint8Array(16));
* const intOneToTen = ctx.random.integerInRange(0, 10);
* ```
*/
export interface Random {
/**
* Returns a random floating-point number in the range `[0.0, 1.0)`.
*
* The returned float will have 53 bits of randomness.
*/
(): number;

/**
* Like `crypto.getRandomValues()`. Fills a `TypedArray` with random integers
* in a uniform distribution, mutating and returning it.
*/
fill<T extends IntArray>(array: T): T;

/**
* Returns a random unsigned 32-bit integer in a uniform distribution in the
* range `[0, 2**32)`.
*/
uint32(): number;

/**
* Returns an integer in the range `[min, max]`.
*/
integerInRange(min: number, max: number): number;

/**
* Returns a bigint in the range `[min, max]`.
*/
bigintInRange(min: bigint, max: bigint): bigint;
}

const { asUintN } = BigInt;

/** Based on the function of the same name in `rand_core::SeedableRng::seed_from_u64` */
function pcg32(state: bigint): number {
const MUL = 6364136223846793005n;
const INC = 11634580027462260723n;

state = asUintN(64, state * MUL + INC);
const xorshifted = Number(asUintN(32, ((state >> 18n) ^ state) >> 27n));
const rot = Number(asUintN(32, state >> 59n));
// rotate `xorshifted` right by `rot` bits
return (xorshifted >> rot) | (xorshifted << (32 - rot));
}

/** From the `pure-rand` README */
function generateFloat64(rng: RandomGenerator): number {
const g1 = unsafeUniformIntDistribution(0, (1 << 26) - 1, rng);
const g2 = unsafeUniformIntDistribution(0, (1 << 27) - 1, rng);
const value = (g1 * Math.pow(2, 27) + g2) * Math.pow(2, -53);
return value;
}

export function makeRandom(seed: Timestamp): Random {
// Use PCG32 to turn a 64-bit seed into a 32-bit seed, as the Rust `rand` crate does.
const rng = xoroshiro128plus(pcg32(seed.microsSinceUnixEpoch));

const random: Random = () => generateFloat64(rng);

random.fill = array => {
const elem = array.at(0);
if (typeof elem === 'bigint') {
const upper = (1n << BigInt(array.BYTES_PER_ELEMENT * 8)) - 1n;
for (let i = 0; i < array.length; i++) {
array[i] = unsafeUniformBigIntDistribution(0n, upper, rng);
}
} else if (typeof elem === 'number') {
const upper = (1 << (array.BYTES_PER_ELEMENT * 8)) - 1;
for (let i = 0; i < array.length; i++) {
array[i] = unsafeUniformIntDistribution(0, upper, rng);
}
}
return array;
};

random.uint32 = () => rng.unsafeNext();

random.integerInRange = (min, max) =>
unsafeUniformIntDistribution(min, max, rng);

random.bigintInRange = (min, max) =>
unsafeUniformBigIntDistribution(min, max, rng);

return random;
}
21 changes: 11 additions & 10 deletions crates/bindings-typescript/src/server/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import type { DbView } from './db_view';
import { SenderError, SpacetimeHostError } from './errors';
import { Range, type Bound } from './range';
import ViewResultHeader from '../lib/autogen/view_result_header_type';
import { makeRandom, type Random } from './rng';

const { freeze } = Object;

Expand Down Expand Up @@ -195,6 +196,7 @@ export const ReducerCtxImpl = class ReducerCtx<
#identity: Identity | undefined;
#senderAuth: AuthCtx | undefined;
#uuidCounter: { value: number } | undefined;
#random: Random | undefined;
sender: Identity;
timestamp: Timestamp;
connectionId: ConnectionId | null;
Expand Down Expand Up @@ -223,26 +225,25 @@ export const ReducerCtxImpl = class ReducerCtx<
));
}

get random() {
return (this.#random ??= makeRandom(this.timestamp));
}

/**
* Create a new random {@link Uuid} `v4` using the {@link crypto} RNG.
*
* WARN: Until we use a spacetime RNG this make calls non-deterministic.
* Create a new random {@link Uuid} `v4` using this `ReducerCtx`'s RNG.
*/
newUuidV4(): Uuid {
// TODO: Use a spacetime RNG when available
const bytes = crypto.getRandomValues(new Uint8Array(16));
const bytes = this.random.fill(new Uint8Array(16));
return Uuid.fromRandomBytesV4(bytes);
}

/**
* Create a new sortable {@link Uuid} `v7` using the {@link crypto} RNG, counter,
* and the timestamp.
*
* WARN: Until we use a spacetime RNG this make calls non-deterministic.
* Create a new sortable {@link Uuid} `v7` using this `ReducerCtx`'s RNG, counter,
* and timestamp.
*/
newUuidV7(): Uuid {
// TODO: Use a spacetime RNG when available
const bytes = crypto.getRandomValues(new Uint8Array(4));
const bytes = this.random.fill(new Uint8Array(4));
const counter = (this.#uuidCounter ??= { value: 0 });
return Uuid.fromCounterV7(counter, this.timestamp, bytes);
}
Expand Down
2 changes: 1 addition & 1 deletion crates/bindings-typescript/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ export default defineConfig([
],
},
external: ['undici', /^spacetime:sys.*$/],
noExternal: ['base64-js', 'fast-text-encoding', 'statuses'],
noExternal: ['base64-js', 'fast-text-encoding', 'statuses', 'pure-rand'],
outExtension,
esbuildOptions: commonEsbuildTweaks(),
},
Expand Down
10 changes: 10 additions & 0 deletions crates/core/src/host/v8/builtins/delete_math_random.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
delete Math.random;
Object.defineProperty(Math, 'random', {
enumerable: false,
configurable: true,
get() {
throw new TypeError(
'Math.random is not available in SpacetimeDB modules. Use ctx.random instead.'
);
},
});
1 change: 1 addition & 0 deletions crates/core/src/host/v8/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub(super) fn evalute_builtins(scope: &mut PinScope<'_, '_>) -> ExcResult<()> {
};
}
eval_builtin!("text_encoding.js")?;
eval_builtin!("delete_math_random.js")?;
Ok(())
}

Expand Down
84 changes: 78 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading