Skip to content
Open
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
39 changes: 37 additions & 2 deletions apps/server/internal/platform/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,20 @@ type HTTPError struct {
Subcode string
TraceID string
RetryAfter time.Duration

// providerStatus is the status before a Meta mapping replaced StatusCode
// with a recovery status. It is zero while no mapping replaced it, and
// survives repeated classification. Errors embedded in an HTTP 200 body
// start as 400.
providerStatus int
}

// providerHTTPStatus returns the status before Meta recovery mapping.
func (e *HTTPError) providerHTTPStatus() int {
if e.providerStatus != 0 {
return e.providerStatus
}
return e.StatusCode
}

func (e *HTTPError) Error() string {
Expand Down Expand Up @@ -157,15 +171,33 @@ type metaCodeKey struct {
type metaMapping struct {
status int
code string
// serverErrorCode names the outcome when Meta answered with HTTP 5xx or
// 408. The mapping then keeps the provider's status instead of forcing
// mapping.status: a write that Meta may already have accepted must not
// become a definite client-error rejection that is safe to repeat.
serverErrorCode string
}

func applyMetaMapping(providerErr *HTTPError, mapping metaMapping) {
if mapping.serverErrorCode != "" && isMetaServerStatus(providerErr.StatusCode) {
providerErr.Code = mapping.serverErrorCode
return
}
if mapping.status != 0 {
if providerErr.providerStatus == 0 {
providerErr.providerStatus = providerErr.StatusCode
}
providerErr.StatusCode = mapping.status
}
providerErr.Code = mapping.code
}

// isMetaServerStatus reports a status that leaves the outcome of a write
// unknown, which downstream write tracking treats as ambiguous.
func isMetaServerStatus(status int) bool {
return status >= http.StatusInternalServerError || status == http.StatusRequestTimeout
}

// metaExactMappings classifies {code, subcode} pairs where the subcode
// changes the recovery action (Postiz #2127).
var metaExactMappings = map[metaCodeKey]metaMapping{
Expand Down Expand Up @@ -216,8 +248,11 @@ var metaCodeMappings = map[string]metaMapping{
"80003": {status: http.StatusTooManyRequests, code: "meta:rate_limit:80003"},
"80004": {status: http.StatusTooManyRequests, code: "meta:rate_limit:80004"},
"80006": {status: http.StatusTooManyRequests, code: "meta:rate_limit:80006"},
"1": {status: http.StatusBadRequest, code: "meta:rejected:1"},
"2": {status: http.StatusServiceUnavailable, code: "meta:transient:2"},
// Code 1 is Meta's generic "unknown error". It is a rejection only when
// Meta answers with a client error; after a 5xx or 408 the write may
// already have been accepted.
"1": {status: http.StatusBadRequest, code: "meta:rejected:1", serverErrorCode: "meta:transient:1"},
"2": {status: http.StatusServiceUnavailable, code: "meta:transient:2"},
}

// isMetaTerminalMediaCode reports whether a numeric Meta code is a known
Expand Down
17 changes: 17 additions & 0 deletions apps/server/internal/platform/export_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package platform

import (
"net/http"
"testing"
)

// ReplaceHTTPClientForTest lets tests in the external platform_test package
// route provider requests through a fake transport. The previous client is
// restored when the test ends. Callers must not run in parallel, because the
// client is shared by every adapter.
func ReplaceHTTPClientForTest(t testing.TB, client *http.Client) {
t.Helper()
original := httpClient
httpClient = client
t.Cleanup(func() { httpClient = original })
}
51 changes: 51 additions & 0 deletions apps/server/internal/platform/facebook_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package platform

import (
"errors"
"io"
"net/http"
"net/url"
Expand Down Expand Up @@ -99,3 +100,53 @@ func TestFacebookVideoResumeSurfacesConfirmedProviderRejection(t *testing.T) {
})
}
}

// Meta can accept the finish call and still answer HTTP 5xx with Graph code 1.
// Only a client error proves the finish was refused.
func TestFacebookReelFinishUnknownErrorIsRejectedOnlyForClientErrors(t *testing.T) {
for _, tc := range []struct {
name string
status int
wantStatus int
wantSubmission PublishSubmissionState
wantRetry PublishRetrySafety
wantCode string
}{
{"client error", http.StatusBadRequest, http.StatusBadRequest, PublishSubmissionRejected, PublishRetryNever, "meta:rejected:1"},
{"server error", http.StatusInternalServerError, http.StatusInternalServerError, PublishSubmissionPending, PublishRetryReconcileOnly, "meta:transient:1"},
{"request timeout", http.StatusRequestTimeout, http.StatusRequestTimeout, PublishSubmissionPending, PublishRetryReconcileOnly, "meta:transient:1"},
} {
t.Run(tc.name, func(t *testing.T) {
original := httpClient
defer func() { httpClient = original }()
httpClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
switch {
case req.URL.Host == "rupload.facebook.com":
return jsonResponse(req, `{"success":true}`), nil
case req.Method == http.MethodGet:
return jsonResponse(req, `{"status":{"video_status":"ready","uploading_phase":{"status":"complete"}}}`), nil
}
body, _ := io.ReadAll(req.Body)
form, _ := url.ParseQuery(string(body))
if form.Get("upload_phase") == "start" {
return jsonResponse(req, `{"video_id":"video-1","upload_url":"https://rupload.facebook.com/video-1"}`), nil
}
return jsonResponseWithStatus(req, tc.status, `{"error":{"message":"An unknown error occurred","code":1}}`), nil
})}

result, err := NewFacebookAdapter("", "", "").Publish(t.Context(), "page-token", "page-1", &PublishRequest{
Profile: "short_video",
OutputProfile: "facebook.reel",
PlatformMediaIDs: []string{"https://media.example/video.mp4"},
Media: []MediaItem{{ID: "media-1", MimeType: "video/mp4"}},
})
var providerErr *HTTPError
if !errors.As(err, &providerErr) || providerErr.Code != tc.wantCode || providerErr.StatusCode != tc.wantStatus {
t.Fatalf("unexpected provider error %v", err)
}
if result.SubmissionState != tc.wantSubmission || result.RetrySafety != tc.wantRetry || result.ProviderReference != "fb1:publishing:video-1" {
t.Fatalf("finish outcome must follow the provider status: %+v", result)
}
})
}
}
57 changes: 54 additions & 3 deletions apps/server/internal/platform/instagram.go
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,12 @@ func (i *InstagramAdapter) publishStories(ctx context.Context, accessToken, inst
}
publishedID, err := i.publishMediaContainer(ctx, accessToken, instagramUserID, containerID, req, pendingInstagramStoryResult(index, ids, containerID))
if err != nil {
return "", instagramStoryFailure(pendingInstagramStoryResult(index, ids, containerID), err)
// The publish intent is already saved. Report it, not the earlier
// reusable-container reference: a resume that finds the container
// FINISHED publishes it again from ig1:s, but only waits from ig1:t.
// A confirmed readiness or rate-limit rejection maps back to ig1:s
// itself.
return "", instagramStoryFailure(pending, err)
}
ids = append(ids, publishedID)
if index+1 < len(req.PlatformMediaIDs) {
Expand Down Expand Up @@ -1415,7 +1420,7 @@ func instagramPendingOrRejected(pending PublishResult, err error) (PublishResult
return outcome.result, outcome.err
}
err = normalizeMetaPublishError(err)
if instagramIsReadinessRejection(err) {
if instagramIsReadinessRejection(err) && instagramRejectionConfirmed(err) {
checkpoint, parseErr := parseInstagramPublishCheckpoint(pending.ProviderReference)
if parseErr == nil {
switch checkpoint.kind {
Expand All @@ -1429,6 +1434,9 @@ func instagramPendingOrRejected(pending PublishResult, err error) (PublishResult
}
return pending, err
}
if reusable, ok := instagramRateLimitRetryCheckpoint(pending, err); ok {
return instagramPendingWithError(reusable, err)
}
var providerErr *HTTPError
if errors.As(err, &providerErr) && providerErr.StatusCode >= 400 && providerErr.StatusCode < 500 && providerErr.StatusCode != http.StatusRequestTimeout && providerErr.StatusCode != http.StatusTooManyRequests {
pending.SubmissionState = PublishSubmissionRejected
Expand All @@ -1438,6 +1446,41 @@ func instagramPendingOrRejected(pending PublishResult, err error) (PublishResult
return instagramPendingWithError(pending, err)
}

// instagramRejectionConfirmed reports whether Meta refused the request with a
// client error. It reads the status Meta sent, not the recovery status that
// classification may have substituted: a 5xx or 408 with a rate-limit or
// readiness code classifies the same way but proves nothing about whether the
// write happened.
func instagramRejectionConfirmed(err error) bool {
var providerErr *HTTPError
if !errors.As(err, &providerErr) {
return false
}
status := providerErr.providerHTTPStatus()
return status >= http.StatusBadRequest && status < http.StatusInternalServerError && status != http.StatusRequestTimeout
}

// instagramConfirmedRateLimit reports a rate-limit answer Meta sent as a
// client error, which proves the request was refused.
func instagramConfirmedRateLimit(err error) bool {
var providerErr *HTTPError
return errors.As(err, &providerErr) && providerErr.StatusCode == http.StatusTooManyRequests && instagramRejectionConfirmed(err)
}

// instagramRateLimitRetryCheckpoint returns the reusable-container checkpoint
// a Story goes back to after Meta confirmed a rate-limit rejection of its
// media_publish. Other publishes keep the checkpoint they have.
func instagramRateLimitRetryCheckpoint(pending PublishResult, err error) (PublishResult, bool) {
if !instagramConfirmedRateLimit(err) {
return PublishResult{}, false
}
checkpoint, parseErr := parseInstagramPublishCheckpoint(pending.ProviderReference)
if parseErr != nil || checkpoint.kind != instagramCheckpointStoryPostKind {
return PublishResult{}, false
}
return pendingInstagramStoryResult(checkpoint.currentIndex, checkpoint.references, checkpoint.containerID), true
}

func instagramPendingWithError(pending PublishResult, err error) (PublishResult, error) {
err = normalizeMetaPublishError(err)
if delay := instagramRateLimitReconcileDelay(err); delay > pending.ReconcileAfter {
Expand Down Expand Up @@ -1490,7 +1533,8 @@ func (i *InstagramAdapter) publishMediaContainer(ctx context.Context, accessToke
}
return "", &instagramPublishOutcome{result: pending, err: fmt.Errorf("instagram media publish: %w", err)}
}
if instagramIsReadinessRejection(err) {
if (instagramIsReadinessRejection(err) && instagramRejectionConfirmed(err)) || (instagramConfirmedRateLimit(err) && instagramIsStoryCheckpoint(retryCheckpoint)) {
// Only a confirmed refusal returns to the reusable container.
if checkpointErr := req.Checkpoint(retryCheckpoint); checkpointErr != nil {
return "", checkpointErr
}
Expand All @@ -1500,6 +1544,13 @@ func (i *InstagramAdapter) publishMediaContainer(ctx context.Context, accessToke
return instagramIDFromResponse("instagram media publish", respBody)
}

// instagramIsStoryCheckpoint reports whether result is a Story's reusable
// container checkpoint.
func instagramIsStoryCheckpoint(result PublishResult) bool {
checkpoint, err := parseInstagramPublishCheckpoint(result.ProviderReference)
return err == nil && checkpoint.kind == instagramCheckpointStoryKind
}

func isMetaUnavailableTarget(err error) bool {
var providerErr *HTTPError
return errors.As(err, &providerErr) && providerErr.Code == metaUnavailableTargetCode
Expand Down
Loading