Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Timestamp a special SATS type #1836

Merged
merged 36 commits into from
Feb 7, 2025
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
dece63c
WIP: Make `Timestamp` a special SATS type
gefjon Oct 10, 2024
998db08
Restore `Timestamp` to user-facing status
gefjon Oct 11, 2024
1a6566a
Clippy
gefjon Oct 11, 2024
9ecc60f
Fix Rust smoketests; offer backcompat methods
gefjon Oct 14, 2024
75a664e
Update TypeScript codegen to use new `Timestamp` class
gefjon Oct 16, 2024
9571e0e
Also add `TimeDuration`, which is like `Duration`
gefjon Oct 17, 2024
75ae9d9
Merge branch 'master' into phoebe/timestamp-special-type
gefjon Oct 21, 2024
5c64b9a
fmt
gefjon Oct 21, 2024
2934b59
Update WebSocket schema to use `TimeDuration`
gefjon Oct 21, 2024
ae88395
Implement Timestamp and TimeDuration in C#
kazimuth Oct 15, 2024
627c35b
Become more special
kazimuth Oct 23, 2024
36bb5bd
Consistent formatting for Timestamp and TimeDuration (please bikeshed)
kazimuth Oct 23, 2024
072c2ea
Prioritize BSATN and BFLATN compat with 0.12
gefjon Oct 30, 2024
8d9715c
Merge branch 'master' into phoebe/timestamp-special-type
kazimuth Nov 22, 2024
c50cbba
Fix extant compile error
kazimuth Nov 22, 2024
22a7355
Fix type error
kazimuth Nov 22, 2024
436cb73
Fix conflicts
kazimuth Nov 22, 2024
436c776
Merge branch 'master' into phoebe/timestamp-special-type
gefjon Jan 24, 2025
4b89003
Rework Timestamp declarations in BSATN.Runtime
kazimuth Jan 29, 2025
5f4c3aa
Start fixing sdk-test, whoops
kazimuth Jan 29, 2025
ffeadfa
Remove outdated API from tests
kazimuth Jan 30, 2025
cb81c9b
Better comments
kazimuth Feb 3, 2025
1cddd58
Merge remote-tracking branch 'origin/master' into phoebe/timestamp-sp…
gefjon Feb 4, 2025
c7c8de5
Fix smoketests
gefjon Feb 4, 2025
fe9998c
format c#
gefjon Feb 4, 2025
2950991
use timestamp in c# benchmark modules
gefjon Feb 4, 2025
dfb0e93
Apply James' suggestions
gefjon Feb 6, 2025
9f469e5
Merge remote-tracking branch 'origin/master' into phoebe/timestamp-sp…
gefjon Feb 6, 2025
0b99e1c
Merge branch 'master' into phoebe/timestamp-special-type
kazimuth Feb 6, 2025
7e12c3e
Allow adding TimeDurations to Timestamps similar to std API
kazimuth Feb 6, 2025
596a10c
Add rest of Timestamp functions to C# and purge DateTimeOffset
kazimuth Feb 6, 2025
d0b210e
Teach CLI about mysterious tildes that sometimes appear in C# bin fol…
kazimuth Feb 6, 2025
f50f238
Merge remote-tracking branch 'origin/master' into phoebe/timestamp-sp…
gefjon Feb 7, 2025
aa7abdc
Dotnet format
kazimuth Feb 7, 2025
46ee2ea
Try formatting with `dotnet csharpier` instead?
gefjon Feb 7, 2025
48b47ce
Add comment re: `bin/` and `bin~/`
gefjon Feb 7, 2025
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
728 changes: 205 additions & 523 deletions Cargo.lock

Large diffs are not rendered by default.

14 changes: 12 additions & 2 deletions crates/bindings-csharp/BSATN.Runtime.Tests/Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,22 @@ public static void NonHexStrings()
[Fact]
public static void TimestampConversionChecks()
{
ulong us = 1737582793990639;
var time = ScheduleAt.DateTimeOffsetFromMicrosSinceUnixEpoch(us);
var us = 1737582793990639L;

var time = ScheduleAt.DateTimeOffsetFromMicrosSinceUnixEpoch(us);
Assert.Equal(ScheduleAt.ToMicrosecondsSinceUnixEpoch(time), us);

var interval = ScheduleAt.TimeSpanFromMicroseconds(us);
Assert.Equal(ScheduleAt.ToMicroseconds(interval), us);

var stamp = new SpacetimeDB.Timestamp(us);
var dto = (DateTimeOffset)stamp;
var stamp_ = (SpacetimeDB.Timestamp)dto;
Assert.Equal(stamp, stamp_);

var duration = new SpacetimeDB.TimeDuration(us);
var timespan = (TimeSpan)duration;
var duration_ = (SpacetimeDB.TimeDuration)timespan;
Assert.Equal(duration, duration_);
}
}
2 changes: 2 additions & 0 deletions crates/bindings-csharp/BSATN.Runtime/BSATN.Runtime.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<!-- Note: the binary produced by this package is used in Unity too, which is limited to .NET Standard 2.1. -->
<TargetFrameworks>netstandard2.1;net8.0</TargetFrameworks>
<RootNamespace>SpacetimeDB</RootNamespace>
<!-- You can enable this when debugging codegen problems. Outputs in obj/debug/[version]/generated. -->
<!-- <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles> -->
</PropertyGroup>

