What Morphium Offers

Several workers compete for the same tickets and for one lease. The update must be decided by the database in one command: a worker that reads "NEW" and then writes "RUNNING" loses against another one in between. Query.modify() builds one atomic update with the field names translated, the values mapped like store() maps them, @LastChange set, and a typed outcome (UPDATED, NOT_MATCHED, DUPLICATE_KEY) instead of a null that can mean three things.

The Challenge

With 6.x, a write that the server rejected (a unique index, a path below a scalar) returned as if it had happened, and a hand-built findAndModify map needed Date.from(...), snake_case keys and a hand-made duplicate key check. In 7.0 a rejected write raises a MorphiumDriverException, and the typed API does the rest.

Morphium Features Used

Query.modify() One atomic update with set, inc, push, rename, min, max and more. Nothing is written until findOneAndUpdate, tryFindOneAndUpdate, updateOne or updateMany is called. Field names are Java names, enum constants, Lombok field constants or dotted paths; the builder translates them to the stored names. MongoDBAtlasCosmosDB UpdateOutcome The typed result of tryFindOneAndUpdate: UPDATED, INSERTED, NOT_MATCHED or DUPLICATE_KEY (the lost conditional upsert), with the document. MongoDBAtlasCosmosDB LeaseManager A lease as one conditional upsert: acquire, renew by the same owner, take over after the expiry, release. A fencing token and a key other than the id are builder options. MongoDBAtlasCosmosDB updateBy... methods Derived update methods of Jakarta Data repositories (a Morphium extension): the name after updateBy is the condition, every parameter after the condition is a field to set. long or boolean gives the count form, the entity or an Optional the find-and-modify form. MongoDBAtlasCosmosDB Rejected writes raise Since 7.0 a statement that the server rejects (duplicate key, $pull on a non-array) throws a MorphiumDriverException: getMongoCode(), isDuplicateKey(), getWriteErrors(). Query.setRaiseOnWriteErrors(false) is the override for one best-effort query. MongoDBAtlasCosmosDB @LastChange on the field A @LastChange that sits on the field only is set by store(), the update builder and, since 7.0, the writer methods (Query.set, inc, push, ...). MongoDBAtlasCosmosDB

Claiming a ticket

The condition (state = NEW) and the change are one command; exactly one of two workers wins.

Claiming a ticket Java
UpdateOutcome<JobTicket> outcome = morphium.createQueryFor(JobTicket.class)
        .f(JobTicket.Fields.id).eq(ticketId)
        .f(JobTicket.Fields.state).eq(JobState.NEW)
        .modify()
        .set(JobTicket.Fields.state, JobState.RUNNING)       // an enum, stored by name
        .set(JobTicket.Fields.owner, worker)
        .set(JobTicket.Fields.startedAt, Instant.now())      // an Instant, stored as a date
        .inc(JobTicket.Fields.attempts, 1)
        .tryFindOneAndUpdate(ReturnDocument.AFTER);

switch (outcome.getKind()) {
    case UPDATED     -> /* this worker won, outcome.getDocument() is the ticket */;
    case NOT_MATCHED -> /* somebody else was faster, or the ticket does not exist */;
}

A lease

Lease Java
LeaseManager<WorkLease> leases = LeaseManager.of(morphium, WorkLease.class, "ownerName", "expiresAt");
LeaseResult<WorkLease> result = leases.tryAcquire("nightly-import", worker, Duration.ofSeconds(60));
if (result.isAcquired()) { /* the lease is held until result.getLease().getExpiresAt() */ }
leases.release("nightly-import", worker);

Derived update methods

JobTicketRepository Java
@Repository
public interface JobTicketRepository extends BasicRepository<JobTicket, String> {
    long updateByState(JobState state, @Param("owner") String owner);                         // updateMany
    Optional<JobTicket> updateByIdAndState(String id, JobState state, @Param("owner") String owner);  // findAndModify
}

A rejected write

Rejected write Java
try {
    query.f("id").eq(ticketId).set("code", newCode);          // the code has a unique index
} catch (MorphiumDriverException e) {
    if (e.isDuplicateKey()) { /* 6.x ignored the reply of the server and returned as if it had written */ }
}

Related Documentation