Chain: persistent mutable state
Learn how to define a TinyChain Cluster in order to host your service
In order to serve a dynamic application, you’ll have to have a way of updating your service’s persistent state. To do this you can use a Chain, a data structure which keeps track of mutations to a Collection in order to maintain the consistency of that State across every replica of a Cluster (see below for details on Cluster).
1
# from the example in test_replication.py
2
3
class Rev(tc.Cluster):
4
__uri__ = tc.URI(f"http://127.0.0.1:8702/app/test/replication")
5
6
def _configure(self):
7
# this cluster has a SyncChain called "rev"
8
self.rev = tc.Chain.Sync(0)
9
10
# this method looks up the value of "rev" within a transaction
11
@tc.get_method
12
def version(self) -> tc.Number:
13
return self.rev
14
15
# this method updates the value of "rev" within a transaction
16
@tc.post_method
17
def bump(self, txn):
18
# note: the value of "version()" must be assigned a name
19
# in order to be addressable by the instance method __add__ below
20
txn.rev = self.version()
21
return self.rev.set(txn.rev + 1)
Copied!
When you start a TinyChain host with a cluster definition, it will assume that there is a hosted cluster with the given URI (”http://…/app/test/replication” in the example above) and attempt to join that cluster as a replica. If the cluster URI has no host address, or is the same as the address of the running host, the host will serve a single replica of a new cluster. Watch out for versioning issues! In production, it’s best to end your cluster URI with a version number which you can update in order to release a new, non-backwards-compatible version with different data and methods.
Copy link