//! `zit push`: upload what the peer lacks from an existing repository.
const std = @import("std");
const ClientHoldings = zit.sync_session.ClientHoldings;
const CloneProgress = @import("sync_dialogue.zig").CloneProgress;
const PeerErrorCopy = zit.sync_session.PeerErrorCopy;
const RepoElidedSet = zit.sync_session.RepoElidedSet;
const ServerNotes = @import("sync_dialogue.zig").ServerNotes;
const SparseClassification = zit.sparse.SparseClassification;
const armBasicAuth = @import("sync_dialogue.zig").armBasicAuth;
const cli = @import("zit").cli;
const diagnostics = @import("../diagnostics.zig");
const erasurePushRows = @import("session_erasures.zig").erasurePushRows;
const erasureRefused = @import("sync_dialogue.zig").erasureRefused;
const help_pages = @import("../help.zig");
const loadClusterIndex = zit.receive.loadClusterIndex;
const logstore = @import("zit").logstore;
const max_password_len = @import("sync_dialogue.zig").max_password_len;
const noRemoteError = @import("sync_dialogue.zig").noRemoteError;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const noteLoginNotSaved = @import("sync_dialogue.zig").noteLoginNotSaved;
const notePlaintext = @import("sync_dialogue.zig").notePlaintext;
const plural = @import("sync_dialogue.zig").plural;
const pushRun = @import("sync_exchange.zig").pushRun;
const push_help = help_pages.push_help;
const readSyncCone = zit.sync_session.readSyncCone;
const readSyncCursor = zit.sync_session.readSyncCursor;
const refusePendingImport = @import("sync_dialogue.zig").refusePendingImport;
const repoReadFail = diagnostics.repoReadFail;
const repoSyncIdentity = zit.sync_session.repoSyncIdentity;
const reportPeerRefusal = @import("sync_dialogue.zig").reportPeerRefusal;
const reportTruncatedPayloads = @import("sync_dialogue.zig").reportTruncatedPayloads;
const reportUvSkipped = @import("sync_dialogue.zig").reportUvSkipped;
const resolvePushCredential = @import("sync_dialogue.zig").resolvePushCredential;
const resolveRemoteUrl = zit.sync_session.resolveRemoteUrl;
const runPull = @import("pull.zig").runPull;
const stateOom = diagnostics.stateOom;
const storePushCredential = @import("sync_dialogue.zig").storePushCredential;
const syncOpenFail = @import("sync_dialogue.zig").syncOpenFail;
const syncRunFail = @import("sync_dialogue.zig").syncRunFail;
const sync_driver = @import("../sync_driver.zig");
const transport = @import("../transport.zig");
const writeSyncCursor = zit.sync_session.writeSyncCursor;
const zit = @import("zit");
/// `zit push URL` — open the current repository, announce its holdings to the
/// peer at URL, and upload every artifact the peer lacks until §3.7 termination.
/// Thin wiring over the same deep modules pull uses: `transport` (HTTP/IO),
/// `sync.Client` + `runSync` (sans-IO §3.7 loop). With URL omitted the saved
/// remote (`zit remote`) is used; a repo with neither is a usage error.
pub fn runPush(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
verb_args: []const []const u8,
streams: cli.Streams,
amb: cli.Ambient,
) cli.Exit {
const parsed = switch (cli.parsePushArgs(verb_args)) {
.ok => |p| p,
.unknown_option => |tok| return cli.usageError(streams, "push", .unknown_option, tok),
.extra_argument => |tok| return cli.usageError(streams, "push", .extra_argument, tok),
.bad_resolve => |tok| return cli.usageError(streams, "push", .bad_resolve, tok),
.too_many_resolves => |tok| return cli.usageError(streams, "push", .too_many_resolves, tok),
};
if (parsed.help) {
streams.out.writeAll(push_help) catch {};
return .ok;
}
// sync §6.3 — a login name is a whitespace-free token (the shared-secret
// derivation embeds it between "/" separators). Reject a malformed --user
// as a usage failure rather than reaching the derivation's assertion.
if (parsed.user) |u| {
if (u.len > 0 and zit.sync.containsFossilWhitespace(u)) {
streams.err.writeAll("zit push: --user must not contain whitespace\n") catch {};
return .failure;
}
}
// Locate the current repository before any network I/O: a push outside a repo
// is a usage failure, not a wasted connection.
const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "push")) orelse {
streams.err.writeAll(not_a_repo_msg) catch {};
return .failure;
};
var root_dir = root.dir;
defer root_dir.close(io);
if (refusePendingImport(streams, io, root_dir, "push")) |rc| return rc;
// sync §4/§6 — the explicit URL wins; an omitted one falls back to the saved
// remote; a repo with neither is a usage error. `url_buf` outlives `open`.
var url_buf: [logstore.max_config_str]u8 = undefined;
const url = resolveRemoteUrl(gpa, io, root_dir, parsed.url, &url_buf) catch |e| switch (e) {
error.OutOfMemory => return stateOom(streams, "push"),
error.Storage => return repoReadFail(streams, "push"),
error.NoRemote => return noRemoteError(streams, "push"),
};
var tr = transport.Transport.open(io, gpa, url) catch |e|
return syncOpenFail(streams, "push", url, e);
defer tr.close();
tr.setResolve(parsed.resolve.slice());
notePlaintext(streams, "push", url);
// The client's holdings view — log-backed and lazy, the igot
// announcement plus the upload source: the peer requests only what it
// lacks, and only those artifacts' content materializes.
var holdings = ClientHoldings.open(gpa, io, root_dir) catch |e| switch (e) {
error.OutOfMemory => return stateOom(streams, "push"),
error.Storage => return repoReadFail(streams, "push"),
};
defer holdings.deinit(io);
var admission = holdings.admission();
// Sparse-cone RFC section 5.2 rule 3: under a store cone, classify once
// and suppress spontaneous requests for elided phantoms. Both the
// classification and the wrapper outlive the run below.
var sync_cone: ?zit.cone.Cone = null;
defer if (sync_cone) |*c| c.deinit(gpa);
var sync_classification: ?SparseClassification = null;
defer if (sync_classification) |*c| c.deinit(gpa);
var sync_elided: RepoElidedSet = undefined;
if (readSyncCone(gpa, io, root_dir, &holdings)) |c| {
sync_cone = c;
sync_classification = zit.sparse.classifyCached(gpa, io, root_dir, &holdings.index.log, holdings.index.classifyStore(), &sync_cone.?, .{}, .parse) catch
return stateOom(streams, "push");
sync_elided = .{ .classification = &sync_classification.?, .store = holdings.store() };
admission.elided = sync_elided.shunSet();
// Horizon draft section 6.2.6 -- announce only what the origin has
// not already seen, and send the cursor so the origin's reply
// announces only what it appended since.
if (readSyncCursor(gpa, io, root_dir, url, &sync_cone.?, holdings.logBackedCount())) |cur| {
admission.announce_from = cur.local + 1;
admission.horizon_cursor = cur.peer;
}
}
// §9.1 — announce this repository's adopted project code in the push card
// (same identity gate as pull; a real peer refuses a mismatch). The buffer
// outlives the run — the client borrows it.
// The cluster index: what the held clusters already announce
// (never announced again individually) and what they promised that this
// repository never collected (seeded as phantoms, so the run asks for it).
// The clusters' plaintext is memoised by the holdings adapter while it
// resolves; drop it — the index keeps only names and bits.
var clusters = loadClusterIndex(gpa, io, root_dir, &holdings.index.log, holdings.store()) catch return stateOom(streams, "push");
defer clusters.deinit();
holdings.index.releaseTransient();
var pc_buf: [zit.sync.max_projectcode_len]u8 = undefined;
const identity = repoSyncIdentity(gpa, io, root_dir, root.abs, &pc_buf) catch |e| switch (e) {
error.OutOfMemory => return stateOom(streams, "push"),
error.Storage => return repoReadFail(streams, "push"),
};
// sync §6 — resolve the login credential (null for an anonymous push). The
// password plaintext is confined to `pw_buf`/argv/env; only the derived
// 40-hex secret (§6.3) is signed with and — on success — persisted.
var pw_buf: [max_password_len]u8 = undefined;
// Defense-in-depth: once the 40-hex secret is derived the plaintext in
// pw_buf is spent, so scrub it on every exit from this scope — success and
// error alike — rather than leave it resident until the stack is reused.
defer std.crypto.secureZero(u8, &pw_buf);
var user_buf: [logstore.max_config_str]u8 = undefined;
const resolved = resolvePushCredential(gpa, io, root_dir, streams, identity.project_code, .{ .url = url, .user = parsed.user, .password = parsed.password }, amb, &pw_buf, &user_buf) catch |e| switch (e) {
error.OutOfMemory => return stateOom(streams, "push"),
error.Storage => return repoReadFail(streams, "push"),
error.NoPassword => {
streams.err.writeAll("zit push: no password supplied for --user\n") catch {};
return .failure;
},
};
var peer_error: PeerErrorCopy = .{};
const stderr_tty = std.Io.File.stderr().isTty(io) catch false;
var progress: CloneProgress = .{ .err = streams.err };
const sink: ?sync_driver.RoundSink = if (stderr_tty) .{ .ctx = &progress, .emit = CloneProgress.emit } else null;
defer progress.finishLine();
if (resolved) |r| armBasicAuth(&tr, r.credential.user, r.plaintext) catch return stateOom(streams, "push");
var notes: ServerNotes = .{};
defer notes.deinit(gpa);
var truncated: u64 = 0;
defer reportTruncatedPayloads(streams, "push", truncated);
admission.push_erasures = erasurePushRows(arena, &holdings.index.log) catch return stateOom(streams, "push");
var erasures_refused = false;
const outcome = pushRun(gpa, &tr, holdings.store(), identity, if (resolved) |r| r.credential else null, admission, &peer_error, ¬es, sink, &clusters, &truncated) catch |e| retry: {
// A peer that stated its refusal is quoted rather than flattened into
// the generic mapping — the whole point of a server-side refusal is that the operator learns
// WHICH file and WHICH rule without a second round trip.
if (e == error.FatalProtocolError) {
if (peer_error.text()) |text| {
if (erasureRefused(streams, "push", text, admission.push_erasures.len)) {
erasures_refused = true;
admission.push_erasures = &.{};
peer_error = .{};
break :retry pushRun(gpa, &tr, holdings.store(), identity, if (resolved) |r| r.credential else null, admission, &peer_error, ¬es, sink, &clusters, &truncated) catch |e2| {
if (e2 == error.FatalProtocolError) if (peer_error.text()) |t2| {
reportPeerRefusal(streams, "push", t2);
return .failure;
};
return syncRunFail(streams, "push", url, e2, &tr);
};
}
reportPeerRefusal(streams, "push", text);
return .failure;
}
}
return syncRunFail(streams, "push", url, e, &tr);
};
// DECISION-3 — persist the derived secret (never the plaintext) at 0600 only
// after the peer accepted the authenticated push, and only when it was
// freshly derived: a reused stored secret is already durable.
if (resolved) |r| {
// --once authenticates this run and saves nothing.
if (r.persist and !parsed.once) {
const saved = storePushCredential(gpa, io, root_dir, r.credential, url) catch |e| switch (e) {
error.OutOfMemory => return stateOom(streams, "push"),
else => return repoReadFail(streams, "push"),
};
if (!saved) noteLoginNotSaved(streams, "push", url);
}
}
// submanifests §7.2 — "the sender MUST refuse to transmit that artifact,
// with an explicit error -- never by converting, downgrading, or silently
// omitting it." A client cannot put an `error` card in a REQUEST (it is
// outside the §3.9 strict-accept request vocabulary), so the explicit error
// is this: the operator is told exactly what was withheld and why, and the
// run fails. Reported before the success line, because there was none.
if (outcome.refused > 0) {
streams.err.print(
"zit push: {d} artifacts were withheld: {s}\n",
.{ outcome.refused, zit.sync.submanifest_peer_error_text },
) catch {};
return .failure;
}
notes.show(streams);
if (outcome.sent == 0) {
streams.out.print("push to {s}: already in sync\n", .{url}) catch {};
} else {
streams.out.print("push to {s}: sent {d} artifact{s} in {d} round{s}\n", .{ url, outcome.sent, plural(outcome.sent), outcome.rounds, plural(outcome.rounds) }) catch {};
reportUvSkipped(streams, "push", outcome.uv_skipped);
}
// The server kept a pushed check-in on an attempt branch. Until the move
// arrives here, this repository still shows it where it was committed, and
// the next commit would build on a picture the server no longer agrees
// with; so fetch it now, from the same server.
// Horizon draft section 6.2.6 -- everything held is now announced, so the
// next push announces only what is appended after this.
if (sync_cone) |*c| writeSyncCursor(gpa, io, root_dir, url, c, .{
.peer = admission.horizon_cursor,
.local = holdings.logBackedCount(),
});
if (notes.diverted) return runPull(gpa, io, arena, &.{url}, streams, amb);
return if (erasures_refused) .failure else .ok;
}