Breaking changes
This chapter will describe significant changes introduced in major version releases of Karton. Versions before 4.0.0 were not officially released, so they have value only for internal purposes. Don’t worry about it if you are a new user.
What is changed in Karton 6.0.0
Note
Migration instructions can be found in Migration to Karton 6.x chapter.
Version 6.0.0 breaks compatibility with Karton 4.x and older. Before upgrade, ensure that your services are using at least karton-core 5.0.0.
Karton service code shouldn’t require any changes to migrate to 6.x. The breaking changes are internal, so they may require attention only if your code operates directly on the Karton Backend.
Version 6.0.0 introduces a new type of backend API called the Karton Gateway API. Karton services communicate via a Websocket/REST API server (called the Karton Gateway Server) instead of direct calls to the Redis database. Resources are exchanged via S3 presigned URLs issued by the Karton Gateway, so no direct S3 authentication is needed.
Karton Gateway is considered the primary backend going forward. The Redis-based interface (called “Direct backend”) still works but is considered legacy, and users are encouraged to migrate to the Gateway-based setup.
The Karton Gateway Server is a separate service shipped within this package and runs as a FastAPI/gunicorn application. Install it together with the extra dependencies:
pip install karton-core[gateway]
Python and dependencies
Python 3.12 or newer is now required.
New runtime dependencies were added:
httpx2,pydanticandwebsocketsto support the Gateway backend implementation. The Gateway Server additionally requiresfastapi,pyjwtandgunicorn(provided by thegatewayextra).
Configuration
The
[gateway]configuration section selects the Gateway backend. It is mutually exclusive with the[redis],[minio]and[s3]sections: defining[gateway]alongside any of them raises aRuntimeErrorat startup. A singlekarton.inimust use either the Gateway or the Direct backend, not both.Client-side
[gateway]section:[gateway] url = ws://gateway.example.com:8000/gateway auth_tokens = ... ; optional: s3_hostname_override = gateway.example.com:9000 retries = 5 retry_base_timeout = 2 retry_jitter = 1 connect_timeout = 5 response_timeout = 5
Server-side
[gateway-server]section (used by the Gateway Server process):[gateway-server] secret_key = ... ; at least 64 characters allowed_foreign_buckets = bucket-one,bucket-two ; comma-separated, not JSON
Backend and service identity
Backends should now be obtained via the
get_backend()factory instead of being constructed directly.get_backend(config, service_info)inspects the configuration and returns the matching implementation: aKartonGatewayBackendwhen a[gateway]section is present, or aKartonBackend(Direct) otherwise.KartonBaseandKartonAsyncBasealready do this internally via the_backend_factoryclass attribute, so most services need no change.from karton.core.backend import get_backend, KartonServiceInfo service_info = KartonServiceInfo.create( identity="karton.my-service", ) # Preferred: let the factory pick the right backend for the configuration backend = get_backend(config, service_info=service_info)
karton.core.backendhas been turned from a single module into a package. The Direct backend class now lives inkarton.core.backend.direct(KartonBackendremains re-exported fromkarton.core.backendfor backwards compatibility). New names exported from the package:KartonBackendProtocol– atyping.Protocoldescribing the backend interface used by producers and consumers, so they no longer depend on a concrete implementation. Code that accepts a backend should type it asKartonBackendProtocolrather than the concreteKartonBackend.KartonGatewayBackend– the Gateway-backed implementation of the protocol.
Constructing a backend directly (e.g.
KartonBackend(config, service_info=...)) is still possible but discouraged in favor ofget_backend(). If you do construct one directly, note that theKartonBackend.__init__signature changed: theidentityargument was removed in favor of the now-requiredservice_info:- backend = KartonBackend(config, identity="karton.my-service") + backend = get_backend( + config, + service_info=KartonServiceInfo.create( + identity="karton.my-service", + ), + )
In practice, you rarely construct a backend or
service_infoyourself:KartonBase/KartonAsyncBasebuildservice_infofrom the serviceidentityandversionautomatically. If you pass a custombackendto a service constructor, it must now be aKartonBackendProtocolrather than the concreteKartonBackendclass.KartonServiceInfogained a requiredinstance_idfield (a unique identifier per running service instance) used to deduplicate connections from the same replica, and now validates theidentity(raiseskarton.core.exceptions.InvalidIdentityErroron empty strings or characters from{" ", "?"}). Use theKartonServiceInfo.create()classmethod to construct one with a randomly generatedinstance_idinstead of passing it manually.The
with_service_infoclass attribute onKartonBase/KartonAsyncBasehas been removed. Service information is always populated, so enabling it explicitly is no longer necessary. Theresolve_service_info()helper has been removed as well.The asyncio backend was restructured to mirror the sync one:
karton.core.asyncio.backendis now a package (backend/{base,direct,gateway}.py).karton.core.asyncio.KartonGatewayBackendwas renamed toKartonAsyncGatewayBackend, and a matchingget_backend()factory andKartonAsyncBackendProtocolare exported fromkarton.core.asyncio.backend.KartonState.replicasis now populated viaget_online_identities(), which returns aDict[str, List[KartonExternalServiceInfo]].KartonExternalServiceInfois a new dataclass representing services observed online (parsed from Redis/Gateway), distinct fromKartonServiceInfo, which describes the local service. The previousget_online_consumers()behavior (returningDict[str, List[Dict[str, str]]]) is superseded by this typed representation.
Resources
RemoteResource.remove()has been removed.ResourceBase._flagshas been removed.Removed redundant
metadata.sha256from serialized__karton_resource__dictionary. Now SHA256 is serialized only intosha256key.Backend object-storage methods were renamed to operate on resource objects rather than
(bucket, uid)pairs:- backend.upload_object(bucket, uid, content) + backend.upload_resource(resource, content) - backend.upload_object_from_file(bucket, uid, path) + backend.upload_resource_from_file(resource, path) - backend.download_object(bucket, uid) + backend.download_resource(resource) - backend.download_object_to_file(bucket, uid, path) + backend.download_resource_to_file(resource, path)
Tasks
Removed
parse_resourcesflag fromTask.unserialize().resource_unserializerset to None should be used instead (it’s a default value)Tasks are always deserialized using
orjson(with fallback to Pythonjsonin case of errors). In 5.xorjsonwas used only when tasks were unserialized withparse_resourcesset toFalse.
Consumer behavior
Bind-change detection no longer relies on polling
get_bind()against the localself._bind. Instead,consume_routed_task()raises the newkarton.core.exceptions.BindExpiredErrorwhen the bind has been overridden by a newer service version. Consumers catch this to shut down gracefully. Custom backend subclasses implementingconsume_routed_taskshould raiseBindExpiredErroraccordingly.
Minor changes
KartonBackend.get_bind()now returnsNonewhen a bind is not found, instead of raising an exception while unserializing a missing entry. Callers should handle theNonecase.KartonBindis now a frozendataclasses.dataclassinstead of acollections.namedtuple. Field access by name is unchanged, but code that relied on the namedtuple’s tuple interface (e.g. positional unpacking) needs to be updated.
What is changed in Karton 5.0.0
Karton-System and core services are still able to communicate with previous versions.
Changed name of
karton.inisection that contains S3 client configuration from[minio]to[s3].In addition to this, you need to add a URI scheme to the
addressfield and remove thesecurefield. Ifsecurewas 0, correct scheme ishttp://. Ifsecurewas 1, usehttps://.- [minio] + [s3] access_key = karton-test-access secret_key = karton-test-key - address = localhost:9000 + address = http://localhost:9000 bucket = karton - secure = 0
v5.0.0 maps
[minio]configuration to correct[s3]configuration internally, but[minio]scheme is considered deprecated and can be removed in further major release.Karton library uses Boto3 library as a S3 client instead of Minio-Py underneath. You may want to check if your code relies on exceptions thrown by previous S3 client.
karton.core.Configinterface is changed.config,minio_configandredis_configattributes are no longer available.We noticed lots of issues caused by calling factory method
main()on instance instead of class, which can be misleading (:py:meth:karton.core.base.KartonBase.mainactually creates own instance of Karton service internally, so the initialization is doubled). To notice these errors more quickly, we preventedmain()call onKartonBaseinstanceif __name__ == "__main__": MyConsumer.main() # correct if __name__ == "__main__": MyConsumer().main() # throws TypeError
karton.core.Consumer.processno longer accepts no arguments. First argument of this method is the incoming task.
# Correct
class MyConsumer(Karton):
def process(self, task: Task) -> None:
...
# Wrong from v5.0.0
class MyConsumer(Karton):
def process(self) -> None:
...
What is changed in Karton 4.0.0
Karton-System and core services are still compatible with both 3.x and 2.x versions.
SHA256is evaluated always whenResourceis created. If you already know it and don’t want it to be recalculated, pass the hash to the constructor viasha256=argument.sample = Resource(path="sample.exe", sha256="2e5d...")
DirectoryResourcehas been removed in favor ofResource.from_directory. Resources created using this method are still deserialized to theRemoteDirectoryResourceform by older Karton versions.RemoteDirectoryResourcehas been merged intoRemoteResource, so all resources containing Zip files can be unzipped even if they were created as regular files.Asynchronous tasks has been removed. Busy waiting should be used instead.
All crashed tasks are preserved in
Crashedstate until they are removed by Karton-System (default is 72 hours) or retried by user. Keep in mind that they hold all the referenced resources, so keep an eye on that queue.
What is changed in Karton 3.0.0
Karton-System and other core services in 3.x are compatible with 2.x. But if you want to use 3.x in Karton service code, all core services need to be upgraded first.
The good news:
Karton subsystems expose the library version and class docstring in
karton.bindsConfig is explicit and get by default from
karton.inifile (yup, it’skarton.ininotconfig.ini). But you can still provide another path if you want.There is no need to provide a suffix
".test"as a part of identity for non-persistent consumer queues. Just setpersistent=Falsein your Karton subsystem classYou can provide
identityas an argument.
So, instead of that code:
# Consumer part
class Subsystem(Karton):
identity = "karton.subsystem.test"
filters = {...}
config = Config("config.ini")
subsystem = Subsystem(config).loop()
# Producer part
class NamedProducer(Producer):
identity = "karton.named-producer"
config = Config("config.ini")
producer = NamedProducer(config).send_task(...)
You can write that code:
# Consumer part
class Subsystem(Karton):
identity = "karton.subsystem"
filters = {...}
persistent = False
subsystem = Subsystem().loop()
# Producer part
producer = Producer(identity="karton.named-producer").send_task(...)
The bad news (for porting):
Resource classes are completely reworked.
Resources are strictly divided to local (uploadable) and remote (downloadable) ones. The inheritance structure is different than in 2.x, so check the API first.
There is no
sha256field, butmetadatadictionary instead. For compatibility reasons: we exposesha256from Karton 2.x asmetadata["sha256"]and back. New subsystems should not rely on that behavior.flagsare also not exposed.Removed
is_directorymethod.If you need to check whether your resource is directory, use
isinstance(resource, DirectoryResourceBase)instead.Remote resources are now lazy-objects bound with MinIO, so we can directly get the contents instead of using proxy methods.
Code from 2.x:
sample = self.current_task.get_resource("sample") # Calling Consumer method to get local version of resource local_sample = self.download_resource(sample) # Get the contents sample_content = local_sample.content
must be ported to:
sample = self.current_task.get_resource("sample") # Contents will be lazy-loaded # If you want to download them directly: use sample.download() sample_content = sample.content
All related
Consumermethods likedownload_resource()ordownload_to_temporary_folder()are completely removed. These methods were incomplete and inconsistent, especially for directories. Now, the whole power behind the Resource features is available directly via object methods.Removed
PayloadBagwrappers with resource iterator methods. They provided additional level of complexity without adding new capabilities. There are classic dictionaries in place of them.
Task classes also changed a bit
payload_contains()is renamed tohas_payload()and doesn’t check only non-persistent payload existence, but includes persistent payloads as well.persistent_payload_contains()is renamed tois_payload_persistent()get_resource()is not justget_payload()alias and provides type checking. It does not accept the default argument.Instead of
get_resources(),get_directory_resources()andget_file_resources()- useiterate_resources()and do type checking yourself.
Removed ‘kpm’ (some kind of helper scripts will be provided in future versions, that one was outdated anyway)