Skip to content

[Feature] Implement SJM as daemon process, so CLI is much faster and can utilise the batch-module #488

Closed
0 of 1 issue completed

Description

@Al-mcne

Eligible idle Mailer eviction, accepted 8 November 2026

A daemon can refuse a new SMTP profile even when another retained Mailer is idle and can be retired. The oldest cache entry may still be constructing, so it has no active lease but cannot yet be evicted.

Mailer cache capacity: 2
A: registered first and still constructing
B: fully constructed; its command has finished
C: a command requests a third, different SMTP profile

The current selection chooses A, cannot retire it, and refuses C without trying B. Retire the oldest eligible idle Mailer instead. If a candidate becomes leased or otherwise unavailable before retirement, continue considering the other candidates before reporting a full cache.

Pending construction and active leases keep their ownership, compatible requests still share one construction, and shutdown retains close-once cleanup. Validation continues to reuse only ready compatible Mailers and otherwise prepares transiently. No CLI option or profile-identity change is introduced.

This completes the unreleased daemon feature under ADR 0019.


CLI validation without SMTP activation — accepted 7 November 2026

A validation command currently constructs a sending Mailer when it cannot reuse one. With a nonzero pool core size, this can open and authenticate SMTP connections before validating the message. A cold daemon command also places that Mailer in its sending cache.

sjm validate --email:startingBlank --email:from sender@example.org --email:to recipient@example.org --email:withPlainText "Preview only" --mailer:withSMTPServer smtp.example.org 587 --mailer:withConnectionPoolCoreSize 1

Keep full validation through the selected Mailer configuration: defaults, overrides, locks, address checks, MIME/security processing and the final encoded-size limit. For a one-shot invocation, prepare transiently without creating sending resources. A daemon may lease an already constructed, live, profile-compatible Mailer; otherwise it uses transient preparation without adding a sending-cache entry or waiting for another command's Mailer construction.

Batch support stays available to the process and its normal sending commands. Validation does not change configured pool sizes or logging mode, start sending workers or proxy bridges, register pools, or reserve sending allowances. Existing daemon pools continue independently. A later send still creates its normal Mailer and activates configured pools. Preserve profile fingerprints, key-file freshness, request-directory ownership, ordinary content/key reads, exception boundaries and current exit codes. No new CLI option or public configuration API is introduced.

This completes the unreleased CLI routing/preparation contract in ADR 0019, using the governed preparation from #688, #709 and ADR 0014. The internal adapter remains outside generated options under ADR 0018, and builds on the completed Session-construction work in #969.


Replay identity retention, accepted 6 November 2026

A completed daemon request can be forgotten under ledger pressure while its original authenticated frame is still fresh. Replaying that frame can execute the same send again.

T+0:   Accept send request U with timestamp T+90 seconds; the send finishes.
       Complete enough other requests to fill the 512-entry ledger.
T+121: Submit a different request, allowing U's identity to be evicted.
T+122: Replay U's identical authenticated frame; it is accepted as new work.

Retain completed request identities throughout the full accepted replay lifetime, including the permitted future timestamp allowance. Keep the current authentication and content checks, bounded ledger and output retention, and refuse new work when every retained identity is still protected. An identical retained request must continue to observe its original result or ambiguous-result tombstone instead of executing again.

This completes the existing unreleased daemon feature under ADR 0019. It adds no new CLI option, automatic resend loop or durable request archive. Ordinary invocations still use new UUIDs; the example requires replay of the same authenticated frame.


Lock-file path safety, accepted 6 November 2026

Daemon startup opens instance.lock before checking that it is a regular file. A dangling symbolic link can therefore create its target before the command refuses startup.

For a 10.0.0 CLI, with no daemon running:

export SJM_DAEMON_STATE_DIR="$PWD/daemon-state"
mkdir -p "$SJM_DAEMON_STATE_DIR/v10/default"
ln -s "$PWD/should-stay-absent" "$SJM_DAEMON_STATE_DIR/v10/default/instance.lock"
sjm daemon run

Use the running CLI's major version in the state path. Refuse an existing symbolic link or other nonregular lock path before opening it, and acquire the lock without following links. Leave a dangling link's target absent and preserve existing wrong-type paths, contents and permissions. Keep normal private lock-file creation, exclusive ownership and lock cleanup.

This completes the existing unreleased daemon feature under ADR 0019. It adds no guarantee against arbitrary concurrent path replacement by the same operating-system user.


Follow-up: resolve request image paths from the caller's directory

A daemon started in directory A can resolve a later command's image paths from A even when the command was issued in directory B.

sjm --daemon=require --daemon-instance=images validate
    --email:from sender@example.org
    --email:to recipient@example.org
    --email:withHTMLText "<img src='logo.png'>"
    --email:withEmbeddedImageAutoResolutionForFiles true
    --email:withEmbeddedImageBaseDir images
    --mailer:withSMTPServer localhost 25

