Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,22 @@ Tested against conformance tests v0.1.8:

Client features: `batching`, `sse`, `longPoll`, `streaming`, `dynamicHeaders`

## Offset Format

This implementation uses the same offset format as the reference Node.js implementation:
```
<readSeq>_<byteOffset>
```
Both components are 16-digit zero-padded integers, e.g., `0000000000000000_0000000000000042`.
This ensures lexicographic sortability as required by PROTOCOL.md Section 6.

## Test Coverage

| Package | Coverage |
|---------|----------|
| durablestream | 90.7% |
| durablestream/transport | 93.1% |
| durablestream/memorystorage | 96.2% |
| durablestream/storage/memorystorage | 96.2% |
| durablestream/internal/protocol | 98.1% |

## Usage
Expand Down
2 changes: 1 addition & 1 deletion durablestream/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"time"

"github.com/ahimsalabs/durable-streams-go/durablestream"
"github.com/ahimsalabs/durable-streams-go/durablestream/memorystorage"
"github.com/ahimsalabs/durable-streams-go/durablestream/storage/memorystorage"
)

// setupTestServer creates a test server with a handler and storage.
Expand Down
2 changes: 1 addition & 1 deletion durablestream/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"time"

"github.com/ahimsalabs/durable-streams-go/durablestream"
"github.com/ahimsalabs/durable-streams-go/durablestream/memorystorage"
"github.com/ahimsalabs/durable-streams-go/durablestream/storage/memorystorage"
)

// [snippet:server]
Expand Down
46 changes: 23 additions & 23 deletions durablestream/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (

"github.com/ahimsalabs/durable-streams-go/durablestream"
"github.com/ahimsalabs/durable-streams-go/durablestream/internal/protocol"
"github.com/ahimsalabs/durable-streams-go/durablestream/memorystorage"
"github.com/ahimsalabs/durable-streams-go/durablestream/storage/memorystorage"
)

func TestHandler_PUT_CreateStream(t *testing.T) {
Expand All @@ -32,7 +32,7 @@ func TestHandler_PUT_CreateStream(t *testing.T) {
wantStatus: http.StatusCreated,
wantHeaders: map[string]string{
"Content-Type": "application/octet-stream",
"Stream-Next-Offset": "0000000000",
"Stream-Next-Offset": "0000000000000000_0000000000000000",
"Location": "http://example.com/test-stream",
},
},
Expand Down Expand Up @@ -359,7 +359,7 @@ func TestHandler_GET_CatchupRead(t *testing.T) {
},
{
name: "read from offset",
offset: "0000000000",
offset: "0000000000000000_0000000000000000",
wantStatus: http.StatusOK,
},
}
Expand Down Expand Up @@ -412,7 +412,7 @@ func TestHandler_GET_JSONMode(t *testing.T) {
_, _ = storage.Append(context.Background(), "/stream", []byte(`{"event":"a"}`), "")
_, _ = storage.Append(context.Background(), "/stream", []byte(`{"event":"b"}`), "")

req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand Down Expand Up @@ -444,7 +444,7 @@ func TestHandler_GET_LongPoll(t *testing.T) {
offset, _ := storage.Append(context.Background(), "/stream", []byte("data1"), "")

t.Run("immediate return with data", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000&live=long-poll", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000&live=long-poll", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand Down Expand Up @@ -519,7 +519,7 @@ func TestHandler_GET_SSE(t *testing.T) {
})
_, _ = storage.Append(context.Background(), "/text-stream", []byte("line1\n"), "")

req := httptest.NewRequest(http.MethodGet, "/text-stream?offset=0000000000&live=sse", nil)
req := httptest.NewRequest(http.MethodGet, "/text-stream?offset=0000000000000000_0000000000000000&live=sse", nil)
rec := httptest.NewRecorder()

// Use a timeout to prevent test hanging
Expand Down Expand Up @@ -553,7 +553,7 @@ func TestHandler_GET_SSE(t *testing.T) {
})
_, _ = storage.Append(context.Background(), "/json-stream", []byte(`{"event":"test"}`), "")

req := httptest.NewRequest(http.MethodGet, "/json-stream?offset=0000000000&live=sse", nil)
req := httptest.NewRequest(http.MethodGet, "/json-stream?offset=0000000000000000_0000000000000000&live=sse", nil)
rec := httptest.NewRecorder()

ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
Expand All @@ -573,7 +573,7 @@ func TestHandler_GET_SSE(t *testing.T) {
ContentType: "application/octet-stream",
})

req := httptest.NewRequest(http.MethodGet, "/binary-stream?offset=0000000000&live=sse", nil)
req := httptest.NewRequest(http.MethodGet, "/binary-stream?offset=0000000000000000_0000000000000000&live=sse", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand Down Expand Up @@ -610,7 +610,7 @@ func TestHandler_GET_SSE(t *testing.T) {
maliciousPayload := "start\r\revent: control\rdata: {\"cr_injected\":true}\r\rend"
_, _ = storage.Append(context.Background(), "/cr-injection-test", []byte(maliciousPayload), "")

req := httptest.NewRequest(http.MethodGet, "/cr-injection-test?offset=0000000000&live=sse", nil)
req := httptest.NewRequest(http.MethodGet, "/cr-injection-test?offset=0000000000000000_0000000000000000&live=sse", nil)
rec := httptest.NewRecorder()

ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
Expand Down Expand Up @@ -998,7 +998,7 @@ func TestHandler_CacheControlHeaders(t *testing.T) {
_, _ = storage.Append(context.Background(), "/stream", []byte("data"), "")

t.Run("catch-up read has cache control", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand All @@ -1019,7 +1019,7 @@ func TestHandler_CacheControlHeaders(t *testing.T) {
})

t.Run("public stream has public cache control", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand Down Expand Up @@ -1049,7 +1049,7 @@ func TestHandler_PrivateCacheControl(t *testing.T) {
_, _ = storage.Append(context.Background(), "/private-stream", []byte("secret data"), "")

t.Run("private stream has private cache control", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/private-stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/private-stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand Down Expand Up @@ -1102,7 +1102,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {
_, _ = storage.Append(context.Background(), "/stream", []byte("data"), "")

t.Run("catch-up read returns ETag header", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)

Expand All @@ -1122,7 +1122,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {

t.Run("304 Not Modified when If-None-Match matches ETag", func(t *testing.T) {
// First request to get the ETag
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec1 := httptest.NewRecorder()
handler.ServeHTTP(rec1, req1)

Expand All @@ -1135,7 +1135,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {
}

// Second request with If-None-Match should get 304
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
req2.Header.Set("If-None-Match", etag)
rec2 := httptest.NewRecorder()
handler.ServeHTTP(rec2, req2)
Expand All @@ -1157,7 +1157,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {
})

t.Run("200 OK when If-None-Match does not match ETag", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
req.Header.Set("If-None-Match", `"wrong-etag"`)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
Expand All @@ -1173,14 +1173,14 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {

t.Run("304 with If-None-Match containing multiple ETags", func(t *testing.T) {
// First request to get the ETag
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec1 := httptest.NewRecorder()
handler.ServeHTTP(rec1, req1)

etag := rec1.Header().Get("ETag")

// Request with multiple ETags (one matching)
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
req2.Header.Set("If-None-Match", `"other-etag", `+etag+`, "another-etag"`)
rec2 := httptest.NewRecorder()
handler.ServeHTTP(rec2, req2)
Expand All @@ -1191,7 +1191,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {
})

t.Run("304 with If-None-Match wildcard", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
req.Header.Set("If-None-Match", "*")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
Expand All @@ -1203,14 +1203,14 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {

t.Run("304 with weak ETag (W/ prefix)", func(t *testing.T) {
// First request to get the ETag
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req1 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec1 := httptest.NewRecorder()
handler.ServeHTTP(rec1, req1)

etag := rec1.Header().Get("ETag")

// Request with weak ETag prefix
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req2 := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
req2.Header.Set("If-None-Match", "W/"+etag)
rec2 := httptest.NewRecorder()
handler.ServeHTTP(rec2, req2)
Expand Down Expand Up @@ -1276,7 +1276,7 @@ func TestHandler_GET_ETagAndIfNoneMatch(t *testing.T) {

// Create request with valid URL, then manually set path to include control char
// This simulates what happens when a client sends a URL-encoded null byte
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
// Override the path extraction to return the stream path with control chars
customHandler := durablestream.NewHandler(storage, &durablestream.HandlerConfig{
PathExtractor: func(*http.Request) string { return streamPath },
Expand Down Expand Up @@ -1607,7 +1607,7 @@ func BenchmarkHandler_Read(b *testing.B) {

b.ResetTimer()
for i := 0; i < b.N; i++ {
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000", nil)
req := httptest.NewRequest(http.MethodGet, "/stream?offset=0000000000000000_0000000000000000", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
// Consume body to avoid measurement skew
Expand Down
31 changes: 0 additions & 31 deletions durablestream/offset.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
// Package durablestream implements the Durable Streams Protocol.
package durablestream

import (
"fmt"
"strconv"
)

// Offset represents an opaque position within a stream.
// Per spec Section 6: Offsets are opaque tokens that are lexicographically sortable.
//
Expand Down Expand Up @@ -50,29 +45,3 @@ func (o Offset) IsZero() bool {
func (o Offset) String() string {
return string(o)
}

// FormatOffset formats an index as a zero-padded 10-digit string offset.
// This is a helper for storage implementations that use sequential integer offsets.
// Uses 10 digits to support up to 9,999,999,999 offsets.
// Per Section 6: Offsets must be lexicographically sortable and strictly increasing.
func FormatOffset(idx int64) Offset {
return Offset(fmt.Sprintf("%010d", idx))
}

// ParseOffset parses an offset string back to an index.
// Returns 0 for empty string or "-1" (stream beginning sentinel).
// Returns ErrBadRequest for invalid or negative offsets.
// This is a helper for storage implementations that use sequential integer offsets.
func ParseOffset(offset Offset) (int64, error) {
if offset == "" || offset == "-1" {
return 0, nil
}
idx, err := strconv.ParseInt(string(offset), 10, 64)
if err != nil {
return 0, fmt.Errorf("invalid offset %q: %w", offset, ErrBadRequest)
}
if idx < 0 {
return 0, fmt.Errorf("negative offset %q: %w", offset, ErrBadRequest)
}
return idx, nil
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// Package memorystorage provides an in-memory implementation of durablestream.Storage.
// Package memorystore provides an in-memory implementation of durablestream.Storage.
//
// This implementation uses the reference offset format from the official Node.js
// implementation: "<readSeq>_<byteOffset>" with 16-digit zero-padded integers.
package memorystorage

import (
Expand All @@ -7,6 +10,7 @@ import (
"sync"

"github.com/ahimsalabs/durable-streams-go/durablestream"
"github.com/ahimsalabs/durable-streams-go/durablestream/storage"
"github.com/go4org/hashtriemap"
)

Expand All @@ -22,7 +26,10 @@ type memoryStream struct {

// Storage is an in-memory implementation of durablestream.Storage.
// Uses hashtriemap for lock-free stream lookups with per-stream locks for mutations.
// Offsets are zero-padded sequential strings (e.g., "0000000001", "0000000002").
//
// Offsets use the reference implementation format: "0000000000000000_0000000000000042"
// where the first 16 digits are the read sequence (always 0 for this implementation)
// and the second 16 digits are the cumulative byte offset.
type Storage struct {
streams hashtriemap.HashTrieMap[string, *memoryStream]
}
Expand Down Expand Up @@ -99,7 +106,8 @@ func (m *Storage) Append(ctx context.Context, streamID string, data []byte, seq
b := make([]byte, len(data))
copy(b, data)

offset := durablestream.FormatOffset(int64(len(stream.messages) + 1))
// Use message index as offset (matching reference implementation's byte offset concept)
offset := storage.FormatSimpleOffset(int64(len(stream.messages) + 1))
msg := durablestream.StoredMessage{
Data: b,
Offset: offset,
Expand Down Expand Up @@ -129,10 +137,11 @@ func (m *Storage) Read(ctx context.Context, streamID string, offset durablestrea
}

// Parse offset to message index
offsetIdx, err := durablestream.ParseOffset(offset)
_, byteOffset, err := storage.ParseOffset(offset)
if err != nil {
return nil, err
}
offsetIdx := byteOffset

// Offset 0 means "start", which maps to first message (index 0)
// Offset N means "after message N", so we start reading from index N
Expand Down Expand Up @@ -164,7 +173,7 @@ func (m *Storage) Read(ctx context.Context, streamID string, offset durablestrea
// No messages returned, stay at current offset
nextOffset = offset
if nextOffset == "" || nextOffset == "-1" {
nextOffset = durablestream.FormatOffset(0)
nextOffset = storage.FormatSimpleOffset(0)
}
}

Expand All @@ -173,7 +182,7 @@ func (m *Storage) Read(ctx context.Context, streamID string, offset durablestrea
if len(stream.messages) > 0 {
tailOffset = stream.messages[len(stream.messages)-1].Offset
} else {
tailOffset = durablestream.FormatOffset(0)
tailOffset = storage.FormatSimpleOffset(0)
}

return &durablestream.ReadResult{
Expand Down Expand Up @@ -203,7 +212,7 @@ func (m *Storage) Head(ctx context.Context, streamID string) (*durablestream.Str
if len(stream.messages) > 0 {
nextOffset = stream.messages[len(stream.messages)-1].Offset
} else {
nextOffset = durablestream.FormatOffset(0)
nextOffset = storage.FormatSimpleOffset(0)
}

return &durablestream.StreamInfo{
Expand Down
Loading