<ItemGroup>
Expand Down
258 changes: 206 additions & 52 deletions crates/bindings-csharp/BSATN.Runtime/Builtins.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
namespace SpacetimeDB;

using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using SpacetimeDB.BSATN;
using SpacetimeDB.Internal;

internal static class Util
{
Expand Down Expand Up @@ -95,18 +93,26 @@ public static byte[] StringToByteArray(string hex)
return bytes;
#endif
}

// Similarly, we need some constants that are not available in .NET Standard.
public const long TicksPerMicrosecond = 10;
public const long MicrosecondsPerSecond = 1_000_000;
}

// The following types are "special" types: they has a special (Ref-less) AlgebraicType representations.
// See `spacetimedb-sats::AlgebraicType::is_valid_for_client_type_[use|generate]` for more information.
// We don't use [Type] here; instead we manually implement the serialization stuff that would be generated by
// [Type] so that we can override GetAlgebraicType to return types in a special, Ref-less form.
public readonly partial struct Unit
{
// Custom BSATN that returns an inline empty product type that can be recognised by SpacetimeDB.
public readonly struct BSATN : IReadWrite<Unit>
{
public Unit Read(BinaryReader reader) => default;

public void Write(BinaryWriter writer, Unit value) { }

public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// Return a Product directly, not a Ref, because this is a special type.
new AlgebraicType.Product([]);
}
}
Expand Down Expand Up @@ -167,6 +173,7 @@ public static Address Random()
return addr;
}

// --- auto-generated ---
public readonly struct BSATN : IReadWrite<Address>
{
public Address Read(BinaryReader reader) =>
Expand All @@ -175,8 +182,18 @@ public Address Read(BinaryReader reader) =>
public void Write(BinaryWriter writer, Address value) =>
new SpacetimeDB.BSATN.U128Stdb().Write(writer, value.value);

// --- / auto-generated ---

// --- customized ---
public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
new AlgebraicType.Product([new("__address__", new AlgebraicType.U128(default))]);
// Return a Product directly, not a Ref, because this is a special type.
new AlgebraicType.Product(
[
// Using this specific name here is important.
new("__address__", new AlgebraicType.U128(default)),
]
);
// --- / customized ---
}

public override string ToString() => Util.ToHexBigEndian(value);
Expand Down Expand Up @@ -229,100 +246,237 @@ public static Identity FromBigEndian(ReadOnlySpan<byte> bytes) =>
/// <returns></returns>
public static Identity FromHexString(string hex) => FromBigEndian(Util.StringToByteArray(hex));

// --- auto-generated ---
public readonly struct BSATN : IReadWrite<Identity>
{
public Identity Read(BinaryReader reader) => new(new SpacetimeDB.BSATN.U256().Read(reader));

public void Write(BinaryWriter writer, Identity value) =>
new SpacetimeDB.BSATN.U256().Write(writer, value.value);

// --- / auto-generated ---

// --- customized ---
public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
new AlgebraicType.Product([new("__identity__", new AlgebraicType.U256(default))]);
// Return a Product directly, not a Ref, because this is a special type.
new AlgebraicType.Product(
[
// Using this specific name here is important.
new("__identity__", new AlgebraicType.U256(default)),
]
);
// --- / customized ---
}

// This must be explicitly forwarded to base, otherwise record will generate a new implementation.
// This must be explicitly implemented, otherwise record will generate a new implementation.
public override string ToString() => Util.ToHexBigEndian(value);
}

// [SpacetimeDB.Type] - we have custom representation of time in microseconds, so implementing BSATN manually
public abstract partial record ScheduleAt
: SpacetimeDB.TaggedEnum<(TimeSpan Interval, DateTimeOffset Time)>
/// <summary>
/// A timestamp that represents a unique moment in time (in the Earth's reference frame).
///
/// This type may be converted to/from a DateTimeOffset, but the conversion can lose precision.
/// This type has less precision than DateTimeOffset (units of microseconds rather than units of 100ns).
/// </summary>
[StructLayout(LayoutKind.Sequential)] // we should be able to use it in FFI
public record struct Timestamp(long MicrosecondsSinceUnixEpoch) : IStructuralReadWrite
{
// Manual expansion of what would be otherwise generated by the [SpacetimeDB.Type] codegen.
public sealed record Interval(TimeSpan Interval_) : ScheduleAt;
public static implicit operator DateTimeOffset(Timestamp t) =>
DateTimeOffset.UnixEpoch.AddTicks(t.MicrosecondsSinceUnixEpoch * Util.TicksPerMicrosecond);

public sealed record Time(DateTimeOffset Time_) : ScheduleAt;
public static implicit operator Timestamp(DateTimeOffset offset) =>
new Timestamp(offset.Subtract(DateTimeOffset.UnixEpoch).Ticks / Util.TicksPerMicrosecond);

public static implicit operator ScheduleAt(TimeSpan interval) => new Interval(interval);
// For backwards-compatibility.
public readonly DateTimeOffset ToStd() => this;

public static implicit operator ScheduleAt(DateTimeOffset time) => new Time(time);
// Should be consistent with Rust implementation of Display.
public override readonly string ToString()
{
var sign = MicrosecondsSinceUnixEpoch < 0 ? "-" : "";
var pos = Math.Abs(MicrosecondsSinceUnixEpoch);
var secs = pos / Util.MicrosecondsPerSecond;
var microsRemaining = pos % Util.MicrosecondsPerSecond;
return $"{sign}{secs}.{microsRemaining:D6}";
}

/// <summary>
/// There are 10 C# Timestamp "Ticks" per microsecond.
/// </summary>
public static readonly ulong TicksPerMicrosecond = 10;
// --- auto-generated ---

public static ulong ToMicroseconds(TimeSpan interval)
public void ReadFields(BinaryReader reader)
{
return (ulong)interval.Ticks / TicksPerMicrosecond;
MicrosecondsSinceUnixEpoch = BSATN.MicrosecondsSinceUnixEpoch.Read(reader);
}

public static TimeSpan TimeSpanFromMicroseconds(ulong intervalMicros)
public readonly void WriteFields(BinaryWriter writer)
{
return TimeSpan.FromTicks((long)(TicksPerMicrosecond * intervalMicros));
BSATN.MicrosecondsSinceUnixEpoch.Write(writer, MicrosecondsSinceUnixEpoch);
}

public static ulong ToMicrosecondsSinceUnixEpoch(DateTimeOffset time)
public readonly partial struct BSATN : IReadWrite<Timestamp>
{
return ToMicroseconds(time - DateTimeOffset.UnixEpoch);
internal static readonly I64 MicrosecondsSinceUnixEpoch = new();

public Timestamp Read(BinaryReader reader) => IStructuralReadWrite.Read<Timestamp>(reader);

public void Write(BinaryWriter writer, Timestamp value)
{
value.WriteFields(writer);
}

// --- / auto-generated ---

// --- customized ---
public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// Return a Product directly, not a Ref, because this is a special type.
new AlgebraicType.Product(
// Using this specific name here is important.
[new("__timestamp_micros_since_unix_epoch__", new AlgebraicType.I64(default))]
);
// --- / customized ---
}
}

/// <summary>
/// A duration that represents an interval between two events (in a particular reference frame).
///
/// This type may be converted to/from a TimeSpan, but the conversion can lose precision.
/// This type has less precision than TimeSpan (units of microseconds rather than units of 100ns).
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public record struct TimeDuration(long Microseconds) : IStructuralReadWrite
{
public static implicit operator TimeSpan(TimeDuration d) =>
new(d.Microseconds * Util.TicksPerMicrosecond);

public static implicit operator TimeDuration(TimeSpan timeSpan) =>
new(timeSpan.Ticks / Util.TicksPerMicrosecond);

public static DateTimeOffset DateTimeOffsetFromMicrosSinceUnixEpoch(ulong microsSinceUnixEpoch)
// For backwards-compatibility.
public readonly TimeSpan ToStd() => this;

// Should be consistent with Rust implementation of Display.
public override readonly string ToString()
{
return DateTimeOffset.UnixEpoch + TimeSpanFromMicroseconds(microsSinceUnixEpoch);
var sign = Microseconds < 0 ? "-" : "+";
var pos = Math.Abs(Microseconds);
var secs = pos / Util.MicrosecondsPerSecond;
var microsRemaining = pos % Util.MicrosecondsPerSecond;
return $"{sign}{secs}.{microsRemaining:D6}";
}

public readonly partial struct BSATN : IReadWrite<ScheduleAt>
// --- auto-generated ---
public void ReadFields(BinaryReader reader)
{
[SpacetimeDB.Type]
private partial record ScheduleAtRepr
: SpacetimeDB.TaggedEnum<(TimeSpanRepr Interval, DateTimeOffsetRepr Time)>;
Microseconds = BSATN.__time_duration_micros__.Read(reader);
}

private static readonly ScheduleAtRepr.BSATN ReprBSATN = new();
public readonly void WriteFields(BinaryWriter writer)
{
BSATN.__time_duration_micros__.Write(writer, Microseconds);
}

public readonly partial struct BSATN : IReadWrite<TimeDuration>
{
internal static readonly I64 __time_duration_micros__ = new();

public TimeDuration Read(BinaryReader reader) =>
IStructuralReadWrite.Read<TimeDuration>(reader);

public void Write(BinaryWriter writer, TimeDuration value)
{
value.WriteFields(writer);
}

// --- customized ---
public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// Return a Product directly, not a Ref, because this is a special type.
new AlgebraicType.Product(
// Using this specific name here is important.
[new("__time_duration_micros__", new AlgebraicType.I64(default))]
);
// --- / customized ---
}
}

public partial record ScheduleAt : TaggedEnum<(TimeDuration Interval, Timestamp Time)>
{
public static implicit operator ScheduleAt(TimeDuration duration) => new Interval(duration);

public static implicit operator ScheduleAt(Timestamp time) => new Time(time);

public static implicit operator ScheduleAt(TimeSpan duration) => new Interval(duration);

public static implicit operator ScheduleAt(DateTimeOffset time) => new Time(time);

public static long ToMicroseconds(TimeSpan interval) => ((TimeDuration)interval).Microseconds;

public static TimeSpan TimeSpanFromMicroseconds(long intervalMicros) =>
(TimeSpan)(new TimeDuration(intervalMicros));

public static long ToMicrosecondsSinceUnixEpoch(DateTimeOffset time) =>
((Timestamp)time).MicrosecondsSinceUnixEpoch;

public static DateTimeOffset DateTimeOffsetFromMicrosSinceUnixEpoch(
long microsSinceUnixEpoch
) => (DateTimeOffset)(new Timestamp(microsSinceUnixEpoch));

// --- auto-generated ---
private ScheduleAt() { }

internal enum @enum : byte
{
Interval,
Time,
}

public sealed record Interval(TimeDuration Interval_) : ScheduleAt;

public sealed record Time(Timestamp Time_) : ScheduleAt;

public readonly partial struct BSATN : IReadWrite<ScheduleAt>
{
internal static readonly SpacetimeDB.BSATN.Enum<@enum> __enumTag = new();
internal static readonly TimeDuration.BSATN Interval = new();
internal static readonly Timestamp.BSATN Time = new();

public ScheduleAt Read(BinaryReader reader) =>
ReprBSATN.Read(reader) switch
__enumTag.Read(reader) switch
{
ScheduleAtRepr.Interval(var intervalRepr) => new Interval(intervalRepr.ToStd()),
ScheduleAtRepr.Time(var timeRepr) => new Time(timeRepr.ToStd()),
_ => throw new SwitchExpressionException(),
@enum.Interval => new Interval(Interval.Read(reader)),
@enum.Time => new Time(Time.Read(reader)),
_ => throw new InvalidOperationException(
"Invalid tag value, this state should be unreachable."
),
};

public void Write(BinaryWriter writer, ScheduleAt value)
{
ReprBSATN.Write(
writer,
value switch
{
Interval(var interval) => new ScheduleAtRepr.Interval(new(interval)),
Time(var time) => new ScheduleAtRepr.Time(new(time)),
_ => throw new SwitchExpressionException(),
}
);
switch (value)
{
case Interval(var inner):
__enumTag.Write(writer, @enum.Interval);
Interval.Write(writer, inner);
break;

case Time(var inner):
__enumTag.Write(writer, @enum.Time);
Time.Write(writer, inner);
break;
}
}

// --- / auto-generated ---

// --- customized ---
public AlgebraicType GetAlgebraicType(ITypeRegistrar registrar) =>
// Constructing a custom one instead of ScheduleAtRepr.GetAlgebraicType()
// to avoid leaking the internal *Repr wrappers in generated SATS.
// We are leveraging the fact that single-element structs are byte-compatible with their elements
// when parsing BSATN.
// TODO: this might break when working with other formats like JSON, but this is all going to be rewritten
// anyway with Phoebe's Timestamp PR.
// Return a Sum directly, not a Ref, because this is a special type.
new AlgebraicType.Sum(
[
new("Interval", new AlgebraicType.U64(default)),
new("Time", new AlgebraicType.U64(default)),
// Using these specific names here is important.
new("Interval", Interval.GetAlgebraicType(registrar)),
new("Time", Time.GetAlgebraicType(registrar)),
]
);
// --- / customized ---
}
}
Loading