{"id":17772155,"url":"https://github.com/dranikpg/gtrs","last_synced_at":"2025-04-21T23:31:06.162Z","repository":{"id":49781116,"uuid":"518040152","full_name":"dranikpg/gtrs","owner":"dranikpg","description":"Turn Redis streams into typed Go channels in just a few lines","archived":false,"fork":false,"pushed_at":"2024-04-27T07:00:40.000Z","size":72,"stargazers_count":84,"open_issues_count":9,"forks_count":15,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-01T16:55:51.601Z","etag":null,"topics":["golang","redis","redis-streams"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dranikpg.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-26T11:51:08.000Z","updated_at":"2025-03-30T23:30:14.000Z","dependencies_parsed_at":"2023-11-28T21:44:08.555Z","dependency_job_id":"44f32ea7-b1b8-4e94-8f6a-b1b21e72d31f","html_url":"https://github.com/dranikpg/gtrs","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dranikpg%2Fgtrs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dranikpg%2Fgtrs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dranikpg%2Fgtrs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dranikpg%2Fgtrs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dranikpg","download_url":"https://codeload.github.com/dranikpg/gtrs/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250150631,"owners_count":21383201,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["golang","redis","redis-streams"],"created_at":"2024-10-26T21:38:07.945Z","updated_at":"2025-04-21T23:31:05.789Z","avatar_url":"https://github.com/dranikpg.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Go Typed Redis Streams\n\n\u003ca href=\"https://pkg.go.dev/github.com/dranikpg/gtrs\"\u003e\u003cimg src=\"https://godoc.org/github.com/dranikpg/gtrs?status.svg\" /\u003e\u003c/a\u003e\n[![Go Report Card](https://goreportcard.com/badge/github.com/dranikpg/gtrs)](https://goreportcard.com/report/github.com/dranikpg/gtrs)\n\nEffectively reading [Redis streams](https://redis.io/docs/manual/data-types/streams/) requires some work: counting ids, prefetching and buffering, asynchronously sending acknowledgements and parsing entries. What if it was just the following?\n\n```go\nconsumer := NewGroupConsumer[MyType](...)\nfor msg := range consumer.Chan() {\n  // Handle mssage\n  consumer.Ack(msg)\n}\n```\n\nWait...it is! 🔥\n\n### Quickstart\n\nDefine a type that represents your stream data. It'll be parsed automatically with all field names converted to snake case. Missing fields will be skipped silently. You can also use the `ConvertibleFrom` and `ConvertibleTo` interfaces to do custom parsing. Struct tags can be used to rename fields.\n\n```go\n// maps to {\"name\": , \"priority\": , \"to\":}\ntype Event struct {\n  Name     string\n  Priority int\n  Target   string `gtrs:\"to\"`\n}\n```\n\n#### Consumers\n\nConsumers allow reading redis streams through Go channels. Specify context, a [redis client](https://github.com/go-redis/redis) and where to start reading. Make sure to specify `StreamConsumerConfig`, if you don't like the default ones or want optimal performance. New entries are fetched asynchronously to provide a fast flow 🚂\n\n```go\nconsumer := NewConsumer[Event](ctx, rdb, StreamIDs{\"my-stream\": \"$\"})\n\nfor msg := range cs.Chan() {\n  if msg.Err != nil {\n    continue\n  }\n  var event Event = msg.Data\n}\n```\n\nDon't forget to `Close()` the consumer. If you want to start reading again where you left off, you can save the last StreamIDs.\n```go\nids := cs.Close()\n```\n\n#### Group Consumers\n\nThey work just like regular consumers and allow sending acknowledgements asynchronously. Beware to use `Ack` only if you keep processing new messages - that is inside a consuming loop or from another goroutine. Even though this introduces a two-sided depdendecy, the consumer is avoids deadlocks.\n\n```go\ncs := NewGroupConsumer[Event](ctx, rdb, \"group\", \"consumer\", \"stream\", \"\u003e\")\n\nfor msg := range cs.Chan() {\n  cs.Ack(msg)\n}\n```\n\nStopped processing? Check your errors 🔎\n```go\n// Wait for all acknowledgements to complete\nerrors := cs.AwaitAcks()\n\n// Acknowledgements that were not sent yet or their errors were not consumed\nremaining := cs.Close()\n```\n\n#### Error handling\n\nThis is where the simplicity fades a litte, but only a little :) The channel provides not just values, but also errors. Those can be only of three types:\n- `ReadError` reports a failed XRead/XReadGroup request. Consumer will close the channel after this error\n- `AckError` reports a failed XAck request\n- `ParseError` speaks for itself\n\nConsumers don't send errors on cancellation and immediately close the channel.\n\n```go\nswitch errv := msg.Err.(type) {\ncase nil: // This interface-nil comparison in safe\n  fmt.Println(\"Got\", msg.Data)\ncase ReadError:\n  fmt.Println(\"ReadError caused by\", errv.Err)\n  return // last message in channel\ncase AckError:\n  fmt.Printf(\"Ack failed %v-%v caused by %v\\n\", msg.Stream, msg.ID, errv.Err)\ncase ParseError:\n  fmt.Println(\"Failed to parse\", errv.Data)\n}\n```\n\nAll those types are wrapping errors. For example, `ParseError` can be unwrapped to:\n- Find out why the default parser failed via `FieldParseError` (e.g. assigning string to int field)\n- Catch custom errors from `ConvertibleFrom`\n\n```go\nvar fpe FieldParseError\nif errors.As(msg.Err, \u0026fpe) {\n  fmt.Printf(\"Failed to parse field %v because %v\", fpe.Field, fpe.Err)\n}\n\nerrors.Is(msg.Err, errMyTypeFailedToParse)\n```\n\n#### Streams\n\nStreams are simple wrappers for basic redis commands on a stream.\n\n```go\nstream := NewStream[Event](rdb, \"my-stream\", \u0026Options{TTL: time.Hour, MaxLen: 1000, Approx: true})\nstream.Add(ctx, Event{\n  Kind:     \"Example event\",\n  Priority: 1,\n})\n```\nThe Options.TTL parameter will evict stream entries after the specified duration has elapsed (or it can be set to `NoExpiration`).\nThe Options.MaxLen parameter will remove older stream entries to accommodate newer entries after the maximum number of entries is reached.\nThe Options.Approx parameter provides better efficiency by using almost exact trimming.\n#### Metadata\n\nThe package defines a Metadata type as:\n```\ntype Metadata map[string]any\n```\n\nThis allows serialization (and deserialization) of generic structured metadata within the stream entries.\nAny value that can be serialized to JSON can be inserted from a field of this type (it uses JSON marshaller under the hood).\nFor example:\n```\nstream.Add(ctx, EventWithMetadata{\n  Kind:     \"Example event\",\n  Priority: 1,\n  Meta: Metadata{\"string\": \"foobar\", \"float\": float64(1234.5)},\n})\n```\n\n### Installation\n\n```\ngo get github.com/dranikpg/gtrs\n```\n\nGtrs is still in its early stages and might change in further releases.\n\n### Examples\n\n* [This is a small example](https://github.com/dranikpg/gtrs-test) for reading from three consumers in parallel and handling all types of errors.\n\n### Performance\n\n```\ngo test -run ^$ -bench BenchmarkConsumer -cpu=1\n```\n\nThe iteration cost on a _mocked client_ is about 500-700 ns depending on buffer sizes, which gives it a **throughput close to 2 million entries a second** 🚀. Getting bad results? Make sure to set large buffer sizes in the options.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdranikpg%2Fgtrs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdranikpg%2Fgtrs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdranikpg%2Fgtrs/lists"}