With B/images/logo.png as the requested resource, the daemon can instead embed A/images/logo.png or fail. Request-supplied filesystem image bases and no-base relative image sources should use the request working directory, matching one-shot execution. Keep configuration-owned paths tied to their configuration directory, preserve containment and locks, and leave URL/classpath interpretation unchanged. Do not change process-wide user.dir.

This completes the unreleased daemon's request-directory contract in ADR 0019.


23:59:46 [main] WARN BatchSupport - Starting SMTP connection pool cluster: JVM won't shutdown until the pool is manually closed with mailer.shutdownConnectionPool() (for each mailer in the cluster)

How I can use your Simple-jave-mail in the batch mode?
I supplied all the required parameters for CLI. An email was successfully sent, but the process was never completed.
I'm thinking about a fully automated process and "manual" Ctrl^C is not a option.
How I can automatically close the current SJM process?
image


CLI metadata follow-up, 1 November 2026

Preparing the CLI command and help data should be part of the Maven build. Developers currently have to keep generated binaries in step with API and Javadoc changes, while startup can attempt an expensive rebuild or read source Javadoc when packaged data is unusable. Files in a source checkout can also override installed metadata because the loader guesses development mode from the working directory.

mvn -pl modules/cli-module -am verify
sjm send --help

The Maven build should create or reuse a complete local metadata pair automatically before CLI tests. Its Git-ignored modules/cli-module/.build-cache/metadata entries should survive normal clean builds and refresh when generation inputs change, including Javadoc-only edits. Release mode should always generate fresh files and check the actual JAR, ZIP and TAR before publication, including builds that skip ordinary unit tests. Every developer should use the same repository-defined JDK and Maven workflow, without extra scripts or personal setup.

Normal CLI execution should only load packaged metadata. Missing, damaged, incompatible or incomplete data should produce a clear installation error without generating files, looking up source documentation or writing replacements. Preserve lazy daemon routing, fresh per-request parser state, existing command syntax and binary codecs. Generated source-resource binaries should no longer be manually maintained in Git.

This completes the unreleased CLI metadata workflow under this feature and the performance direction of #323. The governing decision is ADR 0018.


Startup-log safety follow-up, 2 November 2026

Starting a daemon can empty an unrelated writable file when daemon-startup.log is a symbolic link. Startup opens and truncates the log before refusing the link, so the command can report a private-state failure after changing the linked file.

With no running daemon, this setup demonstrates the problem:

export SJM_DAEMON_STATE_DIR="$PWD/daemon-state"
mkdir -p "$SJM_DAEMON_STATE_DIR/v10/default"
printf 'keep me' > important.txt
ln -s "$PWD/important.txt" "$SJM_DAEMON_STATE_DIR/v10/default/daemon-startup.log"
sjm daemon start

Refuse existing symbolic links and nonregular startup-log paths before changing file content or permissions. A dangling link must not create its target. Opening the log must not follow a link introduced between the path check and the open. Ordinary new and existing regular logs should keep their private permissions and startup behavior.

This completes the unreleased daemon's private-state boundary in ADR 0019. The maintainer accepted the correction on 2 November 2026.


Ordinary daemon-log path safety, accepted 5 November 2026

A directory at the ordinary daemon.log path is accepted as a file during daemon startup. Its permissions can be changed before logging refuses it. On POSIX filesystems, applying file permissions removes the directory's traversal permission, so a failed startup can leave existing state changed.

For a 10.0.0 CLI, with no daemon running:

export SJM_DAEMON_STATE_DIR="$PWD/daemon-state"
mkdir -p "$SJM_DAEMON_STATE_DIR/v10/default/daemon.log"
sjm daemon run

Use the running CLI's major version in that path. Refuse nonregular state-file targets before changing their permissions. Keep the existing directory, its contents and permissions unchanged, and preserve the same refusal for symbolic links and dangling links. Ordinary new and existing regular logs still receive owner-only permissions. Apply this regular-file requirement at the shared private-state boundary so the ordinary log cannot bypass it; retain the existing lock, discovery and startup-log behavior.

This completes the unreleased daemon feature under ADR 0019. It adds no promise of protection against arbitrary path replacement by the same operating-system user.


Consistent daemon state and socket paths, accepted 5 November 2026

A detached daemon can fail to become ready when its state directory is relative and the normal Unix-socket path is long enough to require the short temporary location. The client derives that location from the relative spelling, while its child receives an absolute state directory and derives another location. Discovery then correctly refuses the unexpected endpoint.

From a sufficiently long working directory on a runtime using Unix-domain sockets:

SJM_DAEMON_STATE_DIR=./sjm-state sjm daemon start

Keep relative state directories supported. Resolve the selected root once to a normalized absolute path before deriving runtime locations, and give the child the same root and temporary-directory inputs. An equivalent relative or absolute spelling should select the same state and socket location. Normalization must not require the directory to exist or resolve filesystem links.

Preserve private state, strict endpoint and process identity checks, authenticated readiness, instance isolation and the existing Unix/TCP selection rules. Do not weaken discovery validation or use a security failure as permission to fall back to TCP. This completes the unreleased daemon feature under ADR 0019, with no new option or public API.

