diff --git a/bridgetracker/activity.go b/bridgetracker/activity.go index c81287e5e..1ea83b933 100644 --- a/bridgetracker/activity.go +++ b/bridgetracker/activity.go @@ -349,8 +349,9 @@ func (a *ActivityCache) GetActivity( // GetActivityRevision implements domain.ActivityRevisionReader: the address's current revision // (activityAddrCache.revision), domain.EmptyActivityRevision for an address with nothing cached. -// It does not count as an access (unlike GetActivity, it does not touch lastAccess): the caller -// reads the entries right after, through GetActivity +// It does not count as an access (unlike GetActivity, it does not touch lastAccess): the HTTP +// command has already counted one through RegisterAndAwait, and may not call GetActivity at all +// (a 304 Not Modified) func (a *ActivityCache) GetActivityRevision(_ context.Context, fromAddress common.Address) (string, error) { a.mu.Lock() defer a.mu.Unlock() diff --git a/bridgetracker/api/activity_command.go b/bridgetracker/api/activity_command.go index 29f09e146..ae28cc63e 100644 --- a/bridgetracker/api/activity_command.go +++ b/bridgetracker/api/activity_command.go @@ -9,6 +9,7 @@ import ( "net/http" "sort" "strconv" + "strings" "time" bridgeservicetypes "github.com/agglayer/aggkit/bridgeservice/types" @@ -26,6 +27,27 @@ var _ command = (*activityCommand)(nil) // retrying a 503 response (RFC 9110 §10.2.3), expressed here in whole seconds const retryAfterHeader = "Retry-After" +// HTTP conditional request support of the activity endpoint (RFC 9110 §8.8.3, §13.1.2): the +// address's revision is also sent as the ETag header, and a request whose If-None-Match holds +// it is answered 304 Not Modified with no body (see activityCommand.Execute) +const ( + etagHeader = "ETag" + ifNoneMatchHeader = "If-None-Match" + // cacheControlHeader is sent as cacheControlNoStore next to every ETag. The revision does + // not cover everything in the body (finalized, last_updated_timestamp, tracking, warnings), + // so a 304 means "nothing the revision covers changed", not "the body is byte for byte the + // same". no-store keeps an HTTP cache (a browser's, mainly) from storing the 200 and then + // revalidating it on its own: it would serve its stored body for every 304, and a client that + // never asked for conditional requests would stop seeing those fields change. A client that + // sends If-None-Match itself gets the 304 and decides what to do with it + cacheControlHeader = "Cache-Control" + cacheControlNoStore = "no-store" + // ifNoneMatchAny is the If-None-Match value matching any current representation + ifNoneMatchAny = "*" + // weakETagPrefix marks a weak entity tag; If-None-Match compares weakly, so it is ignored + weakETagPrefix = "W/" +) + // Pagination defaults/limits for the activity endpoint, matching the bridge service's own // paginated endpoints (see bridgeservice.DefaultPage/DefaultPageSize/MaxPageSize) — same // numbers, same 1-based page numbering, so a client already paging bridge service endpoints @@ -209,7 +231,16 @@ type ActivityResponse struct { // skipped and reported in the "warnings" field instead, so Bridges is still whatever every other // network reported. 200 OK unless: invalid from_address/filterBridges (ErrorData/400), the // address registry is at capacity or from_address is not ready yet (ErrorData/503, the latter -// with Retry-After), or registering otherwise failed (ErrorData/500) +// with Retry-After), or registering otherwise failed (ErrorData/500). +// +// Conditional requests: the response's revision is also sent as its ETag header (the revision +// between double quotes, a strong entity tag). A request carrying it in If-None-Match (or "*") is +// answered 304 Not Modified with the ETag and no body, once from_address is ready, without +// calling GetActivity (RegisterAndAwait has already counted the request as an access). Like the +// revision, the ETag is the same whatever filterBridges/page_number/page_size say, and a 304 only +// tells that nothing the revision covers changed (see +// cacheControlHeader). Everything before that point (validation, flush_cache, registering +// from_address with includeTracking) runs exactly as for a 200 // // @Summary Get bridge activity by sender address // @Description Registers from_address as supervised and reports whatever the activity engine's @@ -236,7 +267,10 @@ type ActivityResponse struct { // @Description when an item only becomes finalized. It is the same after a restart and on every // @Description instance holding the same data. Poll it with a cheap request (page_size=1), reload // @Description the loaded pages when it changed, and check it again after the last page. Compare -// @Description it only for equality. +// @Description it only for equality. The same value is sent as the ETag response header (between +// @Description double quotes): a request carrying it in If-None-Match is answered 304 Not Modified +// @Description with no body while the revision is unchanged, whatever the filter or the page. A 304 +// @Description does not tell whether finalized, last_updated_timestamp, tracking or warnings changed. // @Tags bridge-tracker // @Produce json // @Param from_address path string true "Address that sent the bridges to look up" @@ -245,7 +279,11 @@ type ActivityResponse struct { // @Param flush_cache query bool false "Discard cached activity for from_address before answering" // @Param page_number query uint32 false "Page number, 1-based (default 1)" // @Param page_size query uint32 false "Page size (default 20, max 200)" +// @Param If-None-Match header string false "ETag of a previous response (the revision between double quotes)" // @Success 200 {object} ActivityResponse +// @Success 304 "Not Modified: the revision is the one sent in If-None-Match, no body" +// @Header 200,304 {string} ETag "The revision between double quotes (strong entity tag)" +// @Header 200,304 {string} Cache-Control "no-store" // @Failure 400 {object} types.ErrorData "Invalid from_address or filterBridges" // @Failure 500 {object} types.ErrorData "Registering from_address failed" // @Failure 503 {object} types.ErrorData "Registry at capacity, or from_address not ready yet (see Retry-After)" @@ -307,16 +345,26 @@ func (cmd *activityCommand) Execute(c *gin.Context) (int, any, *types.ErrorData) // the revision is read BEFORE the entries (see domain.ActivityRevisionReader): a refresh landing // in between can only make the entries newer than the revision reported, never older - revision, err := cmd.activityRevision(c.Request.Context(), fromAddress) + revision, hasRevision, err := cmd.activityRevision(c.Request.Context(), fromAddress) if err != nil { return 0, nil, &types.ErrorData{Code: http.StatusInternalServerError, Message: aggkitcommon.RedactError(err)} } + // without a real revision (a registry that keeps none) there is no validator to offer: the + // constant empty revision would answer 304 forever + if hasRevision && ifNoneMatchHolds(c.Request.Header.Values(ifNoneMatchHeader), activityETag(revision)) { + setActivityValidatorHeaders(c, revision) + return http.StatusNotModified, nil, nil + } entries, warnings, err := cmd.registry.GetActivity(c.Request.Context(), fromAddress, includeTracking, filter) if err != nil { return 0, nil, &types.ErrorData{Code: http.StatusInternalServerError, Message: aggkitcommon.RedactError(err)} } + // only now: an error response must not carry the ETag of a body the client never received + if hasRevision { + setActivityValidatorHeaders(c, revision) + } return http.StatusOK, ActivityResponse{ FromAddress: fromAddress, Bridges: newActivityItems(paginateActivityEntries(entries, pageNumber, pageSize)), @@ -327,13 +375,53 @@ func (cmd *activityCommand) Execute(c *gin.Context) (int, any, *types.ErrorData) } // activityRevision is fromAddress's revision as served by the registry when it implements -// domain.ActivityRevisionReader, and domain.EmptyActivityRevision when it does not -func (cmd *activityCommand) activityRevision(ctx context.Context, fromAddress common.Address) (string, error) { +// domain.ActivityRevisionReader (kept true), and domain.EmptyActivityRevision with kept false +// when it does not: that constant says nothing about the address's activity +func (cmd *activityCommand) activityRevision( + ctx context.Context, fromAddress common.Address, +) (revision string, kept bool, err error) { reader, ok := cmd.registry.(domain.ActivityRevisionReader) if !ok { - return domain.EmptyActivityRevision, nil + return domain.EmptyActivityRevision, false, nil + } + revision, err = reader.GetActivityRevision(ctx, fromAddress) + return revision, true, err +} + +// activityETag is revision as an entity tag: the opaque string between double quotes, a strong +// validator in RFC 9110 terms (see cacheControlHeader for what it does and does not cover) +func activityETag(revision string) string { + return `"` + revision + `"` +} + +// setActivityValidatorHeaders sets the headers a 200 and a 304 of the activity endpoint share: +// revision as the ETag, and Cache-Control: no-store (see cacheControlHeader) +func setActivityValidatorHeaders(c *gin.Context, revision string) { + c.Header(etagHeader, activityETag(revision)) + c.Header(cacheControlHeader, cacheControlNoStore) +} + +// ifNoneMatchHolds reports whether the If-None-Match header lines of a request hold etag, so the +// request is answered 304: any of the listed entity tags is etag, compared weakly as RFC 9110 +// §13.1.2 mandates for this header (a W/ prefix is ignored), or a header line is exactly "*" (any +// current representation; there always is one at this point). No header, or only other tags, is +// false +func ifNoneMatchHolds(headerLines []string, etag string) bool { + for _, line := range headerLines { + // "*" is only the wildcard as the whole field value (If-None-Match = "*" / #entity-tag): + // inside a list it can only be part of a quoted tag that holds commas + if strings.TrimSpace(line) == ifNoneMatchAny { + return true + } + // an entity tag of this endpoint has no comma, and a quoted tag cannot hold a double + // quote, so splitting the list on commas cannot make a foreign tag look like etag + for _, candidate := range strings.Split(line, ",") { + if strings.TrimPrefix(strings.TrimSpace(candidate), weakETagPrefix) == etag { + return true + } + } } - return reader.GetActivityRevision(ctx, fromAddress) + return false } // parseActivityPageParams parses and validates the activity endpoint's page_number/page_size diff --git a/bridgetracker/api/activity_etag_test.go b/bridgetracker/api/activity_etag_test.go new file mode 100644 index 000000000..3cc582494 --- /dev/null +++ b/bridgetracker/api/activity_etag_test.go @@ -0,0 +1,309 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/agglayer/aggkit/bridgetracker/domain" + aggkitcommon "github.com/agglayer/aggkit/common" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" +) + +const ( + etagTestRevision = "v1:00000000000000000000000000000000000000000000000000000000000000ab" + etagTestOtherRevision = "v1:00000000000000000000000000000000000000000000000000000000000000cd" + etagTestETag = `"` + etagTestRevision + `"` +) + +// newETagTestRegistry returns a ready registry holding one bridge whose revision is revision +func newETagTestRegistry(revision string) *fakeRevisionActivityRegistry { + registry := &fakeRevisionActivityRegistry{fakeActivityRegistry: newFakeActivityRegistry(), revision: revision} + registry.getActivityEntries = []*domain.ActivityEntry{activityEntryAt("1", time.Now())} + return registry +} + +// executeActivity runs cmd for GET /activity/from/{from_address}?rawQuery with the given +// If-None-Match header lines (none: the header is not sent) and returns Execute's result plus +// the response headers it set +func executeActivity( + cmd *activityCommand, rawQuery string, ifNoneMatch ...string, +) (code int, obj any, errCode int, header http.Header) { + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/?"+rawQuery, nil) + for _, value := range ifNoneMatch { + c.Request.Header.Add(ifNoneMatchHeader, value) + } + c.Params = gin.Params{{Key: fromAddressParam, Value: testActivityFromAddress.Hex()}} + + code, obj, errData := cmd.Execute(c) + if errData != nil { + errCode = errData.Code + } + return code, obj, errCode, recorder.Header() +} + +// TestActivityCommandExecute_ETagIsTheRevision verifies a request with no If-None-Match is +// answered as before, plus the revision of its body as a strong ETag and Cache-Control: no-store +func TestActivityCommandExecute_ETagIsTheRevision(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + cmd := &activityCommand{registry: registry} + + code, obj, errCode, header := executeActivity(cmd, "") + require.Zero(t, errCode) + require.Equal(t, http.StatusOK, code) + body, ok := obj.(ActivityResponse) + require.True(t, ok) + require.Equal(t, etagTestRevision, body.Revision) + require.Len(t, body.Bridges, 1) + require.Equal(t, `"`+body.Revision+`"`, header.Get(etagHeader), "the ETag is the body's revision, quoted") + require.Equal(t, cacheControlNoStore, header.Get(cacheControlHeader)) + require.Equal(t, []string{"RegisterAndAwait", "GetActivityRevision", "GetActivity"}, registry.calls) +} + +// TestActivityCommandExecute_IfNoneMatch verifies which If-None-Match values are answered 304 +// (no body, the entries not read) and which get the full 200 +func TestActivityCommandExecute_IfNoneMatch(t *testing.T) { + otherETag := `"` + etagTestOtherRevision + `"` + tests := map[string]struct { + ifNoneMatch []string + notModified bool + }{ + "the current ETag": {ifNoneMatch: []string{etagTestETag}, notModified: true}, + "the current ETag as a weak tag": {ifNoneMatch: []string{"W/" + etagTestETag}, notModified: true}, + "any (*)": {ifNoneMatch: []string{"*"}, notModified: true}, + "any (*) with spaces around": {ifNoneMatch: []string{" * "}, notModified: true}, + "a * inside a quoted tag with commas": {ifNoneMatch: []string{`"other,*,revision"`}}, + "a * inside a list of tags": {ifNoneMatch: []string{otherETag + ", *"}}, + "the revision inside another tag": {ifNoneMatch: []string{`"other,` + etagTestRevision + `"`}}, + "a list holding the current ETag": {ifNoneMatch: []string{otherETag + ` , ` + etagTestETag}, notModified: true}, + "several header lines, one current": {ifNoneMatch: []string{otherETag, etagTestETag}, notModified: true}, + "another revision": {ifNoneMatch: []string{otherETag}}, + "a list without the current ETag": {ifNoneMatch: []string{otherETag + `, "x"`}}, + "the revision without quotes": {ifNoneMatch: []string{etagTestRevision}}, + "an empty header": {ifNoneMatch: []string{""}}, + "the current ETag with something else": {ifNoneMatch: []string{etagTestETag + "x"}}, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + cmd := &activityCommand{registry: registry} + + code, obj, errCode, header := executeActivity(cmd, "", tt.ifNoneMatch...) + require.Zero(t, errCode) + require.Equal(t, etagTestETag, header.Get(etagHeader), "the ETag is sent with a 304 too") + require.Equal(t, cacheControlNoStore, header.Get(cacheControlHeader)) + if tt.notModified { + require.Equal(t, http.StatusNotModified, code) + require.Nil(t, obj, "a 304 has no body") + require.Equal(t, []string{"RegisterAndAwait", "GetActivityRevision"}, registry.calls, + "the entries are not read for a 304") + return + } + require.Equal(t, http.StatusOK, code) + body, ok := obj.(ActivityResponse) + require.True(t, ok) + require.Equal(t, etagTestRevision, body.Revision) + require.Equal(t, []string{"RegisterAndAwait", "GetActivityRevision", "GetActivity"}, registry.calls) + }) + } +} + +// TestActivityCommandExecute_ETagIndependentOfFilterAndPage verifies every filter and page of +// an address carries the same ETag — the revision covers all its bridges — including a page past +// the end and a filter matching nothing, and that the ETag of one of them is a 304 on any other +func TestActivityCommandExecute_ETagIndependentOfFilterAndPage(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + cmd := &activityCommand{registry: registry} + + queries := []string{ + "", "page_size=1", "page_number=2&page_size=1", "page_number=99", + "filterBridges=claimed", "filterBridges=pending&page_size=200", "filterBridges=error&page_number=3", + "includeTracking=true", + } + for _, rawQuery := range queries { + code, obj, errCode, header := executeActivity(cmd, rawQuery) + require.Zero(t, errCode, rawQuery) + require.Equal(t, http.StatusOK, code, rawQuery) + body, ok := obj.(ActivityResponse) + require.True(t, ok) + require.Equal(t, etagTestRevision, body.Revision, rawQuery) + require.Equal(t, etagTestETag, header.Get(etagHeader), rawQuery) + + code, obj, errCode, header = executeActivity(cmd, rawQuery, etagTestETag) + require.Zero(t, errCode, rawQuery) + require.Equal(t, http.StatusNotModified, code, rawQuery) + require.Nil(t, obj, rawQuery) + require.Equal(t, etagTestETag, header.Get(etagHeader), rawQuery) + } +} + +// TestActivityCommandExecute_IfNoneMatchAfterTheRevisionChanged verifies the ETag a client holds +// stops matching once the revision changes: it gets the full response and the new ETag +func TestActivityCommandExecute_IfNoneMatchAfterTheRevisionChanged(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + cmd := &activityCommand{registry: registry} + + code, obj, errCode, header := executeActivity(cmd, "page_size=1", etagTestETag) + require.Zero(t, errCode) + require.Equal(t, http.StatusNotModified, code) + require.Nil(t, obj) + require.Equal(t, etagTestETag, header.Get(etagHeader)) + + registry.revision = etagTestOtherRevision + code, obj, errCode, header = executeActivity(cmd, "page_size=1", etagTestETag) + require.Zero(t, errCode) + require.Equal(t, http.StatusOK, code) + body, ok := obj.(ActivityResponse) + require.True(t, ok) + require.Equal(t, etagTestOtherRevision, body.Revision) + require.Equal(t, `"`+etagTestOtherRevision+`"`, header.Get(etagHeader)) +} + +// TestActivityCommandExecute_IfNoneMatchKeepsRequestSideEffects verifies a 304 skips nothing but +// the read of the entries: flush_cache still flushes first and includeTracking still reaches +// RegisterAndAwait, which is what marks the address as wanting tracking +func TestActivityCommandExecute_IfNoneMatchKeepsRequestSideEffects(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + cmd := &activityCommand{registry: registry, resolveTimeout: 5 * time.Second} + + code, obj, errCode, _ := executeActivity(cmd, "includeTracking=true&flush_cache=true", etagTestETag) + require.Zero(t, errCode) + require.Equal(t, http.StatusNotModified, code) + require.Nil(t, obj) + require.Equal(t, []string{"FlushActivity", "RegisterAndAwait", "GetActivityRevision"}, registry.calls) + require.Equal(t, testActivityFromAddress, registry.lastFlushAddress) + require.True(t, registry.lastRegisterIncludeTracking) + require.Equal(t, 5*time.Second, registry.lastRegisterTimeout) +} + +// TestActivityCommandExecute_IfNoneMatchNeverHidesAnError verifies If-None-Match (even "*") only +// applies where a 200 would be answered: every error keeps its status and carries no ETag +func TestActivityCommandExecute_IfNoneMatchNeverHidesAnError(t *testing.T) { + tests := map[string]struct { + rawQuery string + prepare func(registry *fakeRevisionActivityRegistry) + code int + calls []string + }{ + "invalid filter": {rawQuery: "filterBridges=typo", code: http.StatusBadRequest}, + "invalid page": {rawQuery: "page_size=0", code: http.StatusBadRequest}, + "address not ready yet": { + prepare: func(registry *fakeRevisionActivityRegistry) { registry.registerAndAwaitReady = false }, + code: http.StatusServiceUnavailable, calls: []string{"RegisterAndAwait"}, + }, + "registry full": { + prepare: func(registry *fakeRevisionActivityRegistry) { + registry.registerAndAwaitErr = domain.ErrActivityRegistryFull + }, + code: http.StatusServiceUnavailable, calls: []string{"RegisterAndAwait"}, + }, + "reading the revision fails": { + prepare: func(registry *fakeRevisionActivityRegistry) { registry.revisionErr = errBoom }, + code: http.StatusInternalServerError, calls: []string{"RegisterAndAwait", "GetActivityRevision"}, + }, + } + for name, tt := range tests { + for _, ifNoneMatch := range []string{etagTestETag, "*"} { + t.Run(name+"/"+ifNoneMatch, func(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + if tt.prepare != nil { + tt.prepare(registry) + } + cmd := &activityCommand{registry: registry, pollInterval: 10 * time.Second} + + code, obj, errCode, header := executeActivity(cmd, tt.rawQuery, ifNoneMatch) + require.Equal(t, tt.code, errCode) + require.Zero(t, code) + require.Nil(t, obj) + require.Empty(t, header.Values(etagHeader)) + require.Empty(t, header.Values(cacheControlHeader)) + require.Equal(t, tt.calls, registry.calls) + }) + } + } +} + +// TestActivityCommandExecute_EntriesErrorCarriesNoETag verifies a request that is not answered 304 +// still fails with 500 when the entries cannot be read, and that this error carries no ETag +func TestActivityCommandExecute_EntriesErrorCarriesNoETag(t *testing.T) { + registry := newETagTestRegistry(etagTestRevision) + registry.getActivityErr = errBoom + cmd := &activityCommand{registry: registry} + + for _, ifNoneMatch := range [][]string{nil, {`"` + etagTestOtherRevision + `"`}} { + code, obj, errCode, header := executeActivity(cmd, "", ifNoneMatch...) + require.Equal(t, http.StatusInternalServerError, errCode) + require.Zero(t, code) + require.Nil(t, obj) + require.Empty(t, header.Values(etagHeader), "no ETag for a body that was never sent") + require.Empty(t, header.Values(cacheControlHeader)) + } +} + +// TestActivityCommandExecute_NoETagWithoutRevisionReader verifies a registry that keeps no +// revision offers no validator: its body carries the constant empty revision, which says nothing +// about the activity, so no ETag is sent and If-None-Match is never answered 304 +func TestActivityCommandExecute_NoETagWithoutRevisionReader(t *testing.T) { + for _, ifNoneMatch := range []string{`"` + domain.EmptyActivityRevision + `"`, "*"} { + registry := newFakeActivityRegistry() + cmd := &activityCommand{registry: registry} + + code, obj, errCode, header := executeActivity(cmd, "", ifNoneMatch) + require.Zero(t, errCode) + require.Equal(t, http.StatusOK, code) + body, ok := obj.(ActivityResponse) + require.True(t, ok) + require.Equal(t, domain.EmptyActivityRevision, body.Revision) + require.Empty(t, header.Values(etagHeader)) + require.Empty(t, header.Values(cacheControlHeader)) + require.Equal(t, []string{"RegisterAndAwait", "GetActivity"}, registry.calls) + } +} + +// TestActivityRouteNotModifiedOnTheWire runs the flow a client follows through the real router: +// a first request, then a conditional one with the ETag received. The 304 has the ETag and an +// empty body with no Content-Type; an address with no bridges has the empty revision as its ETag +func TestActivityRouteNotModifiedOnTheWire(t *testing.T) { + gin.SetMode(gin.TestMode) + registry := newETagTestRegistry(etagTestRevision) + router := gin.New() + NewAPI(nil, "sha1", nil, registry, nil, 0, 0, 0, aggkitcommon.CORSConfig{}, nil).RegisterRoutes(router) + target := TrackerV1Prefix + "/activity/from/" + testActivityFromAddress.Hex() + "?page_size=1" + get := func(ifNoneMatch string) *httptest.ResponseRecorder { + request := httptest.NewRequest(http.MethodGet, target, nil) + if ifNoneMatch != "" { + request.Header.Set(ifNoneMatchHeader, ifNoneMatch) + } + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, request) + return recorder + } + + first := get("") + require.Equal(t, http.StatusOK, first.Code) + var body ActivityResponse + require.NoError(t, json.Unmarshal(first.Body.Bytes(), &body)) + etag := first.Header().Get(etagHeader) + require.Equal(t, `"`+body.Revision+`"`, etag) + require.Equal(t, cacheControlNoStore, first.Header().Get(cacheControlHeader)) + + unchanged := get(etag) + require.Equal(t, http.StatusNotModified, unchanged.Code) + require.Zero(t, unchanged.Body.Len(), "a 304 has no body") + require.Empty(t, unchanged.Header().Get("Content-Type")) + require.Equal(t, etag, unchanged.Header().Get(etagHeader)) + require.Equal(t, cacheControlNoStore, unchanged.Header().Get(cacheControlHeader)) + + registry.revision = domain.EmptyActivityRevision + registry.getActivityEntries = nil + changed := get(etag) + require.Equal(t, http.StatusOK, changed.Code) + require.NoError(t, json.Unmarshal(changed.Body.Bytes(), &body)) + require.Equal(t, domain.EmptyActivityRevision, body.Revision) + require.Equal(t, `"`+domain.EmptyActivityRevision+`"`, changed.Header().Get(etagHeader)) +} diff --git a/bridgetracker/api/api.go b/bridgetracker/api/api.go index 9097c6697..37911fe4d 100644 --- a/bridgetracker/api/api.go +++ b/bridgetracker/api/api.go @@ -178,16 +178,24 @@ func (a *API) RegisterRoutes(router gin.IRouter) { // logic against the request and returns the HTTP status code and body to write, or the // ErrorData to write instead type command interface { + // Execute returns the status and the body to write (obj nil: no body), or errData Execute(c *gin.Context) (code int, obj any, errData *types.ErrorData) } -// runCommand executes cmd and writes its result (or error) as the gin response +// runCommand executes cmd and writes its result (or error) as the gin response. A nil obj with +// no error is a response with no body (e.g. the activity endpoint's 304 Not Modified): only the +// status and the headers the command set are written func runCommand(c *gin.Context, cmd command) { code, obj, errData := cmd.Execute(c) if errData != nil { c.JSON(errData.Code, errData) return } + if obj == nil { + c.Status(code) + c.Writer.WriteHeaderNow() + return + } c.JSON(code, obj) } diff --git a/bridgetracker/api/docs/bridgetracker_docs.go b/bridgetracker/api/docs/bridgetracker_docs.go index 0297eaca0..5f68d3d34 100644 --- a/bridgetracker/api/docs/bridgetracker_docs.go +++ b/bridgetracker/api/docs/bridgetracker_docs.go @@ -24,7 +24,7 @@ const docTemplatebridgetracker = `{ "paths": { "/activity/from/{from_address}": { "get": { - "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality.", + "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality. The same value is sent as the ETag response header (between\ndouble quotes): a request carrying it in If-None-Match is answered 304 Not Modified\nwith no body while the revision is unchanged, whatever the filter or the page. A 304\ndoes not tell whether finalized, last_updated_timestamp, tracking or warnings changed.", "produces": [ "application/json" ], @@ -79,6 +79,12 @@ const docTemplatebridgetracker = `{ "description": "Page size (default 20, max 200)", "name": "page_size", "in": "query" + }, + { + "type": "string", + "description": "ETag of a previous response (the revision between double quotes)", + "name": "If-None-Match", + "in": "header" } ], "responses": { @@ -86,6 +92,29 @@ const docTemplatebridgetracker = `{ "description": "OK", "schema": { "$ref": "#/definitions/api.ActivityResponse" + }, + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } + } + }, + "304": { + "description": "Not Modified: the revision is the one sent in If-None-Match, no body", + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } } }, "400": { diff --git a/bridgetracker/api/docs/bridgetracker_swagger.json b/bridgetracker/api/docs/bridgetracker_swagger.json index bf583001f..1e338f57e 100644 --- a/bridgetracker/api/docs/bridgetracker_swagger.json +++ b/bridgetracker/api/docs/bridgetracker_swagger.json @@ -17,7 +17,7 @@ "paths": { "/activity/from/{from_address}": { "get": { - "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality.", + "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality. The same value is sent as the ETag response header (between\ndouble quotes): a request carrying it in If-None-Match is answered 304 Not Modified\nwith no body while the revision is unchanged, whatever the filter or the page. A 304\ndoes not tell whether finalized, last_updated_timestamp, tracking or warnings changed.", "produces": [ "application/json" ], @@ -72,6 +72,12 @@ "description": "Page size (default 20, max 200)", "name": "page_size", "in": "query" + }, + { + "type": "string", + "description": "ETag of a previous response (the revision between double quotes)", + "name": "If-None-Match", + "in": "header" } ], "responses": { @@ -79,6 +85,29 @@ "description": "OK", "schema": { "$ref": "#/definitions/api.ActivityResponse" + }, + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } + } + }, + "304": { + "description": "Not Modified: the revision is the one sent in If-None-Match, no body", + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } } }, "400": { diff --git a/bridgetracker/api/docs/bridgetracker_swagger.yaml b/bridgetracker/api/docs/bridgetracker_swagger.yaml index 9b43ffa0e..c03003f9d 100644 --- a/bridgetracker/api/docs/bridgetracker_swagger.yaml +++ b/bridgetracker/api/docs/bridgetracker_swagger.yaml @@ -764,7 +764,10 @@ paths: when an item only becomes finalized. It is the same after a restart and on every instance holding the same data. Poll it with a cheap request (page_size=1), reload the loaded pages when it changed, and check it again after the last page. Compare - it only for equality. + it only for equality. The same value is sent as the ETag response header (between + double quotes): a request carrying it in If-None-Match is answered 304 Not Modified + with no body while the revision is unchanged, whatever the filter or the page. A 304 + does not tell whether finalized, last_updated_timestamp, tracking or warnings changed. parameters: - description: Address that sent the bridges to look up in: path @@ -800,13 +803,34 @@ paths: in: query name: page_size type: integer + - description: ETag of a previous response (the revision between double quotes) + in: header + name: If-None-Match + type: string produces: - application/json responses: "200": description: OK + headers: + Cache-Control: + description: no-store + type: string + ETag: + description: The revision between double quotes (strong entity tag) + type: string schema: $ref: '#/definitions/api.ActivityResponse' + "304": + description: 'Not Modified: the revision is the one sent in If-None-Match, + no body' + headers: + Cache-Control: + description: no-store + type: string + ETag: + description: The revision between double quotes (strong entity tag) + type: string "400": description: Invalid from_address or filterBridges schema: diff --git a/bridgetracker/api/revision.go b/bridgetracker/api/revision.go index 43f2c603b..618635c55 100644 --- a/bridgetracker/api/revision.go +++ b/bridgetracker/api/revision.go @@ -52,4 +52,12 @@ package api // an addition, removal, claim_status change or reorg correction, not when an entry only // becomes final, and being a hash it is the same after a restart and on every instance // holding the same data; clients compare it for equality only -const CurrentAPIRevision = 7 +// - 8: GET /activity/from/{from_address} supports HTTP conditional requests +// (agglayer/aggkit#1971). Its 200 response carries the revision as the ETag header (the +// revision between double quotes, a strong entity tag) and Cache-Control: no-store; a request +// carrying that value in If-None-Match (or "*") is answered 304 Not Modified, with the ETag +// and no body, while the revision is unchanged, whatever filterBridges/page_number/page_size +// say. Additive: the body is unchanged and a client that sends no If-None-Match never +// receives a 304. A 304 says nothing about what the revision does not cover (finalized, +// last_updated_timestamp, tracking, warnings) +const CurrentAPIRevision = 8 diff --git a/docs/assets/swagger/bridge_tracker/swagger.json b/docs/assets/swagger/bridge_tracker/swagger.json index bf583001f..1e338f57e 100644 --- a/docs/assets/swagger/bridge_tracker/swagger.json +++ b/docs/assets/swagger/bridge_tracker/swagger.json @@ -17,7 +17,7 @@ "paths": { "/activity/from/{from_address}": { "get": { - "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality.", + "description": "Registers from_address as supervised and reports whatever the activity engine's\nbackground refresh has cached for it so far — on a first-time address, this\nrequest waits briefly for that first refresh before answering, and answers 503\nwith a Retry-After header (the engine's poll interval) if it is still not ready\nby then, instead of an empty 200 indistinguishable from \"no activity\" (see\nRegisterResolveTimeout-equivalent config). Results are cached: a bridge already\nknown to be claimed, with its claim record already fetched, is not rechecked on a\nlater refresh. Passing includeTracking=true additionally marks the address so a\nfollowing background refresh registers every still-unclaimed bridge with the\nbridge tracker and includes its current tracking snapshot. filterBridges\nrestricts the result to bridges with only that claim state (claimed / still\npending / ready to claim / errored while checking). flush_cache=true discards\nwhatever is already cached for from_address, so the next background refresh\nrechecks everything from scratch. A network whose bridge service could not be\nscanned is skipped and reported in the \"warnings\" field instead of failing the\nwhole request. Bridges are sorted most recent first and paginated via\npage_number/page_size (same names and 1-based numbering as the bridge service's\nown paginated endpoints); \"count\" reports how many bridges matched in total,\nacross every page. \"revision\" is an opaque string, a hash of the address's\nactivity: it changes when a bridge is added or removed, changes claim_status or is\ncorrected after a reorg, wherever it sits in the sorted result, and does not change\nwhen an item only becomes finalized. It is the same after a restart and on every\ninstance holding the same data. Poll it with a cheap request (page_size=1), reload\nthe loaded pages when it changed, and check it again after the last page. Compare\nit only for equality. The same value is sent as the ETag response header (between\ndouble quotes): a request carrying it in If-None-Match is answered 304 Not Modified\nwith no body while the revision is unchanged, whatever the filter or the page. A 304\ndoes not tell whether finalized, last_updated_timestamp, tracking or warnings changed.", "produces": [ "application/json" ], @@ -72,6 +72,12 @@ "description": "Page size (default 20, max 200)", "name": "page_size", "in": "query" + }, + { + "type": "string", + "description": "ETag of a previous response (the revision between double quotes)", + "name": "If-None-Match", + "in": "header" } ], "responses": { @@ -79,6 +85,29 @@ "description": "OK", "schema": { "$ref": "#/definitions/api.ActivityResponse" + }, + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } + } + }, + "304": { + "description": "Not Modified: the revision is the one sent in If-None-Match, no body", + "headers": { + "Cache-Control": { + "type": "string", + "description": "no-store" + }, + "ETag": { + "type": "string", + "description": "The revision between double quotes (strong entity tag)" + } } }, "400": { diff --git a/docs/bridgetracker/API.md b/docs/bridgetracker/API.md index e79edd4d9..4c57f76b3 100644 --- a/docs/bridgetracker/API.md +++ b/docs/bridgetracker/API.md @@ -92,7 +92,7 @@ stateDiagram-v2 On the tracker, until the claim is final every tick re-checks what a reorg can undo (the origin bridge block, the claim, and at `readyToClaim` the GER injection and the L1 info leaf) and moves the bridge back when one is gone; a WebSocket subscriber receives those backward moves like any other change. A transient failure of those checks (an RPC error, or a bridge service answering `503` while it resolves a reorg) never moves the bridge back. Which calls are made and when: see [Reorgs](../bridgetracker.md#reorgs-re-evaluation-and-backward-transitions). -> **Availability.** `claimed_finalized`, `finalized`, `block_finalized` and `revision` are part of the contract since `api_revision` 7, and all of them are populated. +> **Availability.** `claimed_finalized`, `finalized`, `block_finalized` and `revision` are part of the contract since `api_revision` 7, and all of them are populated. `api_revision` 8 adds the `ETag` / `If-None-Match` support of the activity endpoint (see [Conditional requests](#conditional-requests-etag-and-304)); nothing else changes. > - Activity endpoint: an item becomes `claimed_finalized` / `finalized` once the bridge's block (origin network) and the claim's block (destination network) are both final, and `revision` is kept up to date (agglayer/aggkit#1968, #1969). > - Tracker endpoints ([TrackingData](#trackingdata)): `claim_status` becomes `claimed_finalized` once the claim's block is final, and `bridge_status.block_finalized` follows the origin bridge block (agglayer/aggkit#1970). @@ -450,7 +450,7 @@ Example: ```json { "status": "ok", - "api_revision": 7, + "api_revision": 8, "instance_id": "3f1c9a2e-8b4d-4f6a-9c0e-5d7b2a1e4c8f", "start_date": "2026-09-22T10:30:00Z", "config_sha1": "2ef7bde608ce5404e97d5f042f95f89f1c232871", @@ -484,10 +484,12 @@ Request: | filterBridges | query | string | no | one of `"all"` (default), `"claimed"`, `"pending"`, `"readyToClaim"`, `"error"` — restricts the result to bridges with only that `claim_status`; `"claimed"` matches both `claim_status` `"claimed"` and `"claimed_finalized"` | | page_number | query | uint32 | no | 1-based page number. Default `1` — same parameter name and numbering as the bridge service's own paginated endpoints | | page_size | query | uint32 | no | page size. Default `20`, max `200` | +| If-None-Match | header | string | no | the `ETag` of a previous response, i.e. the [`revision`](#revision) between double quotes. While the revision is still that one the answer is `304 Not Modified` with no body — see [Conditional requests](#conditional-requests-etag-and-304). Since `api_revision` 8 | ### Behavior -- `200 OK` — the body is an [ActivityResponse](#activityresponse). +- `200 OK` — the body is an [ActivityResponse](#activityresponse). The response carries the `ETag` header (the body's `revision` between double quotes) and `Cache-Control: no-store`. +- `304 Not Modified` — only for a request with `If-None-Match`, when the address's `revision` is the one it holds: no body, same `ETag` and `Cache-Control` headers. See [Conditional requests](#conditional-requests-etag-and-304). - `400 Bad Request` — invalid `from_address`, an unrecognized `filterBridges` value, or an invalid `page_number`/`page_size` (zero, non-numeric, or `page_size` over `200`): the body is an [ErrorData](#errordata). - `500 Internal Server Error` — scanning the configured bridge services failed: the body is an [ErrorData](#errordata). - **This endpoint is opt-in**: it only exists if the binary is configured with both an activity bridge scanner and claim checker (`Config.ActivityScanner`/`ActivityClaims`); otherwise the route is not registered at all (plain `404`). @@ -518,7 +520,10 @@ Clients that need the complete list must deduplicate by `bridge.global_index` (u #### Rules -- `revision` **changes** whenever any of the address's bridges is added, removed, changes `claim_status` or is corrected after a reorg (the bridge or its claim is re-included in another block or transaction) — wherever the entry sits in the sorted result, not just on page 1. +- `revision` **changes** whenever any of the address's bridges is added, removed, changes `claim_status` or is corrected after a reorg — wherever the entry sits in the sorted result, not just on page 1. +- What counts as a reorg correction follows from what is hashed (see the table below): + - a **bridge** re-included in another block or in another transaction changes `revision` (`bridge.block_num` and `bridge.tx_hash` are hashed); + - a **claim** changes `revision` only when its transaction changes (only `claim.tx_hash` is hashed). The same claim transaction re-included in another block does **not** change it. - `revision` **does not change** when an entry only goes from not final to final (`finalized` from `false` to `true`, which includes `claim_status` going from `"claimed"` to `"claimed_finalized"`), nor on a refresh that changes nothing. So it stays stable while nothing relevant happens, and finality alone never forces a client to reload. - It covers all of the address's bridges. It is the same whatever `filterBridges`, `page_number` and `page_size` the request used: a single value per address at a given moment. - It is **always present** (never omitted). It is a string such as `"v1:"` followed by 64 lowercase hex characters; the prefix is the version of the hashing scheme, so two instances that hash different fields never agree by accident. Treat it as opaque and **compare the whole string for equality only**: it has no order, so do not parse it or check whether it grew. @@ -549,6 +554,28 @@ Two consequences follow from it being a hash of the content: > An address with no bridges has the empty-activity `revision`: `"v1:"` followed by 64 zeros. +#### Conditional requests (ETag and 304) + +Since `api_revision` 8 the poll of step 2 can skip the body. Every `200` carries the `revision` of its body as the `ETag` header, between double quotes (a strong entity tag, [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3)): + +``` +ETag: "v1:1ab162228afe25b74655b2bfb280cae4926372f5ac13646f341a30053c4a92f1" +Cache-Control: no-store +``` + +A request that sends that value back in `If-None-Match` is answered `304 Not Modified`, with the same headers and **no body**, as long as the address's `revision` is still that one; otherwise it gets the normal `200` with the new `ETag`. + +- The `ETag` is the `revision`, so it is the same for every `filterBridges`, `page_number` and `page_size` of an address: the `ETag` taken from any response can be sent with any other request for the same `from_address`. +- `If-None-Match` accepts a list of entity tags and `*` (always `304`), and a weak tag (`W/"..."`) matches like a strong one, as RFC 9110 defines for this header. The value must be quoted: the bare `revision` does not match. +- It only replaces a `200`. `400`, `500` and `503` (with `Retry-After`) are answered as without the header, and carry no `ETag`. The rest of the request is processed as usual: `flush_cache=true` still flushes, and `includeTracking=true` still marks the address. +- **A `304` means that nothing the `revision` covers changed, not that the body would be identical.** `finalized`, `claim_status` going from `"claimed"` to `"claimed_finalized"`, `last_updated_timestamp`, `tracking` and `warnings` can differ from the response the client holds (see [Rules](#rules)). A client that needs them reloads the page without `If-None-Match`. +- `Cache-Control: no-store` is there for that reason: an HTTP cache (a browser's, mainly) must not store the `200` and revalidate it on its own, because it would then hand its stored body to a client that never asked for a conditional request. Conditional requests are an explicit choice of the client, which sends `If-None-Match` itself. +- **Browser clients on another origin** (see `[REST.CORS]` in `docs/common_config.md`): + - `If-None-Match` is not a CORS-safelisted request header, so the browser sends a preflight and the proxy must allow the header in `[REST.CORS].AllowedHeaders`. The proxy's default is `AllowedHeaders = ["*"]`, which allows it, so nothing has to be added once CORS is enabled with the defaults (CORS itself is disabled by default). A deployment that sets an explicit list instead (e.g. `["Content-Type", "Authorization"]`) must add `"If-None-Match"` to it, or the preflight fails and the browser never sends the request. + - The `ETag` response header is **not** exposed to cross-origin scripts (the CORS configuration has no exposed-headers setting, and `ETag` is not CORS-safelisted). Such a client does not read the header: it builds the tag from the `revision` of the body it holds (`'"' + revision + '"'`). + +Client flow with conditional requests: keep the `revision` of the pages loaded (step 1), poll with `page_size=1` and `If-None-Match: ""` (step 2); a `304` is "unchanged", and a `200` carries the new `revision`, so continue at step 3. A client that does not send `If-None-Match` never receives a `304`. + ### ActivityResponse | field | type | desc |