Skip to content

fix(dashboard): resolve guest users in Excel export instead of crashing on g.user.id - #43340

Closed
gabotorresruiz wants to merge 18 commits into
apache:fix/excel-export-guest-sessions-and-s3-link-expiryfrom
gabotorresruiz:gabotorresruiz/fix-excel-export-guest-user-id
Closed

gabotorresruiz wants to merge 18 commits into
apache:fix/excel-export-guest-sessions-and-s3-link-expiryfrom
gabotorresruiz:gabotorresruiz/fix-excel-export-guest-user-id

Conversation

@gabotorresruiz

@gabotorresruiz gabotorresruiz commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

SUMMARY

Targets fix/excel-export-guest-sessions-and-s3-link-expiry (#43336), not master. It fixes a bug in that PR's guest path and is meant to merge into it, so the guard removal and this fix travel together.

#43336 removes the isinstance(g.user, GuestUser) guard that returned 400 so embedded guests can export, but export_xlsx still calls g.user.id (for the throttle lock params and the Celery task's user_id). GuestUser extends AnonymousUserMixin and has no id attribute, so a guest POST crashes with AttributeError and returns 500 {"message": "Fatal error"} before the task is ever enqueued. Verified empirically on a staging deployment carrying #43336's changes: the embedded export button returned exactly that 500; with this fix applied the export goes through.

The fix mirrors _load_user_from_job_metadata in superset/tasks/async_queries.py:

  • The endpoint passes user_id=get_user_id() (None for guests) plus guest_token=getattr(g.user, "guest_token", None).
  • The task reconstructs the guest via security_manager.get_guest_user_from_token(...), so the export runs under the token's RLS rules and resource claims, never under an elevated identity.
  • Guests share throttle lock slot 0 per dashboard, acquired and released with the same key.

ADDITIONAL INFORMATION

@dosubot dosubot Bot added authentication Related to authentication change:backend Requires changing the backend dashboard:export Related to exporting dashboards labels Aug 19, 2026
@bito-code-review

bito-code-review Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Bito Automatic Review Skipped - Branch Excluded

Bito didn't auto-review because the source or target branch is excluded from automatic reviews.
No action is needed if you didn't intend for the agent to review it. Otherwise, to manually trigger a review, type /review in a comment and save.
You can change the branch exclusion settings here, or contact your Bito workspace admin at [email protected].

@netlify

netlify Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for superset-docs-preview ready!

Name Link
🔨 Latest commit ee331bc
🔍 Latest deploy log https://app.netlify.com/projects/superset-docs-preview/deploys/6a91deae593bbd00098f51d8
😎 Deploy Preview https://deploy-preview-43340--superset-docs-preview.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 50.28571% with 87 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (fix/excel-export-guest-sessions-and-s3-link-expiry@26fabcf). Learn more about missing BASE report.

Files with missing lines Patch % Lines
superset/tasks/export_dashboard_excel.py 20.00% 28 Missing ⚠️
superset/utils/gcs.py 0.00% 26 Missing ⚠️
superset/utils/s3.py 0.00% 22 Missing ⚠️
...hboard/components/menu/DownloadMenuItems/index.tsx 77.77% 10 Missing ⚠️
superset/dashboards/api.py 95.83% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@                                  Coverage Diff                                  @@
##             fix/excel-export-guest-sessions-and-s3-link-expiry   #43340   +/-   ##
=====================================================================================
  Coverage                                                      ?   66.65%           
=====================================================================================
  Files                                                         ?     2876           
  Lines                                                         ?   163855           
  Branches                                                      ?    37796           
=====================================================================================
  Hits                                                          ?   109213           
  Misses                                                        ?    52513           
  Partials                                                      ?     2129           
Flag Coverage Δ
hive 38.15% <23.84%> (?)
javascript 73.78% <77.77%> (?)
mysql 57.83% <40.76%> (?)
postgres 57.86% <40.76%> (?)
presto 40.09% <23.84%> (?)
python 59.25% <40.76%> (?)
sqlite 57.50% <40.76%> (?)
unit 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@bito-code-review

Copy link
Copy Markdown
Contributor

The flagged issue is correct. In superset/tasks/export_dashboard_excel.py, the guest user reconstruction (security_manager.get_guest_user_from_token(guest_token)) occurs before the try/finally block that ensures the distributed lock is released. If this reconstruction fails, the task terminates without releasing the lock, causing subsequent exports for that dashboard to be blocked until the TTL expires.

To resolve this, move the user reconstruction logic inside the try block or ensure the lock is released in a finally block that covers the entire execution path. Given the current structure, wrapping the user initialization in the try block is the most straightforward fix.

superset/tasks/export_dashboard_excel.py

# ... (previous code)
    requested_at = datetime.now(tz=timezone.utc)
    try:
        if user_id is not None:
            user = security_manager.get_user_by_id(user_id)
        elif guest_token:
            user = security_manager.get_guest_user_from_token(guest_token)
        else:
            user = None
        # ... (rest of the logic)
    finally:
        # ... (lock release logic)

@gabotorresruiz
gabotorresruiz force-pushed the gabotorresruiz/fix-excel-export-guest-user-id branch from 4ad2fcd to 619bd26 Compare August 19, 2026 19:22
@pull-request-size pull-request-size Bot added size/L and removed size/M labels Aug 19, 2026
…ng on g.user.id

GuestUser extends AnonymousUserMixin and has no id attribute, so an
embedded guest triggering export_xlsx crashed with AttributeError (500
Fatal error) on g.user.id before the task was ever enqueued. Pass
user_id=None plus the guest token payload instead, and reconstruct the
guest in the worker via get_guest_user_from_token (the async-queries
pattern) so the export runs under the token's RLS rules and resource
claims rather than an elevated identity. Guests share throttle-lock
slot 0 per dashboard, acquired and released with the same key.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
@gabotorresruiz
gabotorresruiz force-pushed the gabotorresruiz/fix-excel-export-guest-user-id branch from 619bd26 to 4423f50 Compare August 19, 2026 19:31
gabotorresruiz and others added 2 commits August 19, 2026 20:10
…est access

Guest datasource authorization requires form_data.dashboardId to link a
chart to the embedded dashboard (raise_for_access). The browser stamps
it on every interactive request, but the export task replays saved query
contexts that do not carry it, so every chart in a guest export failed
the access check and the workbook came back empty. Stamp the exporting
dashboard's id the same way the browser does; logged-in exports already
carry dashboard scope and are unaffected.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
Embedded (iframe) sessions get delivery neutral toast copy (no email
promise a guest can never receive), a polling window that outlives the
server task budget so a slow but successful export is not orphaned, and
the image export item hidden (the webdriver cannot render Explore under
a guest identity, so it would burn the whole task budget producing
nothing). The pending toast now mirrors the screenshot download's
repeating noDuplicate info toast for all sessions.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
gabotorresruiz and others added 3 commits August 20, 2026 13:55
…s redirect

The direct window.location.href assignment from the base branch trips
the navigationUtils invariant scan: it bypasses ensureAppRoot (broken
under subdirectory deployment) and the scheme guard. Use redirect()
instead; tests assert the redirect call rather than the raw sink.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
…t toast

Customer feedback showed the email-only wording made the export read as
an email delivery feature, prompting requests for a direct download that
already exists. Promise both channels, matching actual behavior.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
…mplementation

superset/utils/s3.py is hardcoded to boto3/AWS S3, so a deployment whose
EXCEL_EXPORT_S3_BUCKET names a native Google Cloud Storage bucket (not an
S3-compatible one) has no way to make dashboard Excel export actually reach
it: uploads and pre-signed download URLs both go through boto3 regardless.

Add EXCEL_EXPORT_STORAGE, an optional config hook following the same
"instance in config" idiom as RESULTS_BACKEND/CUSTOM_SECURITY_MANAGER: set it
to an object implementing the small ExportStorage protocol (upload_file,
generate_download_url) to take over both the task's upload and the download
redirect's URL minting. Left unset, behavior is unchanged -- the existing
boto3/S3 helpers run exactly as before.

Ship GCSExportStorage (superset/utils/gcs.py) as a ready-to-use
implementation for GCS-backed deployments, using the native
google-cloud-storage client (Application Default Credentials) rather than
S3-compatible interop credentials. google-cloud-storage is imported lazily
and is only required if GCSExportStorage is actually configured, via a new
excel-export-gcs extra (mirroring the existing excel-export/boto3 extra).
… dict

EXCEL_EXPORT_S3_BUCKET/EXCEL_EXPORT_S3_KEY_PREFIX were misleadingly named --
both are actually provider-agnostic (used by whichever EXCEL_EXPORT_STORAGE
backend is configured, not just S3), while EXCEL_EXPORT_S3_CLIENT_KWARGS is
genuinely S3/boto3-specific and only applies to the default backend. Having
these three flat, S3-flavored names sit alongside the newly-introduced,
correctly-generic EXCEL_EXPORT_STORAGE was confusing.

Fold bucket/key_prefix/client_kwargs/backend into a single
ExcelExportStorageConfig TypedDict under EXCEL_EXPORT_STORAGE, e.g.:

    EXCEL_EXPORT_STORAGE = {
        "bucket": "my-gcs-bucket",
        "backend": GCSExportStorage(),
    }

EXCEL_EXPORT_LINK_TTL_SECONDS stays a separate top-level setting: it bounds
the Superset-issued redirect link itself, independent of which storage
backend or bucket is configured.
Plain "backend" reads ambiguously next to the dict key of the same name;
storage_backend matches what it actually holds.
…bucket configured

The API already rejects export_xlsx with 501 when EXCEL_EXPORT_STORAGE has
no bucket, but the Celery task itself trusted that check had already run.
If the config is cleared after enqueue, or the task is invoked directly,
it now fails with a clear SupersetException instead of an opaque
boto3/SDK error for a None bucket.
…removing the implicit S3 fallback

A bucket alone was never enough to run exports (boto3 would fail without
S3 credentials/config), yet the code silently defaulted to the boto3/S3
helper whenever EXCEL_EXPORT_STORAGE["backend"] was unset. The backend is
now a required part of the config, symmetric across providers:

    from superset.utils.s3 import S3ExportStorage   # or gcs.GCSExportStorage
    EXCEL_EXPORT_STORAGE = {"bucket": "...", "backend": S3ExportStorage()}

- superset/utils/s3.py module functions become an S3ExportStorage class
  implementing the ExportStorage protocol; boto3 client_kwargs move from
  the config dict to its constructor
- the export_xlsx 501 guard and the task's defensive check now require
  both "bucket" and "backend"; the download route reports 501 instead of
  falling back to boto3 when the backend is unset
- docs and UPDATING.md updated to the consolidated config shape (they
  still described the pre-consolidation flat EXCEL_EXPORT_S3_* keys)
The storage config is not Excel-specific -- it names a bucket, a key
prefix, and a pluggable backend, all of which apply equally to any other
export file type stored there in the future. Only the storage config is
renamed (ExcelExportStorageConfig -> ExportStorageConfig too); the
genuinely Excel-specific keys (EXCEL_EXPORT_LINK_TTL_SECONDS,
EXCEL_EXPORT_TABLE_VIZ_TYPES, EXCEL_EXPORT_QUERY_CONTEXT_BUILDER) keep
their names.
A multi-tenant deployment sharing one export bucket across tenants only
knows the per-tenant prefix in request/task context, the same reason the
cache *_KEY_PREFIX configs accept callables. A callable is invoked per
export; a plain string keeps working unchanged.
@github-actions github-actions Bot added the doc Namespace | Anything related to documentation label Aug 26, 2026
…ials

Token-only Application Default Credentials (GKE workload identity, GCE
metadata, Cloud Run) carry no private key, so local V4 signing raised
AttributeError and every download click returned 500 while the upload
itself succeeded. Route signing through the IAM signBlob API by passing
the service account email and a fresh access token; key-file credentials
keep signing locally. Also makes the missing-dependency test
deterministic and drops a stale note about the S3 pre-signed cap.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
Comment thread superset/dashboards/api.py Resolved
);
return;
}
addExportPendingToast();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This re-adds the pending info toast on every poll. Because the toast expires after four seconds while polling continues every three, it is recreated and announced repeatedly throughout a slow export—up to roughly 120 times during the embedded window. Could the pending status be shown once (or updated without a new alert) until the export reaches a terminal state?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept as is deliberately: this mirrors useDownloadScreenshot's existing repeating info toast with noDuplicate, and consistency between the two download flows matters more to us than reducing the re announcements. Happy to revisit both flows together in a follow up if the repetition proves to be a real problem.

…gning

Review follow-ups:
- run anonymous (Public-role) requesters under the anonymous principal
- reject guest mode=images at the API, not just in the menu
- gate delivery copy, poll window, and image export on the requester
  identity instead of iframe detection
- record a running status when a worker starts, and restart the client's
  wait window on it so queue delay is not counted against the export
- record the uploading storage backend on the download link and refuse
  to sign with a different backend
- docs: guest polling flow, link vs storage URL lifetime, web-tier
  storage permissions

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
Comment thread UPDATING.md Resolved
Comment thread superset/dashboards/api.py Resolved
if user_id is not None:
return security_manager.get_user_by_id(user_id)
if guest_token:
return security_manager.get_guest_user_from_token(guest_token)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rebuilds the guest principal from the already-decoded payload, so a task that waits in Celery can run after the token expires or is revoked. Could the worker revalidate the guest token/claims before querying chart data, so delayed exports do not continue using stale guest access?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping as is, deliberately: this mirrors superset.tasks.async_queries, which reconstructs the guest from the already validated payload. The access decision is enforced at request time via raise_for_access, guest tokens are short lived stateless JWTs with no server side revocation to consult, and enforcing exp in the worker would fail every legitimately queued export since tokens routinely expire within a normal queue wait. If delayed execution under a stale token is a concern worth addressing, I think it belongs to both consumers together as a follow up rather than this PR.

