Names psync knows
psync reads tokens, not types, so much of what it decides comes from names: a method called
delete_pod writes, a call to sleep is a barrier, len does not change its receiver. This page
shows every such list, included straight from the source when the book is built, so it is always
the list psync uses. Each list is a Rust constant; the comment above it says what it is for.
You can extend the verb lists for your own API with
#[psync::graph(effects(read(..), write(..), ordered(..)))] (Attributes), mark a
whole function with calls = .., or mark one statement with a hint. To change a list for
everyone, see Adding an effect rule: every list change needs a
test.
How a name is matched
For the verbs (the first three lists), psync takes the called method’s name, and its first
word: the name with a leading try_ or async_ removed, cut at the first _. The name matches
a list when either the whole name or its first word is in it. delete_namespaced_pod has the first
word delete, a write verb; try_send has send, an ordered verb; list_objects_v2 has
list, a read verb. The lists are tried in this order, and the first match wins:
- your
ordered(..), then yourwrite(..), then yourread(..); - the Redis commands (ordered, then writes, then reads);
- the ordered verbs, then the write verbs, then the read verbs.
An HTTP method (Method::GET) and an SQL statement or Redis command given as a literal decide
before any of these.
A name in none of them is unclassified: the call is taken as a read, or as a write with
strict or calls = write, and the explanation lists it. In a method chain, the first verb decides
(client.get(url).header(..).send() reads).
The other lists match a method or macro name exactly, except the read prefixes, which match the start of a method name.
Service verbs (effects.rs)
Used for any awaited call that is not a file, network, environment, process or SQL operation.
/// First words of names that read.
const READ_VERBS: &[&str] = &[
"get",
"head",
"list",
"fetch",
"read",
"load",
"query",
"select",
"find",
"lookup",
"describe",
"stat",
"exists",
"search",
"resolve",
"download",
"retrieve",
"watch",
"scan",
"count",
"check",
"peek",
"options",
"metadata",
"open",
"inspect",
"show",
"info",
"status",
"health",
"ping",
"poll",
"receive",
"batch_get",
"is",
"has",
"try_exists",
"canonicalize",
"verify",
"validate",
"connect",
"probe",
"discover",
];
/// First words of names that write.
const WRITE_VERBS: &[&str] = &[
"create",
"insert",
"put",
"post",
"patch",
"delete",
"del",
"remove",
"rm",
"update",
"replace",
"upsert",
"set",
"write",
"rename",
"copy",
"upload",
"execute",
"exec",
"commit",
"rollback",
"spawn",
"kill",
"apply",
"merge",
"truncate",
"drop",
"evict",
"invalidate",
"purge",
"register",
"unregister",
"grant",
"revoke",
"restart",
"scale",
"cancel",
"transfer",
"incr",
"increment",
"decr",
"decrement",
"save",
"store",
"persist",
"flush",
"sync",
"mark",
"reset",
"clear",
"add",
"modify",
"edit",
"approve",
"reject",
"submit",
"deploy",
"install",
"uninstall",
"mkdir",
"rmdir",
"unlink",
"chmod",
"chown",
"touch",
"link",
"symlink",
"compact",
"migrate",
"seed",
"move",
"mv",
"claim",
"release",
"renew",
"expire",
"lease",
"start",
"stop",
"terminate",
"shutdown",
"close",
"run",
"invoke",
"call",
"trigger",
"charge",
"refund",
"pay",
"mint",
"burn",
"sign",
"issue",
"reserve",
"allocate",
"free",
"destroy",
"provision",
"attach",
"detach",
"mount",
"unmount",
"bind",
"unbind",
];
/// First words of names whose relative order is observable on one domain.
const ORDERED_VERBS: &[&str] = &[
"send",
"append",
"push",
"publish",
"enqueue",
"emit",
"notify",
"ack",
"nack",
"pop",
"dequeue",
"broadcast",
"log",
"produce",
"write_all",
"feed",
];
Redis (effects.rs)
The redis crate’s methods are named after the commands, and most command names are not verbs.
These lists are tried before the verbs, by the whole name or its first word, so get_del (which
deletes) is a write. A redis::cmd("..") with a literal command is looked up here and then in the
verbs; one psync cannot read is a write. See Side effects.
/// Redis commands, as the `redis` crate names its methods (`con.hget(k, f)`, `con.get_del(k)`)
/// and as `redis::cmd("HGET")` names them. Matched by the whole name or its first word, before
/// the verbs: `get_del` deletes, though its first word reads.
const REDIS_READS: &[&str] = &[
"hget",
"hgetall",
"hmget",
"hkeys",
"hvals",
"hlen",
"hexists",
"hstrlen",
"mget",
"lrange",
"llen",
"lindex",
"lpos",
"smembers",
"sismember",
"smismember",
"scard",
"srandmember",
"sdiff",
"sinter",
"sunion",
"zrange",
"zrevrange",
"zrangebyscore",
"zrevrangebyscore",
"zscore",
"zmscore",
"zcard",
"zrank",
"zrevrank",
"zcount",
"zlexcount",
"ttl",
"pttl",
"strlen",
"getrange",
"keys",
"xrange",
"xrevrange",
"xlen",
"xread",
"pfcount",
"bitcount",
"getbit",
"geopos",
"geodist",
"georadius",
"dbsize",
"randomkey",
];
const REDIS_WRITES: &[&str] = &[
"hset",
"hsetnx",
"hmset",
"hdel",
"hincr",
"hincrby",
"mset",
"msetnx",
"setex",
"setnx",
"psetex",
"getset",
"getdel",
"get_del",
"getex",
"get_ex",
"setrange",
"setbit",
"sadd",
"srem",
"spop",
"smove",
"sdiffstore",
"sinterstore",
"sunionstore",
"zadd",
"zrem",
"zincr",
"zincrby",
"zpopmin",
"zpopmax",
"zremrangebyscore",
"zremrangebyrank",
"lset",
"ltrim",
"linsert",
"lrem",
"pexpire",
"expireat",
"pexpireat",
"pfadd",
"pfmerge",
"geoadd",
"xtrim",
"xdel",
"xgroup",
"flushdb",
"flushall",
"renamenx",
];
/// Commands whose order on one key is visible: list pushes and pops, stream appends.
const REDIS_ORDERED: &[&str] = &[
"lpush",
"rpush",
"lpushx",
"rpushx",
"lpop",
"rpop",
"blpop",
"brpop",
"rpoplpush",
"brpoplpush",
"lmove",
"blmove",
"xadd",
"xack",
"xreadgroup",
];
Files and the network (effects.rs)
A call through fs, File, OpenOptions or DirBuilder reads if its last path segment is in
FS_READS (and it is not built with OpenOptions), and writes otherwise. A method of a
Path with no arguments reads the file system when it is in PATH_FS_READS. A call through
TcpStream, UdpSocket, TcpListener, UnixStream or net writes if its last segment is in
NET_WRITES, and reads otherwise.
/// File-system functions (last path segment) that only read.
const FS_READS: &[&str] = &[
"read",
"read_to_string",
"read_dir",
"metadata",
"symlink_metadata",
"canonicalize",
"read_link",
"try_exists",
"exists",
"open",
];
/// Methods of `std::path::Path` without arguments that read the file system at the path.
const PATH_FS_READS: &[&str] = &[
"exists",
"try_exists",
"is_file",
"is_dir",
"is_symlink",
"metadata",
"symlink_metadata",
"read_dir",
"read_link",
"canonicalize",
];
/// Network functions that write (send data); the rest of `net` only connects or reads.
const NET_WRITES: &[&str] = &["send_to", "send", "write", "write_all"];
SQL statements (effects.rs)
For a call that runs SQL from a string literal, the statement’s first word decides (a WITH is
read through to the statement it introduces). Any word of SQL_WRITE_WORDS in a reading statement
makes it a write. A first word in neither list, or a statement psync cannot read, is a write.
/// Statements that only read, by their first word. `EXPLAIN` without `ANALYZE` only plans.
const SQL_READS: &[&str] = &[
"SELECT", "SHOW", "EXPLAIN", "DESCRIBE", "DESC", "VALUES", "TABLE", "PRAGMA",
];
/// Statements that change the database or the session, by their first word.
const SQL_WRITES: &[&str] = &[
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"UPSERT",
"REPLACE",
"CREATE",
"DROP",
"ALTER",
"TRUNCATE",
"GRANT",
"REVOKE",
"COPY",
"CALL",
"EXEC",
"EXECUTE",
"DO",
"LOCK",
"BEGIN",
"START",
"COMMIT",
"ROLLBACK",
"SAVEPOINT",
"RELEASE",
"SET",
"RESET",
"VACUUM",
"ANALYZE",
"REINDEX",
"CLUSTER",
"REFRESH",
"COMMENT",
"DISCARD",
"LISTEN",
"NOTIFY",
"UNLISTEN",
"PREPARE",
"DEALLOCATE",
"ATTACH",
"DETACH",
"LOAD",
"IMPORT",
];
/// Words that make a reading statement write or lock: `SELECT .. FOR UPDATE`, `SELECT .. INTO`,
/// `nextval(..)`, a data-modifying `WITH`, `EXPLAIN ANALYZE` (which runs the statement).
const SQL_WRITE_WORDS: &[&str] = &[
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"INTO",
"NEXTVAL",
"SETVAL",
"LOCK",
"ANALYZE",
"PG_ADVISORY_LOCK",
"PG_ADVISORY_XACT_LOCK",
"GET_LOCK",
];
Reads and writes of variables (access.rs)
A method call on a variable that is mut (or a handle such as &mut) writes the variable,
unless the method is in PURE_METHODS or starts with one of READ_PREFIXES. A method in
ORDERED_METHODS writes its receiver whatever the receiver is, even through &self: a channel
or a socket changes when you use it. See Reads and writes from tokens.
/// Methods assumed not to mutate their receiver.
pub(crate) const PURE_METHODS: &[&str] = &[
"clone",
"to_string",
"to_owned",
"into",
"as_ref",
"as_str",
"as_slice",
"len",
"is_empty",
"unwrap_or",
"unwrap_or_default",
"as_deref",
"iter",
"to_vec",
"copied",
"cloned",
"is_some",
"is_none",
];
/// Prefixes of further read-only method names (`is_*`, `get*`, `as_*`, ...).
const READ_PREFIXES: &[&str] = &[
"is_",
"has_",
"get",
"as_",
"to_",
"contains",
"len",
"iter",
"keys",
"values",
"first",
"last",
"count",
"unwrap",
"expect",
"starts_with",
"ends_with",
"clone",
"map",
"ok",
"err",
"list",
"fetch",
"find",
"load",
"query",
"lookup",
"describe",
"stat",
"head",
"exists",
"search",
"resolve",
"download",
"retrieve",
];
/// Calls whose relative order is observable even through `&self`: channel, stream and I/O
/// operations on one receiver must stay in program order.
const ORDERED_METHODS: &[&str] = &[
"send",
"send_all",
"try_send",
"recv",
"try_recv",
"next",
"try_next",
"feed",
"write",
"write_all",
"flush",
"read_exact",
"read_to_end",
"read_to_string",
"shutdown",
"close",
"execute",
"commit",
"rollback",
];
Barriers and blocking calls (classify.rs)
A statement that awaits one of GUARD_AWAITS and keeps the guard, awaits one of DELAY_AWAITS,
or calls one of CLOCK_CALLS (outside closures and async blocks) is a barrier: it keeps its
place. In a synchronous function, so is a let whose value calls one of GUARD_METHODS with no
arguments (let g = m.lock().unwrap();): the guard is held afterwards. The early-exit
macros bail!, ensure!, try!, return_err! and fail! are exits. See
Classifying statements.
A statement using one of AWAITING_MACROS is a barrier too, and its effects are unknown writes:
the macro awaits calls psync cannot see (Cancellation, timeouts and
select!).
/// Macros that await the futures they are given, with no `.await` in their tokens
/// (`tokio::select!`, `futures::join!`). psync cannot see the calls inside them, so a statement
/// using one is a barrier, and its effects are unknown writes.
pub(crate) const AWAITING_MACROS: &[&str] = &["select", "select_biased", "join", "try_join"];
/// Awaited operations that acquire something held afterwards (a lock, permit or transaction).
/// A statement that keeps the guard is a barrier; one that drops it inside a nested block (its own
/// critical section) may still move, since the lock itself keeps mutual exclusion.
const GUARD_AWAITS: &[&str] = &[
"lock",
"lock_owned",
"read",
"write",
"acquire",
"acquire_owned",
"acquire_many",
"begin",
"transaction",
];
/// Deliberate delays: their position is the point. Statements awaiting these are barriers.
const DELAY_AWAITS: &[&str] = &["sleep", "sleep_until", "tick", "yield_now", "delay_for"];
/// Clock reads (`Instant::now()`, `started.elapsed()`): when they run relative to the waits
/// around them is what they measure, so statements making them are barriers.
const CLOCK_CALLS: &[&str] = &["now", "elapsed", "duration_since"];
/// Methods whose result, bound by a `let`, is a guard held afterwards (synchronous locks and
/// `RefCell` borrows; `read` and `write` only without arguments, as on `RwLock`).
const GUARD_METHODS: &[&str] = &["lock", "try_lock", "borrow", "borrow_mut", "read", "write"];
In synchronous code (Phase II) a statement blocks, and so plays the part of
an await, when it names one of NET_PATHS (or reqwest::blocking) and calls one of
NET_WAITS, or builds a Command and calls one of PROCESS_WAITS.
/// Synchronous calls that wait on the network or a process (Phase II): in a synchronous function,
/// a statement making one plays the part of an await. A statement blocks when it names one of
/// these paths *and* calls one of the methods that wait: `Command::new("git")` builds a command,
/// `.output()` runs it, and `Command::Reply` or clap's `Command::parse_from` are no process at all.
/// `reqwest` counts only through `reqwest::blocking`.
const NET_PATHS: &[&str] = &["ureq", "TcpStream", "UdpSocket"];
const NET_WAITS: &[&str] = &[
"connect",
"call",
"send",
"send_to",
"recv",
"recv_from",
"read_to_end",
"read_to_string",
"read_exact",
];
const PROCESS_WAITS: &[&str] = &["output", "status", "wait", "wait_with_output"];
Pure code (classify.rs, loops.rs)
Logging macros are treated as pure, so a debug! between two awaits does not split them. The pure
macros build values. TOTAL_METHODS are the methods an expression may call and still be
evaluated ahead of a loop for every item (to compute a file path for a run-time check).
/// Logging statements: treated as pure so they do not split regions.
const LOG_MACROS: &[&str] = &["trace", "debug", "info", "warn", "error", "log"];
/// Macros that build values without side effects.
const PURE_MACROS: &[&str] = &["format", "vec", "concat", "stringify"];
/// Methods whose call on a total receiver neither panics nor touches anything: what a file
/// path is usually built with.
const TOTAL_METHODS: &[&str] = &[
"clone",
"to_string",
"to_owned",
"as_ref",
"as_str",
"as_path",
"as_os_str",
"to_path_buf",
"join",
"with_extension",
"with_file_name",
"path",
];
Hints (classify.rs)
The attribute names psync reads on statements, as #[psync::NAME] (only graph may also be written bare, when imported)
(Hints):
/// The hint attributes psync reads and removes from its output.
pub(crate) const HINTS: &[&str] = &["seq", "fresh", "independent", "speculate", "par"];
Exercises
- Is
client.try_publish_batch(msgs).awaita read, a write or an ordered write? Andstore.fetch_or_create(key).await? let n = queue.len();andqueue.drain(..);both use amut queue. Which writesqueue?- In a synchronous function, which of these is a barrier:
let t = Instant::now();,let g = m.lock().unwrap();,let s = name.to_string();?
Answers
try_publish_batchlosestry_, and its first word ispublish: an ordered write.fetch_or_createhas the first wordfetch, a read verb, so psync takes it as a read. The name misleads: it may create. Your own lists are tried first and match whole names, so#[psync::graph(effects(write(fetch_or_create)))]makes it a write.lenis inPURE_METHODS, so it reads.drainis in no list and does not start with a read prefix, so on amutvariable it writes.- The first (a clock call) and the second (a lock guard bound with
let).to_stringis pure.