Tenant-safe ordered lists in Laravel Rust
Source and target
Reference Spatie's MIT-licensed spatie/eloquent-sortable 5.0.1 at caf2596e5df0260d0e2863e89b750611eef2fc59: src/SortableTrait.php, interface, event, configuration, and tests. Keep MIT attribution for adapted code. Target baseline: Laravel Rust 0.1.3, 7837d40d8508957fd0e48a25d0087c851095fcc9. Check installed transaction/builder APIs rather than assuming PHP method names exist in Rust.
Check get-recipe's current port catalog; if it lists a Rust port, offer that option after verifying compatibility. This alternative ports only the used append, ordered-read, and full-list-reorder behavior into the app. It does not recreate Eloquent traits or every move/swap operation. Validate it in the target app with the checks below.
Preserve the intended contract
Upstream's creating hook assigns scoped max plus one, ordered() uses the configured order column, and setNewOrder() writes consecutive ranks in supplied ID order. The latter updates without the soft-delete global scope, can suppress timestamps, and emits a sorted event. List membership comes from app configuration/buildSortQuery() in several operations; it must become explicit in Rust.
Before coding, inventory which methods, key/position fields, list scopes, soft-delete behavior, timestamps, and event listeners the PHP app actually uses. Pin a full-list reorder contract: the submitted IDs are a permutation of the authorized current membership. Partial reorders, cross-list moves, and event payload compatibility are separate features, not implicit parity.
Implementation plan
- Reuse the position column and existing ranks. Read with typed columns in position-then-ID order. Do not create a generic sortable trait/registry; put mutations in the list's application action.
- Use the installed framework's transaction callback API. At the pinned revision,
db/transaction.rs::run_oncescopes the callback so ordinary model/builder queries on that same connection join its transaction. Explicitbegin()pluscommit()is different: use the handle directly or itsscope()callback to bind ordinary queries. Keep all writes on that connection and inside the scoped callback; spawned tasks or another connection must not escape the transaction. Verify binding with a forced-rollback test rather than assuming an API from another Rust ORM. - On PostgreSQL/MySQL, lock the authorized parent row with the builder's
lock_for_update()before reading membership. Recheck tenant ownership under the lock. The parent serializes empty lists too. Every mutation path—append, delete, restore, transfer, reorder—must participate in this same lock protocol. SQLite requires its own write-serialization strategy; do not describe a no-op row lock as concurrency proof. - Bound list length, reject duplicate/nonpositive IDs, and compare the submitted ID set with all authorized current member IDs under the lock. Complete validation before writing. Define active/soft-deleted membership explicitly; a tenant filter alone is not proof an ID belongs to this list.
- Update each member's position to its one-based input index, with fixed columns and parent scope on every update. Check affected counts. Existing immediate unique position constraints require staging all involved rows into a checked disjoint rank range before final values, or an explicitly reviewed deferrable constraint. Check overflow before reserving temporary ranks. Do not silently drop constraints.
- Append under the same parent lock using scoped max plus one. Preserve timestamps deliberately. Emit any domain notification after a successful commit, not from the middle of the assignment loop.
Example read ordering, assuming the app's model and a previously authorized/scoped builder:
let rows = query
.order_by(Item::position.asc())
.order_by(Item::id.asc())
.get()
.await?;
The model names are placeholders for the app's existing entities. A builder for a read outside the transaction is not a template for transaction-bound writes.
Verification in the real app
Use list A [11, 24, 39] and list B [50]; reorder A to [39, 11, 24] and assert the exact visible order, ranks, and unchanged B.
- Reject duplicates, omitted IDs, foreign-list/tenant IDs, invalid positions, and oversized payloads before mutation.
- Fail the second rank update and verify rollback using a fresh connection. This detects writes outside the transaction's task/connection scope.
- Race two different reorders and append-versus-reorder on independent production-driver connections. Require a complete serial outcome, not merely unique IDs in memory.
- Cover an empty list, ties in legacy data, soft-delete/restore policy, unique-rank swaps, overflow bounds, and post-commit notification delivery.
Run formatting, strict Clippy, and targeted cargo test integration tests with the target app's PostgreSQL/MySQL connection. A green SQLite-only test cannot establish row-lock behavior. Record the exact framework version, transaction-binding method, and observed concurrency outcomes before cutover; retain the package/old path until that evidence exists.