Sub-issues

Sub-issues

0 of 1 Issues completed
Loading 1 sub-issues

Activity

  1. bbottema commented on Dec 20, 2023

    @bbottema
    Owner

    Hhm, I'm wondering if the batch module makes sense on the CLI at all, since you can't actually send emails in batches on the CLI. Each action is a separate process and connection pools don't last between sessions.

    What I mean is Simple Java Mail doesn't have a daemon process running in the background... I never thought about that before, but it's a nice feature request to think about! Would speed up sending emails significantly (after initially spinning up a daemon).

    You can simply remove the batch-module.jar from the libraries folder, for now. That will solve your immediate problem.

  2. changed the title [-]JVM won't shutdown until the pool is manually closed [/-] [+][Feature] Implement SJM as daemon process, so CLI is much faster and can utilise the batch-module[/+] on Dec 20, 2023
  3. Al-mcne commented on Dec 21, 2023

    @Al-mcne
    Author

    Thank you for the quick solution!
    It works perfectly on the Windows platform (sjm.bat)
    Later I will validate the same solution on Linux.

    Thank you again!
    Alex
    image

  4. added this to the 10.0.0 milestone on Aug 7, 2026
  5. bbottema commented on Aug 20, 2026

    @bbottema
    Owner

    Implementation update for 10.0.0

    The CLI daemon implementation is complete locally.

    Implemented contract:

    • The library modules remain Java 8-compatible; only cli-module now requires Java 17.
    • Existing CLI commands remain one-shot by default.
    • -d, bare --daemon, and --daemon=acquire opt into a daemon and start one when needed; --daemon=require, --daemon=off, and --no-daemon provide the strict alternatives.
    • daemon run, start, stop, status, and restart are implemented, including named per-user instances.
    • The daemon uses authenticated local IPC, preferring Unix-domain sockets with a strict authenticated 127.0.0.1 fallback.
    • One daemon can safely retain multiple effective Mailer configurations. Compatible requests reuse a bounded Mailer entry; incompatible SMTP, credential, proxy, trust, security, and pool configurations do not.
    • batch-module remains supported and optional. With it present, compatible daemon sends can reuse the SMTP connection pool; without it, the daemon still works but cannot retain pooled SMTP connections.
    • Requests, retained results, output, workers, profiles, and shutdown time are bounded. Ambiguous sends are never retried automatically.
    • Portable Windows and Unix archives, systemd, launchd, Windows Scheduled Task, Homebrew, Chocolatey, operations documentation, website documentation, and a hosted OS/JDK CI matrix are included.
  6. bbottema commented on Aug 24, 2026

    @bbottema
    Owner

    Implemented for 10.0.0 and pushed on codex/10.0.0.

    The CLI remains one-shot by default. -d / --daemon=acquire enables on-demand daemon use, lifecycle commands and named instances are available, multiple Mailer configurations are isolated within one daemon, and batch-module remains optional while enabling SMTP pool reuse when present.

    The portable ZIP/TAR daemon is complete. Homebrew and Chocolatey publication is tracked separately in #708 and does not block this feature.

  7. 125 remaining items

  8. bbottema commented on Nov 7, 2026

    @bbottema
    Owner
    sjm validate --daemon=off --email:startingBlank --email:from sender@example.org --email:to recipient@example.org --email:withPlainText "Preview only" --mailer:withSMTPServer smtp.example.org 587 --mailer:withConnectionPoolCoreSize 1
    

    CLI validation now performs full governed preparation without starting sending resources. One-shot commands and daemon cache misses prepare transiently. A daemon can reuse a fully constructed, live compatible Mailer; pending, failed or retiring profiles use transient preparation. Existing pools continue independently, and a later send still activates its configured pool.

    Defaults, overrides, locks, address checks, MIME/security processing, encoded-size checks, exact EML and ordinary content ownership retain their preparation behavior. CLI syntax and batch availability stay the same.

    This completes the accepted CLI activation follow-up on the unreleased 10.0.0 development branches. It builds on #688/#709 preparation and #969 construction, following ADR 0014, ADR 0018 and ADR 0019.

    Delivered changes: shared preparation and ready Mailer reuse, CLI usage guide, architecture and migration target guidance.

  9. moved this from Done to In Progress in Simple Java Mail 10.0.0on Nov 8, 2026
  10. bbottema commented on Nov 8, 2026

    @bbottema
    Owner
    Mailer cache capacity: 2
    A: still constructing
    B: fully constructed and idle
    C: a command requests a different SMTP profile
    Result: B is retired and C is admitted; A keeps its construction.
    

    The daemon now considers idle Mailers in age order until one can be retired. An older Mailer that is still starting, or becomes leased before retirement, no longer hides another eligible idle Mailer. Pending construction, active commands and close-once cleanup retain their ownership.

    This completes the accepted eviction follow-up on the unreleased 10.0.0 development branches, following ADR 0019.

    Delivered changes: eligible idle Mailer eviction and operations guidance, CLI website guidance.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions