English
DTOs and cursors
Step 1. What a service returns
Why. A service of Chatex.Core never returns an entity. It returns a DTO — a data transfer object: a small immutable record with exactly the data the caller should see. The reasons:
- Safety. A
Userentity carries the password hash, the security stamp and the lockout counter. AUserSummaryDtocarries the id, the names and whether there is an avatar. What is not in the DTO cannot leak into a JSON response by accident. - A stable contract. The entities may change with the database; the DTOs are the contract with the API and the Angular client, and change only on purpose.
- No lazy surprises. A DTO is plain data: no navigation property that is
nullbecause nobody loaded it, no change tracking.
Each feature defines its DTOs next to its service (Users/UserDtos.cs, Chats/ChatDtos.cs, …) together with commands — the records a client sends, such as RegisterCommand(UserName, Email, Password, DisplayName) — and mapping extension methods such as user.ToSummaryDto(). They appear in the topics of their features. This chapter adds the one DTO that all lists share: a page.
Step 2. Pages and opaque cursors
Why. The data layer pages with typed cursors: a Guid for messages and members, a ChatListCursor(LastActivityAt, ChatId) for the chat list (topic 5). Clients should not see those types. If the Angular client learned that a cursor is "a message id", it might start building cursors itself — and Chatex could never change the paging without breaking it.
So the business layer turns every cursor into an opaque string: a few bytes encoded with Base64Url, the variant of Base64 that is safe in URLs (- and _ instead of + and /, no = padding). The client only passes it back unchanged: GET /api/chats/{id}/messages?before=AZ4v0x.... A cursor the client tampered with is rejected with a validation error, never trusted.
Do.
cs
using System.Buffers.Binary;
using System.Buffers.Text;
using Chatex.Data.Models;
namespace Chatex.Core.Common;
/// <summary>One page of a list. Pass <see cref="NextCursor"/> back to get the next page; it is null on the last one.</summary>
public sealed record PageDto<T>(IReadOnlyList<T> Items, string? NextCursor);
internal static class Paging
{
public const int DefaultLimit = 50;
public const int MaxLimit = 100;
public static Error InvalidCursor { get; } = Error.Validation("cursor", "invalid_cursor", "The cursor is not valid.");
public static int Clamp(int? limit) => Math.Clamp(limit ?? DefaultLimit, 1, MaxLimit);
}
/// <summary>
/// Opaque cursors: clients pass them back unchanged and must not parse them, so their format can change.
/// </summary>
internal static class CursorCodec
{
private const int GuidLength = 16;
private const int ChatListLength = sizeof(long) + GuidLength;
public static string? Encode(Guid? id) =>
id is { } value ? Base64Url.EncodeToString(value.ToByteArray(bigEndian: true)) : null;
public static string? Encode(ChatListCursor? cursor)
{
if (cursor is not { } value)
{
return null;
}
Span<byte> bytes = stackalloc byte[ChatListLength];
BinaryPrimitives.WriteInt64BigEndian(bytes, value.LastActivityAt.UtcTicks);
value.ChatId.TryWriteBytes(bytes[sizeof(long)..], bigEndian: true, out _);
return Base64Url.EncodeToString(bytes);
}
/// <summary>Decodes a Guid cursor; a null or empty cursor means "first page".</summary>
public static bool TryDecode(string? cursor, out Guid? id)
{
id = null;
if (string.IsNullOrEmpty(cursor))
{
return true;
}
Span<byte> bytes = stackalloc byte[GuidLength];
if (!Base64Url.TryDecodeFromChars(cursor, bytes, out var written) || written != GuidLength)
{
return false;
}
id = new Guid(bytes, bigEndian: true);
return true;
}
public static bool TryDecode(string? cursor, out ChatListCursor? chatListCursor)
{
chatListCursor = null;
if (string.IsNullOrEmpty(cursor))
{
return true;
}
Span<byte> bytes = stackalloc byte[ChatListLength];
if (!Base64Url.TryDecodeFromChars(cursor, bytes, out var written) || written != ChatListLength)
{
return false;
}
var ticks = BinaryPrimitives.ReadInt64BigEndian(bytes);
if (ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks)
{
return false;
}
chatListCursor = new ChatListCursor(new DateTimeOffset(ticks, TimeSpan.Zero), new Guid(bytes[sizeof(long)..], bigEndian: true));
return true;
}
}PageDto<T>is what every list endpoint returns: the items and the next cursor,nullon the last page.Paging.Clampturns the limit a client asks for into 1…100, 50 by default. A client cannot ask for a million rows.CursorCodec.Encode(Guid?)writes the 16 bytes of the id in big-endian order. AGuid's default byte order mixes little- and big-endian parts; big-endian bytes match the text form of the id, so the encoding is the same on every platform.Encode(ChatListCursor?)packs two values into 24 bytes: the activity time as UTC ticks (long, 8 bytes) followed by the chat id (16 bytes).stackalloccreates the buffer on the stack — no heap allocation for a temporary 24-byte array — andSpan<byte>with ranges such asbytes[sizeof(long)..]slices it without copying.TryDecodefollows theTry…pattern of .NET: it returnsfalseinstead of throwing for bad input, because a broken cursor from a client is an expected failure. An empty cursor means "the first page". The ticks are checked against the valid range ofDateTimeOffset, because a crafted cursor could contain any 8 bytes.- The overloads differ only in the type of the
outparameter, so a call must name the type:CursorCodec.TryDecode(cursor, out ChatListCursor? after).
Check
dotnet build succeeds. Paging uses ChatListCursor from Chatex.Data.Models: the business layer may use the types of the data layer, never the other way round.