Skip to content

V3 reroll - #395

Open
drzraf wants to merge 12 commits into
flowjs:v3from
drzraf:v3-next
Open

drzraf wants to merge 12 commits into
flowjs:v3from
drzraf:v3-next

Conversation

@drzraf

@drzraf drzraf commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator

A reroll on top of v3 fixing the major blocking point remaining on this branch.

The recursive XHR upload flow (replaced with one async session), which was still subject to odd race-conditions and was the single most cognitively painful and bug-prone point.
-> (Flow.uploadNextChunk(), FlowChunk.readFinished() and preprocessFinished() are removed)

It achieves #368 async formalization (asyncReadFileFn is removed. readFileFn is always awaited, await flow.upload() now waits for the session to settle)

Regarding hooks:

  • Remove DeferredPromise and simplify hook system (flow.on/off/once are removed, no global EventTarget.prototype overloading). addEventListener, + removeEventListener and {once: true} instead.
  • Hooks are configured through hooks: { ... } instead of on('file-added'), no name-based hook/event dispatch.
Hook Arguments Purpose
filterFile (file, {event, flow}) Return false to skip the file. All filters are AND-ed.
fileAdded (flowFile, {event, flow}) Runs after bootstrap, before the file is queued. Delete flowFile.file to reject it.
filesAdded (flowFiles, {event, flow}) May reorder or mutate the array before queuing.
filesSubmitted (flow.files, {event, flow}) Runs after the files are queued. A good place to call flow.upload().

Other long-standing problems:

  • True End-Of-Stream indicator, so that streamable can be done. In case of unknown length, progress indicator can still be provided as a hint
  • Better job regarding stateful / non-seekable reader error (and caching/dropping hunks)
  • simplified the CI (rollup + terser) and added a bunch of test for each changed aspect

Replaces:

Fixes

Previous conversations and debates involved:

100% product of (heavily guided) supervised Deepseek

…sion

- Add a promise-based XHR transport; listeners only resolve requests.
- Introduce an explicit chunk state machine and a payload sentinel
  (undefined=unread, null=EOF, zero-length Blob=valid empty payload).
- Replace uploadNextChunk recursion and the Queue/Deferred experiment with
  an async-generator read queue and a bounded worker pool.
- Make upload() completion-oriented and idempotent while a session is
  active; resume() continues the same session.
- Abort async reads on pause/cancel and re-check the file state after each
  read, so a chunk read that spans a pause/cancel is never uploaded (flowjs#368).
- Send exactly one zero-byte request for empty files (flowjs#375).
- Rewrite retries as loops with abortable delays.

Fixes flowjs#346
Fixes flowjs#375
Refs: flowjs#319, flowjs#353, flowjs#354, flowjs#363, flowjs#368
- Flow now extends EventTarget; remove Eventizer and the global
  EventTarget.prototype monkey patch.
- Events are CustomEvent instances with object details and a catch-all
  event carrying {type, hook, detail}.
- Hooks are explicit options (filterFile, fileAdded, filesAdded,
  filesSubmitted), each accepting a function or an array. Hook errors
  are reported via the error event instead of breaking addFiles.
- addFile(s) now take {event, initFileFn} options instead of positional
  arguments.

Refs: flowjs#319, flowjs#346, flowjs#353
- Pause/cancel no longer flips a chunk out of 'reading' before the reader
  returns. The session discards a stale read result, preserving the flowjs#368
  guarantee: a chunk read that spans a pause/cancel is never uploaded.
- A direct chunk.send() after cancel reports 'cancelled'.
- Capture the browse input before awaiting in assignBrowse; event.target
  can be cleared once the synchronous change dispatch ends.
- Feature-detect directory support on a file input instead of user-agent
  matching, ported from v2 (flowjs#390).
- Document that prioritizeFirstAndLastChunk requires a seekable reader.

Refs: flowjs#368, flowjs#390
- Replace Babel/core-js/Grunt/Karma/SauceLabs with Rollup + Terser only.
- Emit ESM, UMD, minified UMD and CommonJS bundles from one source.
- Remove legacy Grunt, Karma, Bower and Meteor manifests.
- Set version 3.0.0-alpha.1 and inject it with output.intro.
- Rewrite README for the v3 API, add MIGRATION.md and a v3 CHANGELOG entry.
- Adapt the Node sample and local demo page to native events and hooks.
- Add Composer metadata ported from v2 (flowjs#391).
- Generated dist bundles are committed once at the end of the series.

Refs: flowjs#319, flowjs#353, flowjs#363, flowjs#391
- Pass a per-read AbortController signal to readFileFn, linked to the
  session signal. Previously the reader received only the session signal,
  so FlowFile.pause()/Flow.pause() did not actually abort an in-flight
  read; the result was discarded later (flowjs#368).
- Discard a read result after pause/cancel/error and keep the chunk state
  consistent instead of reverting an error chunk to pending.
- When a permanent chunk error occurs while another chunk is reading, the
  reading chunk now settles as error, so the session can complete.
- A direct chunk.send() reports 'error' if the file already failed.

Refs: flowjs#368
- Treat a null/undefined reader result for a non-empty file as a truncation
  error by default. This prevents silently short uploads; allowShortStream is
  the explicit opt-in for a declared size that is only an upper bound.
- Add optional chunkChecksum(chunk, payload), cached and sent as
  flowChunkHash. It is computed once and reused on retries, so a stateful
  reader/encryptor is never re-run for the same chunk.
- Filter duplicate identifiers within one addFiles batch.
- When an error chunk has no cached payload, retry() re-runs initFileFn and
  rebuilds the chunk list instead of reading a partially consumed stream.

Refs: flowjs#368, flowjs#375
A stateful reader (GPG packetizer, stream cipher, ...) has already consumed
the bytes when readFileFn resolves. Discarding a completed read because a
pause/cancel/error raced with it corrupts the stream on resume. Cache the
payload and checksum before the session decides whether to upload it.

Skip the reader entirely when the signal was already aborted before the read
starts. Add a stateful-pause regression asserting the produced ciphertext is
reused and the reader is not called again for the same chunk.

Refs: flowjs#368
- Add `streaming: true`: chunks are created dynamically until the reader
  returns null/undefined or an empty slice after the first chunk.
- Requests carry `flowTotalSize=-1`, `flowIsStreaming=true`, a growing
  `flowTotalChunks`, and `flowChunkIsLast` on the final zero-byte marker.
- Dynamic probes are created only after existing chunks settle, so a
  stateful GPG/stream-cipher upload buffers only active chunk payloads and
  never the whole input.
- Underestimated sizes are extended; overestimated sizes stop at EOF and
  mark trailing estimate chunks as zero-byte successes.
- Pause/resume, cached retries, reordering by chunk number, read errors and
  final marker semantics are preserved.

Node harness validates unknown, under/over-estimated, retry, read-error,
pause/resume and bounded-memory scenarios. Browser matrix pending endpoint.
- Add target-API regressions for empty async-read files (flowjs#375),
  pause/cancel across an async read (flowjs#368), concurrency, completion
  semantics, stateful-read caching and payload integrity.
- Add upload/error edge cases, transport load/error/timeout/abort,
  test-request success/404/retry, EOF/null/ArrayBuffer/string readers,
  read errors, raw-data transforms, checksum caching, duplicate batch
  filtering, retry reset, priority scheduling, browse/drop, hooks,
  session guards and real HTTP upload/retry tests.
- Add a dedicated streaming suite for unknown, underestimated and
  overestimated sizes, dynamic chunks, EOF markers, marker retries, read
  errors, pause/resume, Blob-backed empty-slice EOF and bounded payload
  memory.
- Add seeded randomized stress with one spec per seed, fresh scope per
  seed, a stall diagnostic, and waitFor() failures that throw instead of
  silently continuing. This makes a timed-out seed report its state
  rather than turning into an opaque Jasmine timeout.
- Drive the suite with Playwright across Chromium, Firefox and WebKit;
  keep a chromium-cdp mode that attaches to an existing Chromium without
  closing it.
- Add Istanbul instrumentation and merged coverage reporting.
  Chromium: 97.4% statements, 86.7% branches, 98.0% functions, 97.6%
  lines over 145 specs. CI runs the full browser matrix.
- Update CI to install Playwright browsers, run the matrix and upload
  coverage.

Refs: flowjs#319, flowjs#353, flowjs#368, flowjs#375
@AidasK

AidasK commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Good stuff! Approved :)) Let me know if you need any accesses, but I think you have everything you need

flow.js always merges its own bookkeeping parameters (flowChunkNumber,
flowTotalChunks, flowIdentifier, flowFilename, ...) into every request: as
query-string parameters in `octet` mode, as body fields in `multipart` mode.
That merge is unconditional and cannot be avoided from userland, because the
`query` option is merged *with* those parameters rather than instead of them.

This makes flow.js unusable against any endpoint whose URL is signed. The
practical case is an S3 pre-signed `UploadPart` URL: AWS SigV4 covers the exact
canonical query string, so appending `flowChunkNumber=1&flowFilename=...`
makes the computed signature differ from `X-Amz-Signature` and S3 rejects every
part with 403 SignatureDoesNotMatch.

Pre-signing *with* those parameters is not a workaround either, because three
of them cannot be known when the URL is signed:

- `flowTotalChunks` grows while a stream of unknown length is consumed,
- `flowChunkIsLast` is only known at EOF,
- `flowChunkHash` depends on the bytes actually read.

`sendFlowParams: false` therefore leaves the request untouched: the URL stays
exactly as `target` produced it, and the body is the payload alone. An explicit
`query` option is still honoured, for signed endpoints that tolerate extra
parameters or for non-signed ones that want only custom fields.

Use case: resumable, chunked, client-side-encrypted uploads sent straight from
the browser into an S3 multipart upload, where the application pre-signs one
URL per part and `target` is a per-chunk function. It also stops the original
file name leaking into the request URL and therefore into storage access logs,
which matters when the uploader is used for anonymous submissions.

Incompatible with `testChunks`, which needs those parameters for the server to
recognise an already-uploaded chunk; noted in the option documentation.

The default stays `true`, so existing consumers are unaffected.
@drzraf

drzraf commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Added 6168329
(not part of the refactor but nice-to-have and relevant for (niche?) use-cases already mentioned: #150

as-is v3 equivalent: sendFlowParams — override chunk.buildRequest from preprocess. buildRequest returns a plain {method, url, body, headers} object, so you rewrite request.url and return it. In v2 the method had already called xhr.open() internally, so you'd have had to re-open the XHR to fix the URL.

but

The workaround overrides undocumented instance methods. Coupling to internals would break on any refactor.
sendFlowParams is strictly more general: it also strips the parameters from the multipart body, which is what the reporter of #150 actually complained about ("the server thinks it's part of file"). URL rewriting doesn't touch that.
The v2 snippet returns this.fileObj.file — the whole file, not the chunk — so it only ever worked for single-request uploads. Two later commenters (2017, 2019) reported it not working or looking incomplete.

So worth an explicit flag.

`target`, `query` and `headers` could already be functions, but their result
was used as-is, so they had to be synchronous. They are now awaited.

This is what an endpoint with per-chunk integrity checks needs. The digest of
a chunk is only known once its payload has been read, and some endpoints want
that digest *in the request itself* rather than in the body. An S3 pre-signed
UploadPart URL is the clearest case: the signature covers the
`x-amz-checksum-sha256` header it commits to, so the URL cannot be produced
before the chunk exists, and S3 answers 400 BadDigest if the bytes that arrive
do not match. Getting that URL means an asynchronous call, per chunk, after
the payload is read.

The options are evaluated in buildRequest(), which already runs after
readPayload() has computed `chunk.checksum`, so a consumer can simply read it:

    target: async (file, chunk) => negotiateUrl(chunk.checksum)

Nothing else changes: a plain value or a synchronous function behaves exactly
as before, since `await` on a non-promise is a no-op. A rejection fails the
chunk through the normal path, so the usual retry policy applies.

This keeps the integrity mechanism generic. flow.js computes the digest and
lets the consumer attach it in whatever shape the endpoint expects -- a signed
URL, a header, a query parameter -- rather than hard-coding any one scheme.
Single generated-artifact commit for the v3-next series. Built from the
final source with Rollup + Terser:

- dist/flow.esm.js
- dist/flow.js (UMD)
- dist/flow.min.js (minified UMD)
- dist/flow.cjs (CommonJS)

Refs: flowjs#353
@drzraf

drzraf commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator Author

Added 6144c75 for AWS S3 ETag signing. Add a (signed) header containing the SHA256 of the chunk. But computing this chunk mean the stream has been fully read, and the Webcrypto API is async.

Awaiting target/query/headers completes an existing API rather than adding surface: they already accepted functions.

@evilaliv3

Copy link
Copy Markdown
Member

@drzraf: thank you for this effort.

What are the advantages of this pull request in short?

@drzraf

drzraf commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator Author

What are the advantages of this pull request in short?

The first main purpose of v3 (back in 2021) was async readers. That led to necessary API adaptations, for it to be more consistent regarding sync/async handling (with, admittedly going back & forth much more than initially expected/desired).

My personal use-case was actually very close to GlobalLeaks. Client-side GPG-encrypted (chunked) uploads but with near-zero server-side hosting/infrastructure. (= uploading directly to some AWS/OpenStack object storage straight from the client).

This brought in various topics (GPG streams -> async initFileFn/readFileFn, unseekable readers, unpredictable size and EOS, async chunk hash computation, URL vs header signing, etc...)

As state in the initial comment this v3 reroll tackled with LLM what my brain (and motivation) couldn't fulfill anymore: Resolving some subtle race condition introduced late in the v3 process and too hard to spot/reliably reproduce (especially given the nested xhr/listeners recursive nature of the codebase).

This made v3 too unreliable to be safely merged (this was due to the #354 / #363 merge episode)

And this is what this reroll finally fixed.

The fact that Deepseek could adapt Angular ngx-flow bindings to v3 / API changes for < 0.05 € was also a strong motivation to get back on this :)

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants