DEV Community

ErasmusPierce7981
ErasmusPierce7981

Posted on

Property Video Generation: How to Check Capabilities Before Offering Options

Consider a page for a property listing media pipeline: prospective tenants are waiting for photographs, while the on-call dashboard shows a growing backlog of promotional video generation requests. The operator needs to check capabilities before offering more options to users. This is an illustrative alert, not a reported incident.

Short answer: read video generation capabilities at startup, constrain both the form and server validation to supported options, and refresh that information before its cache expires. Keep image compression decisions separate: choose the smallest approved image rendition that preserves the details a tenant needs to inspect, and measure its delivered bytes alongside the media workflow's availability. An HTTP success alone cannot establish either visual quality or a useful form.

For a Node.js application using Express, the capability check belongs in the server's admission path; a browser dropdown is only a presentation of that decision. The Go example below makes the admission policy executable without assuming an undocumented provider response shape. Its fields belong to the application.

1. How should you check video generation capabilities before offering options?

The earlier signal is an expired capability snapshot while the application continues to offer generation options.

Capabilities change without a deployment.

A form built once at release time therefore carries a hidden assumption: every option will remain valid until the next release, even if the underlying service changes in the meantime.

Reject that assumption.

Read capabilities during startup and keep the generation controls unavailable until the application has a validated snapshot. Refresh periodically, with an expiry that the server checks independently of the refresh timer, because a timer firing is not evidence that a refresh succeeded. The form and submission handler should consult the same active snapshot; submission validation must still run when an old browser tab sends an option that has disappeared.

In the property management workflow, this policy protects the optional step that turns listing material into a promotional video. It does not make the photographs depend on video generation. Image compression and delivery deserve their own admission criteria, particularly where fine details in a floor plan or a room photograph determine whether a rendition is acceptable.

Define two SLOs before choosing alert thresholds: one for serving approved listing images and another for accepting supported promotional video requests. Track denied submissions separately from provider request failures. Otherwise, a server correctly rejecting a stale choice can look indistinguishable from a backend outage, and an operator may respond by weakening the very validation that protects the workflow.

There is also a capacity consequence. If an illustrative rollout renders 120 listing pages per minute and each page includes eight images, its delivery budget has to account for 960 image responses per minute before considering cache behavior. Those are planning inputs, not traffic measurements. Video admission should not consume the operational attention needed to keep those photographs usable.

2. Add an expiry gate and a byte-budget signal

Start with a small executable policy probe. Save the following as main.go and run it with go run main.go. It uses only the standard library. Set INFRAI_BASE_URL to the service's HTTPS API base, including its version prefix, and set INFRAI_API_KEY in the process environment. The program reads video capabilities and checks that the response is valid JSON without assuming its fields. The sample video option used later is a local test label, not a provider model or capability identifier; the local fixture is not populated from the fetched document.

The first step is to represent a successfully normalized snapshot. The second is to evaluate that snapshot again at submission time. The third is to report image bandwidth pressure without treating a smaller file as proof of acceptable quality. These steps share one program so their decisions can be inspected together.

package main

import (
    "context"
    "encoding/json"
    "errors"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func capabilities(ctx context.Context) (json.RawMessage, error) {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    u, err := url.Parse(base)
    if err != nil || u.Scheme != "https" || u.Host == "" || key == "" {
        return nil, errors.New("set the HTTPS API base and API key")
    }
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodGet,
            base+"/video/capabilities", nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1048577))
        resp.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if len(body) > 1048576 {
            return nil, errors.New("capability document exceeds local size limit")
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retry := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
                delay = time.Duration(seconds) * time.Second
            } else if until, err := http.ParseTime(retry); err == nil {
                delay = time.Until(until)
                if delay < 0 {
                    delay = 0
                }
            }
            timer := time.NewTimer(delay)
            select {
            case <-ctx.Done():
                timer.Stop()
                return nil, ctx.Err()
            case <-timer.C:
            }
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return nil, fmt.Errorf("capability read: status=%d body=%s", resp.StatusCode, body)
        }
        if !json.Valid(body) {
            return nil, errors.New("capability response is not JSON")
        }
        return json.RawMessage(body), nil
    }
    return nil, errors.New("capability retry limit reached")
}

type Snapshot struct {
    LoadedAt time.Time
    TTL      time.Duration
    Options  map[string]bool
}

func admission(s Snapshot, now time.Time, option string) string {
    if s.LoadedAt.IsZero() || s.TTL <= 0 {
        return "snapshot_missing"
    }
    if now.Before(s.LoadedAt) || !now.Before(s.LoadedAt.Add(s.TTL)) {
        return "snapshot_expired"
    }
    if !s.Options[option] {
        return "option_not_supported"
    }
    return "accepted"
}

type Rendition struct {
    Name            string
    Bytes           int64
    VisuallyApproved bool
}

func choose(images []Rendition) (Rendition, bool) {
    var best Rendition
    found := false
    for _, img := range images {
        if img.Bytes <= 0 || !img.VisuallyApproved {
            continue
        }
        if !found || img.Bytes < best.Bytes {
            best, found = img, true
        }
    }
    return best, found
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    doc, err := capabilities(ctx)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Printf("capability_document_bytes=%d\n", len(doc))
    now := time.Date(2026, time.November, 28, 12, 0, 0, 0, time.UTC)
    s := Snapshot{
        LoadedAt: now,
        TTL:      5 * time.Minute,
        Options:  map[string]bool{"sample-option": true},
    }
    checks := []struct {
        At     time.Time
        Option string
    }{
        {now, "sample-option"},
        {now, "unlisted-option"},
        {now.Add(5 * time.Minute), "sample-option"},
    }
    for _, check := range checks {
        fmt.Printf("video_admission decision=%s\n",
            admission(s, check.At, check.Option))
    }

    images := []Rendition{
        {"room-review-a", 180000, true},
        {"room-review-b", 110000, false},
        {"room-review-c", 140000, true},
    }
    img, ok := choose(images)
    if !ok {
        fmt.Println("image_admission decision=no_approved_rendition")
        return
    }
    const imagesPerPage int64 = 8
    const pagesPerMinute int64 = 120
    const pageBudgetBytes int64 = 1000000
    pageBytes := img.Bytes * imagesPerPage
    fmt.Printf("image_selection name=%s page_bytes=%d bytes_per_minute=%d over_budget=%t\n",
        img.Name, pageBytes, pageBytes*pagesPerMinute,
        pageBytes > pageBudgetBytes)
}
Enter fullscreen mode Exit fullscreen mode

After a successful capability read, the expected fixture decisions are accepted, option_not_supported, and snapshot_expired, in that order.

Expiry is exclusive.

At exactly five minutes, this example denies the choice. That boundary matters when an old tab and a refresh happen at nearly the same time. A real adapter must validate and normalize the fetched document before enabling actual form choices. Valid JSON alone is not a supported-options contract, and the fixture must never become a production allowlist.

For images, the policy selects the 140,000-byte approved rendition, producing a planned 1,120,000 bytes per page and 134,400,000 bytes per minute. It flags the illustrative page budget. It does not select the 110,000-byte file, because a review rejected that rendition's visual quality; all sizes, approvals, and thresholds here are test fixtures rather than benchmark results.

Keep the detail.

In production, replace the printed decisions with counters, record the age of the last successful capability refresh, and publish a validated replacement snapshot atomically. Do not extend the expiry merely because another refresh attempt started. Use bounded decision labels, as the example does, rather than placing listing identifiers or arbitrary user input in metric labels. The network adapter must validate the actual capability response before it populates this local structure; this example deliberately makes no claim about provider JSON fields.

The five-minute TTL is a policy choice to test. Shorter expiry reduces how long a changed option can remain visible, while increasing the importance of timely refreshes; longer expiry reduces refresh pressure but tolerates more stale presentation. Measure refresh duration and option changes before setting the production value. No universal SLO follows from this sample.

3. Choose what to buy and what to operate

The admission policy survives a vendor change, but the operational burden does not disappear. A buy-vs-build review should ask who operates transformations, who approves visual output, and who owns the interface between current capabilities and the form. An image tool and a video generation service also solve different parts of the listing workflow; scoring them as interchangeable products hides the most consequential boundary.

Option Buy-vs-build boundary Quality versus bandwidth decision Operational trade-off
sharp Build an image processing pipeline around a library Evaluate your chosen resize and encoding settings on listing images The team owns workers, capacity, caching, and rollout policy
libvips Build around an image processing library Control the processing recipe and approve the resulting renditions More direct pipeline ownership also means more operational responsibility
Cloudinary Evaluate managed image transformation and delivery Compare candidate transformations against the same approved corpus Assess service dependence and migration of transformation recipes
imgix Evaluate managed image rendering and delivery Review output from the selected rendering parameters Assess URL conventions, cache behavior, and migration work

These are architectural alternatives, not a measured quality ranking. No comparable output corpus or authenticated performance measurements establish a winner here. sharp and libvips belong to the same broad build strategy; adopting a wrapper does not transfer worker operations to a managed service. Neither should be mistaken for a video capability registry.

Infrai offers one key, one bill and one REST API for backend services: a single key and unified billing replace separate credentials and invoices across those integrations, while plain HTTP means no SDK required for the capability reader. This fits a platform team whose roadmap includes reducing credential sprawl and month-end reconciliation. A single REST API accessible from any language lets the reader use the standard HTTP client already deployed with the admission service; its public discovery schemas help validate the adapter. Those properties support an integration decision; they do not establish that an image rendition meets a property's visual acceptance criteria.

Use the same review corpus across candidates: room photographs, exterior views, and floor plans that your team is permitted to process. Record delivered bytes and the reason a reviewer accepts or rejects each rendition. Check browser format compatibility against the image format guide before publishing a format choice. A smaller output is useful only if the intended audience can render it and inspect the necessary details.

4. Close the page without creating a noisier one

Alert on sustained loss of useful admission, and make snapshot age visible before that loss becomes a backlog. A single rejected stale-tab submission should contribute to a diagnostic counter; it should not automatically wake someone. A fleet that cannot obtain fresh capabilities before its current snapshots expire warrants a different response, because that threatens the availability of the video controls themselves.

Keep the image decision independent. A page that exceeds the illustrative byte budget calls for investigation of rendition choices and capacity, not automatic approval of a visually rejected file. Before expanding a rollout, inspect both the image acceptance results and the rate of capability-related denials.

The false-positive cost is real even without attaching a currency figure: an expiry threshold that repeatedly pages during harmless refresh variation consumes on-call attention and encourages bypasses, while a bandwidth alarm tied to every individual photograph penalizes listings whose visual detail is necessary. Tune thresholds against observed demand and the chosen SLOs. The correct result is an alert that identifies the action an operator can take.

References

The following primary documentation supports the image format review and the buy-vs-build alternatives. It is not evidence of a shared performance benchmark or a particular property's quality requirements.

Further reading

Top comments (0)