Comment thread superset/utils/gcs.py Resolved
# and resource claims) from the token payload passed alongside.
user_id = get_user_id()
lock_params = export_lock_params(user_id or 0, dashboard.id)
try:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This TTL starts at enqueue but the task's execution budget starts only when Celery picks it up, so queue delay can let the lock expire while the first export is still running. Could the worker renew/own the lock for its execution (and release only its own lease) so a delayed task cannot overlap or delete a later export's replacement lock?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Real but bounded, and I would defer it: the worst case is a second concurrent export while the first finishes, and the throttle is best effort by design. This base branch's release is an unconditioned delete with no extend primitive, so renewing from the task would be a release plus acquire, which is itself a race. Master already has ownership checked release (compare and delete); the clean fix is lease extension plus owned release when this stack rebases onto master, and I am happy to file that follow up.

… gates

Second review round:
- transaction-wrap the export status writes: the worker session otherwise
  only commits when the task settles, so the running marker was invisible
  to polling web pods exactly when it mattered
- reject mode=images for any session without a user id (anonymous too),
  matching the UI's predicate
- request an explicit scope for the GCS signBlob credentials, which
  external-account/workload-identity ADC needs to refresh
- one 12 minute poll window for every session: the export email is
  best-effort (SMTP optional, send failures swallowed), so the client
  cannot treat it as a fallback and stop polling early
- cover the API-to-worker guest handoff (user_id None + token payload +
  lock slot 0) with an integration test
- UPDATING.md: SMTP is optional, email delivery only

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
@gabotorresruiz
gabotorresruiz force-pushed the gabotorresruiz/fix-excel-export-guest-user-id branch from 2739f7e to 23b9873 Compare August 27, 2026 00:13
"active_data_mask": payload.get("active_data_mask", {}),
"job_id": job_id,
"mode": payload.get("mode", "data"),
"guest_token": (

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

During a web-before-worker rollout, older workers still registered without guest_token reject this message before the task can record failure or release the lock. That leaves the export pending until its TTL expires. Could this be made rollout-compatible (for example by staging the task signature change or versioning the task)?

Comment thread superset/config.py
backend: ExportStorage


EXPORT_STORAGE: ExportStorageConfig = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This replaces the supported EXCEL_EXPORT_S3_* configuration with an empty EXPORT_STORAGE without a compatibility path. An existing S3 deployment that upgrades unchanged will now receive 501 for every export. Could the legacy settings be preserved as a deprecated fallback or migrated explicitly?

if (status === 'ready') {
if (downloadUrl) {
window.location.href = downloadUrl;
redirect(downloadUrl);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The no-email flow now depends on this URL, but the status endpoint builds it from WEBDRIVER_BASEURL_USER_FRIENDLY, whose default is http://0.0.0.0:8080/. In a normal deployment that has not configured the webdriver/email base URL, a guest export completes but redirects the browser to an unreachable address with no email fallback. Could the polling response use a same-origin download path or make this configuration an explicit prerequisite?

)
backend_cls = type(storage_backend)
configured_backend = f"{backend_cls.__module__}.{backend_cls.__qualname__}"
if uploaded_backend is not None and uploaded_backend != configured_backend:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only compares the backend class, not the backend configuration. If an export is uploaded through S3ExportStorage(endpoint_url=old-minio) and the web tier switches to another S3ExportStorage endpoint, the check passes and the redirect signs the stored key against the wrong service. Could the stored link bind enough backend identity to reject this same-class migration too?

Replace the signed storage URL redirect with streaming the object
through the download endpoint using the deployment's own storage
credentials. Signing is impossible for some ambient identities: direct
workload identity federation has no service account to sign as, so the
IAM signBytes call failed with 400 "Invalid form of account ID
<project>.svc.id.goog" on GKE clusters using principal-based grants.
A signed URL is also a transferable bearer credential Superset can
neither observe nor revoke once issued; streaming keeps the unguessable
job id as the only credential and every download inside Superset.

The ExportStorage protocol swaps generate_download_url for a chunked
download method (FileNotFoundError for missing objects, answered as
410), and the whole signing apparatus (GCS signBlob fallback, IAM role
prerequisite, presigned TTL) is removed along with its docs.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
@gabotorresruiz

Copy link
Copy Markdown
Contributor Author

Design change in ee331bc, driven by a production failure: on GKE clusters using direct workload identity federation (IAM grants to the Kubernetes principal, no Google service account bound), every download click failed with TransportError from the IAM signBytes API: 400 "Invalid form of account ID .svc.id.goog". There is no service account to sign as in that identity mode, so no signing design can work there.

The download endpoint now streams the object through Superset with the deployment's own storage credentials instead of redirecting to a signed URL. The ExportStorage protocol swaps generate_download_url for a chunked download method (FileNotFoundError becomes a clean 410), and the whole signing apparatus is removed: the GCS signBlob fallback, the serviceAccountTokenCreator prerequisite, the presigned TTL, and their docs. Security model is unchanged (the unguessable job id remains the credential) and strictly tighter: no transferable bearer URL is ever minted, and every download is observable and revocable server side. Unit and integration suites updated and green.

@eschutho eschutho left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the four commits since the storage chain merge (100023b0 → ee331bc7). Solid round — the streaming pivot is the right call given signing is architecturally impossible under direct workload identity federation, and a few of these fixes are subtle and well caught:

  • The @transaction() on the status writes fixes a real visibility bug: the worker session previously only committed when the task settled, so the running marker would've been invisible to polling web pods exactly when it mattered.
  • Recording the uploading backend on the download link and refusing to serve with a mismatched one is good defensive design for storage migrations — and backward-compatible for links written before it was tracked.
  • The eager first-chunk pull (missing object → clean 410 instead of dying mid-response) and the once-only poll-deadline restart on running (sawRunning guard, so no infinite extension) both read correct.
  • Identity-based gating replacing iframe detection, and the anonymous-principal resolution mirroring async_queries, are both improvements.

One change request:

Set Content-Length on the streamed download response. If storage errors mid-stream (credential refresh failure, network blip), the 200 has already been sent — the client silently receives a truncated .xlsx that Excel rejects as corrupt, with no error surfaced anywhere. Both backends can supply the size nearly free: S3's get_object response already carries ContentLength, and GCS needs one metadata fetch (blob.reload() / blob.size) before opening the stream. With Content-Length set, browsers detect truncation and mark the download as failed instead of saving a corrupt file — and users get a real progress bar. One shape for it: have download() return (size, Iterator[bytes]) (or a small dataclass), since both backends learn the size in the same call that opens the stream.

Two nits, take or leave: an empty object currently streams as a 200 empty attachment (unreachable in practice given exports are never empty), and the attachment filename is still {job_id}.xlsx — using the dashboard title would be a nice touch someday, but that predates this diff.

download() now returns (size, chunks): S3 reads ContentLength off the
get_object response it already makes, GCS adds one metadata fetch that
doubles as an eager existence check. With a declared length, a stream
that dies midway is a failed download in the browser instead of a
silently truncated file Excel rejects as corrupt, and users get a real
progress bar.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012HwFSVNUzsZ4xW6D8Y2n95
@gabotorresruiz

Copy link
Copy Markdown
Contributor Author

Thanks Elizabeth! Content-Length added in 5da2b36 with the shape you suggested: download() now returns (size, chunks) as a small NamedTuple, S3 reads ContentLength off the get_object call it already makes, and GCS does one blob.reload() that doubles as an eager existence check, which also let me drop the first chunk pull trick from the endpoint. Integration test asserts the header. On the nits: agreed the empty object case is unreachable (every export carries at least the summary sheet), and the dashboard title filename is a nice follow up since the job record would need to carry the title; leaving both as is for this PR.

@gabotorresruiz

Copy link
Copy Markdown
Contributor Author

Superseded by #43805, which consolidates this stack with #43336 onto current master (same commits, review fixes included, suites green). Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Related to the REST API authentication Related to authentication change:backend Requires changing the backend dashboard:export Related to exporting dashboards doc Namespace | Anything related to documentation size/XXL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants