index/db/commands/server: TTL indexes
createIndex({expireAt: 1}, {expireAfterSeconds: 60}) now deletes a
document once its indexed date is that many seconds old.
index.zig carries the option: Index.ttl (?i64), parsed from
expireAfterSeconds (int32/int64/integral double, within MongoDB's
[0, 2147483647]; 0 means "expire at the stored instant"), emitted by
spec_pairs and so persisted through the log and reported by listIndexes,
and compared by spec_equal — a same-name re-create with a different
expiry stays IndexOptionsConflict, as in MongoDB, since collMod does not
exist here. The bound keeps the value an int32 on the wire and makes the
emission cast unconditional. TTL is single-field only (a compound key is
error.TtlOnCompoundIndex); an absent option parses to null, so every
existing log record reparses unchanged.
db.zig sweeps: Engine.ttl_sweep(now_ms) walks each TTL index's entries
and deletes through the ordinary remove path, so an expiry is logged and
fsynced like any other write and holds across a restart. Expired ids are
duped before removal — remove frees the docs-map key that Entry.id
aliases — then sorted and deduped, because one document can be expired
by several entries (an array of dates expires on its earliest member,
which multikey expansion gives for free) or by several TTL indexes.
Selecting entries is a type test rather than a range lookup: bson
compare order ranks datetime above null, numbers and strings, so a
datetime upper bound would also select every value of a lesser type. A
sweep that deleted something checks the compaction threshold, since a
TTL-only workload never reaches the one in upsert.
commands.zig maps the new spec errors: CannotCreateIndex (67) for a
compound key or an out-of-range expiry, and InvalidIndexSpecificationOption
(197) for an expiry on {_id: 1}, which the idempotent _id no-op would
otherwise swallow.
server.zig runs the monitor as a member of the connection group, so the
existing group.cancel tears it down; it sleeps first, then sweeps under
the write lock, and logs rather than dies on a sweep failure.
--ttl-sweep-secs sets the interval (default 60, 0 leaves it unspawned).
Expiry is coarse by design, as in MongoDB: a document stays visible
until the next sweep, and a non-date value at the indexed path never
expires. Unit tests cover the spec round-trip and every rejection, the
sweep (inclusive cutoff, string/missing/future values untouched, second
sweep a no-op) and its survival of a reopen, and two TTL indexes over
one collection. e2e4.js exercises it through the Node driver.
This commit is contained in:
@@ -16,6 +16,10 @@ pub const Server = struct {
|
||||
connection_counter: std.atomic.Value(u32),
|
||||
engine: *db.Engine,
|
||||
start_time: std.Io.Timestamp,
|
||||
/// Seconds between TTL sweeps; 0 leaves the monitor unspawned. Signed
|
||||
/// because that is what std.Io.Duration.fromSeconds takes — the CLI
|
||||
/// rejects negatives.
|
||||
ttl_sweep_secs: i64,
|
||||
|
||||
pub fn run(self: *Server) !void {
|
||||
// Unbounded async limit: connection handlers otherwise fall back to
|
||||
@@ -36,6 +40,10 @@ pub const Server = struct {
|
||||
var group: std.Io.Group = .init;
|
||||
defer group.cancel(io);
|
||||
|
||||
// The TTL monitor is just another member of the connection group, so
|
||||
// the `group.cancel` above stops it with everything else.
|
||||
if (self.ttl_sweep_secs > 0) group.async(io, ttl_monitor, .{ io, self });
|
||||
|
||||
while (true) {
|
||||
const stream = listener.accept(io) catch |err| switch (err) {
|
||||
error.Canceled => return,
|
||||
@@ -49,6 +57,27 @@ pub const Server = struct {
|
||||
}
|
||||
};
|
||||
|
||||
/// Expire documents under TTL indexes every `ttl_sweep_secs` seconds, until
|
||||
/// the group is canceled. Sweeping takes the engine's write lock, so it is
|
||||
/// serialized with commands exactly like any other write; a sweep failure is
|
||||
/// logged rather than fatal, since the next one will retry.
|
||||
fn ttl_monitor(io: std.Io, server: *Server) error{Canceled}!void {
|
||||
const interval: std.Io.Duration = .fromSeconds(server.ttl_sweep_secs);
|
||||
while (true) {
|
||||
// Sleep first: at startup the engine has just replayed the log, and
|
||||
// an immediate sweep would race the listener's first connections for
|
||||
// the write lock.
|
||||
try std.Io.sleep(io, interval, .awake);
|
||||
try server.engine.lock();
|
||||
defer server.engine.unlock();
|
||||
const now_ms = std.Io.Timestamp.now(io, .real).toMilliseconds();
|
||||
_ = server.engine.ttl_sweep(now_ms) catch |err| {
|
||||
std.debug.print("mongo-light: TTL sweep failed: {s}\n", .{@errorName(err)});
|
||||
continue;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Entry point required by `Group.async`: must return only `error.Canceled`.
|
||||
fn handle_connection(io: std.Io, stream: std.Io.net.Stream, server: *Server) error{Canceled}!void {
|
||||
handle_connection_inner(io, stream, server) catch {};
|
||||
|
||||
Reference in New Issue
Block a user