Skip to content
Open
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
165 changes: 116 additions & 49 deletions crates/bindings-typescript/src/server/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as _syscalls1_0 from 'spacetime:sys@1.0';
import * as _syscalls1_2 from 'spacetime:sys@1.2';
import * as _syscalls1_3 from 'spacetime:sys@1.3';

import type { ModuleHooks, u16, u32 } from 'spacetime:sys@1.0';
import { AlgebraicType, ProductType } from '../lib/algebraic_type';
Expand Down Expand Up @@ -48,7 +49,9 @@ import ViewResultHeader from '../lib/autogen/view_result_header_type';

const { freeze } = Object;

export const sys = freeze(wrapSyscalls(_syscalls1_0, _syscalls1_2));
export const sys = freeze(
wrapSyscalls(_syscalls1_0, _syscalls1_2, _syscalls1_3)
);

export function parseJsonObject(json: string): JsonObject {
let value: unknown;
Expand Down Expand Up @@ -220,10 +223,8 @@ export const hooks: ModuleHooks = {
return writer.getBuffer();
},
__call_reducer__(reducerId, sender, connId, timestamp, argsBuf) {
const argsType = AlgebraicType.Product(
MODULE_DEF.reducers[reducerId].params
);
const args = AlgebraicType.deserializeValue(
const argsType = MODULE_DEF.reducers[reducerId].params;
const args = ProductType.deserializeValue(
new BinaryReader(argsBuf),
argsType,
MODULE_DEF.typespace
Expand Down Expand Up @@ -499,15 +500,30 @@ function makeTableView(
prefix: any[],
prefix_elems: number
) => {
if (prefix_elems > numColumns - 1)
throw new TypeError('too many elements in prefix');
for (let i = 0; i < prefix_elems; i++) {
const elemType = indexType.value.elements[i].algebraicType;
AlgebraicType.serializeValue(writer, elemType, prefix[i], typespace);
}
return writer;
};

const serializePoint = (colVal: any[]): Uint8Array => {
const writer = new BinaryWriter(baseSize);
serializePrefix(writer, colVal, numColumns);
return writer.getBuffer();
};

const singleElement =
numColumns === 1 ? indexType.value.elements[0].algebraicType : null;

const serializeSinglePoint =
singleElement &&
((colVal: any): Uint8Array => {
const writer = new BinaryWriter(baseSize);
AlgebraicType.serializeValue(writer, singleElement, colVal, typespace);
return writer.getBuffer();
});

type IndexScanArgs = [
prefix: Uint8Array,
prefix_elems: u16,
Expand All @@ -516,33 +532,51 @@ function makeTableView(
];

let index: Index<any, any>;
if (isUnique) {
const serializeBound = (colVal: any[]): IndexScanArgs => {
if (colVal.length !== numColumns)
throw new TypeError('wrong number of elements');

const writer = new BinaryWriter(baseSize + 1);
const prefix_elems = numColumns - 1;
serializePrefix(writer, colVal, prefix_elems);
const rstartOffset = writer.offset;
writer.writeU8(0);
AlgebraicType.serializeValue(
writer,
indexType.value.elements[numColumns - 1].algebraicType,
colVal[numColumns - 1],
typespace
);
const buffer = writer.getBuffer();
const prefix = buffer.slice(0, rstartOffset);
const rstart = buffer.slice(rstartOffset);
return [prefix, prefix_elems, rstart, rstart];
};
if (isUnique && serializeSinglePoint) {
index = {
find: (colVal: IndexVal<any, any>): RowType<any> | null => {
const point = serializeSinglePoint(colVal);
const iter = tableIterator(
sys.datastore_index_scan_point_bsatn(index_id, point),
rowType
);
const { value, done } = iter.next();
if (done) return null;
if (!iter.next().done)
throw new Error(
'`datastore_index_scan_range_bsatn` on unique field cannot return >1 rows'
);
return value;
},
delete: (colVal: IndexVal<any, any>): boolean => {
const point = serializeSinglePoint(colVal);
const num = sys.datastore_delete_by_index_scan_point_bsatn(
index_id,
point
);
return num > 0;
},
update: (row: RowType<any>): RowType<any> => {
const writer = new BinaryWriter(baseSize);
AlgebraicType.serializeValue(writer, rowType, row, typespace);
const ret_buf = sys.datastore_update_bsatn(
table_id,
index_id,
writer.getBuffer()
);
integrateGeneratedColumns?.(row, ret_buf);
return row;
},
} as UniqueIndex<any, any>;
} else if (isUnique) {
index = {
find: (colVal: IndexVal<any, any>): RowType<any> | null => {
if (numColumns === 1) colVal = [colVal];
const args = serializeBound(colVal);
if (colVal.length !== numColumns)
throw new TypeError('wrong number of elements');

const point = serializePoint(colVal);
const iter = tableIterator(
sys.datastore_index_scan_range_bsatn(index_id, ...args),
sys.datastore_index_scan_point_bsatn(index_id, point),
rowType
);
const { value, done } = iter.next();
Expand All @@ -554,11 +588,13 @@ function makeTableView(
return value;
},
delete: (colVal: IndexVal<any, any>): boolean => {
if (numColumns === 1) colVal = [colVal];
const args = serializeBound(colVal);
const num = sys.datastore_delete_by_index_scan_range_bsatn(
if (colVal.length !== numColumns)
throw new TypeError('wrong number of elements');

const point = serializePoint(colVal);
const num = sys.datastore_delete_by_index_scan_point_bsatn(
index_id,
...args
point
);
return num > 0;
},
Expand All @@ -574,6 +610,23 @@ function makeTableView(
return row;
},
} as UniqueIndex<any, any>;
} else if (serializeSinglePoint) {
index = {
filter: (range: any): IteratorObject<RowType<any>> => {
const point = serializeSinglePoint(range);
return tableIterator(
sys.datastore_index_scan_point_bsatn(index_id, point),
rowType
);
},
delete: (range: any): u32 => {
const point = serializeSinglePoint(range);
return sys.datastore_delete_by_index_scan_point_bsatn(
index_id,
point
);
},
} as RangedIndex<any, any>;
} else {
const serializeRange = (range: any[]): IndexScanArgs => {
if (range.length > numColumns) throw new TypeError('too many elements');
Expand Down Expand Up @@ -613,21 +666,35 @@ function makeTableView(
return [prefix, prefix_elems, rstart, rend];
};
index = {
filter: (range: any): IteratorObject<RowType<any>> => {
if (numColumns === 1) range = [range];
const args = serializeRange(range);
return tableIterator(
sys.datastore_index_scan_range_bsatn(index_id, ...args),
rowType
);
filter: (range: any[]): IteratorObject<RowType<any>> => {
if (range.length === numColumns) {
const point = serializePoint(range);
return tableIterator(
sys.datastore_index_scan_point_bsatn(index_id, point),
rowType
);
} else {
const args = serializeRange(range);
return tableIterator(
sys.datastore_index_scan_range_bsatn(index_id, ...args),
rowType
);
}
},
delete: (range: any): u32 => {
if (numColumns === 1) range = [range];
const args = serializeRange(range);
return sys.datastore_delete_by_index_scan_range_bsatn(
index_id,
...args
);
delete: (range: any[]): u32 => {
if (range.length === numColumns) {
const point = serializePoint(range);
return sys.datastore_delete_by_index_scan_point_bsatn(
index_id,
point
);
} else {
const args = serializeRange(range);
return sys.datastore_delete_by_index_scan_range_bsatn(
index_id,
...args
);
}
},
} as RangedIndex<any, any>;
}
Expand Down
12 changes: 12 additions & 0 deletions crates/bindings-typescript/src/server/sys.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,15 @@ declare module 'spacetime:sys@1.2' {

export function procedure_abort_mut_tx();
}

declare module 'spacetime:sys@1.3' {
export function datastore_index_scan_point_bsatn(
index_id: u32,
point: Uint8Array
): u32;

export function datastore_delete_by_index_scan_point_bsatn(
index_id: u32,
point: Uint8Array
): u32;
}
1 change: 1 addition & 0 deletions crates/core/src/host/v8/syscall/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ fn resolve_sys_module_inner<'scope>(
(1, 0) => Ok(v1::sys_v1_0(scope)),
(1, 1) => Ok(v1::sys_v1_1(scope)),
(1, 2) => Ok(v1::sys_v1_2(scope)),
(1, 3) => Ok(v1::sys_v1_3(scope)),
_ => Err(TypeError(format!(
"Could not import {spec:?}, likely because this module was built for a newer version of SpacetimeDB.\n\
It requires sys module v{major}.{minor}, but that version is not supported by the database."
Expand Down
49 changes: 49 additions & 0 deletions crates/core/src/host/v8/syscall/v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,23 @@ pub(super) fn sys_v1_2<'scope>(scope: &mut PinScope<'scope, '_>) -> Local<'scope
)
}

pub(super) fn sys_v1_3<'scope>(scope: &mut PinScope<'scope, '_>) -> Local<'scope, Module> {
create_synthetic_module!(
scope,
"spacetime:sys@1.2",
(
with_sys_result_ret,
AbiCall::DatastoreIndexScanPointBsatn,
datastore_index_scan_point_bsatn
),
(
with_sys_result_ret,
AbiCall::DatastoreDeleteByIndexScanPointBsatn,
datastore_delete_by_index_scan_point_bsatn
),
)
}

/// Registers a function in `module`
/// where the function has `name` and does `body`.
fn register_module_fun(
Expand Down Expand Up @@ -1694,3 +1711,35 @@ fn procedure_commit_mut_tx(scope: &mut PinScope<'_, '_>, _args: FunctionCallback

Ok(())
}

fn datastore_index_scan_point_bsatn(
scope: &mut PinScope<'_, '_>,
args: FunctionCallbackArguments<'_>,
) -> SysCallResult<u32> {
let index_id: IndexId = deserialize_js(scope, args.get(0))?;
let point: &[u8] = deserialize_js(scope, args.get(1))?;

let env = get_env(scope)?;

// Find the relevant rows.
let chunks = env
.instance_env
.datastore_index_scan_point_bsatn_chunks(&mut env.chunk_pool, index_id, point)?;

// Insert the encoded + concatenated rows into a new buffer and return its id.
Ok(env.iters.insert(chunks.into_iter()).0)
}

fn datastore_delete_by_index_scan_point_bsatn(
scope: &mut PinScope<'_, '_>,
args: FunctionCallbackArguments<'_>,
) -> SysCallResult<u32> {
let index_id: IndexId = deserialize_js(scope, args.get(0))?;
let point: &[u8] = deserialize_js(scope, args.get(1))?;

// Delete the relevant rows.
let count = get_env(scope)?
.instance_env
.datastore_delete_by_index_scan_point_bsatn(index_id, point)?;
Ok(count)
}
Loading