Compare commits
40
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6df9f08643 | ||
|
|
a511834edd | ||
|
|
6e9419f342 | ||
|
|
e1625d2000 | ||
|
|
cd9168fc9d | ||
|
|
3ba8aea90e | ||
|
|
68d56ddedd | ||
|
|
4e81bda8ec | ||
|
|
82891b54fd | ||
|
|
ee86e62c04 | ||
|
|
53913bd8df | ||
|
|
71401f8e0f | ||
|
|
1d76c5d930 | ||
|
|
f9777ae373 | ||
|
|
77e72ae068 | ||
|
|
e8870e33ac | ||
|
|
1584a5d879 | ||
|
|
ee0c60dcec | ||
|
|
b74dd284a8 | ||
|
|
aff97b503c | ||
|
|
70d78e375f | ||
|
|
04f4e74253 | ||
|
|
4b396534de | ||
|
|
7e2e23a60d | ||
|
|
82c4f3de56 | ||
|
|
d5f7d78035 | ||
|
|
3e6030fe35 | ||
|
|
dae957153e | ||
|
|
ddad68cf02 | ||
|
|
70883fefce | ||
|
|
41a7dcfbfb | ||
|
|
fc946a9e55 | ||
|
|
a1835b90ad | ||
|
|
1e9ff699e7 | ||
|
|
63b88fe753 | ||
|
|
ac553ddd5a | ||
|
|
f787cafdd8 | ||
|
|
9236276b9c | ||
|
|
d061a61f6b | ||
|
|
8390cfc535 |
No files matched your search
@@ -0,0 +1,28 @@
|
||||
---
|
||||
|
||||
version: 2.1
|
||||
|
||||
orbs:
|
||||
qqq-orb: kingsrook/qqq-orb@0.6.8
|
||||
|
||||
commands:
|
||||
configure-package-install:
|
||||
steps:
|
||||
- run:
|
||||
name: Keep package installation unattended
|
||||
command: |
|
||||
# These build machines are discarded after the job.
|
||||
# Use Ubuntu's archive mirror, which also carries the signed security suite.
|
||||
sudo sed -i 's|http://security.ubuntu.com/ubuntu|https://archive.ubuntu.com/ubuntu|g' /etc/apt/sources.list
|
||||
sudo install -d /etc/needrestart/conf.d
|
||||
printf '%s\n' '$nrconf{restart} = "l";' | sudo tee /etc/needrestart/conf.d/99-qqq-ci.conf >/dev/null
|
||||
|
||||
workflows:
|
||||
|
||||
# Build and unit tests on every branch push. Dependencies are public
|
||||
# (Maven Central and the Central snapshot repository), so no context is needed.
|
||||
test_only:
|
||||
jobs:
|
||||
- qqq-orb/mvn_test_only:
|
||||
pre-steps:
|
||||
- configure-package-install
|
||||
@@ -0,0 +1,10 @@
|
||||
.git
|
||||
.github
|
||||
.circleci
|
||||
.env
|
||||
docs
|
||||
qqq-all-bom
|
||||
qqq-all-bom-test
|
||||
qqq-all-app/src
|
||||
qqq-all-app/target/*
|
||||
!qqq-all-app/target/qqq-all-app.jar
|
||||
@@ -0,0 +1,29 @@
|
||||
# Local demonstration values only. Copy to .env and override before exposing ports.
|
||||
QQQ_ALL_PORT=8080
|
||||
KEYCLOAK_PORT=8081
|
||||
POSTGRES_USER=qqq
|
||||
POSTGRES_PASSWORD=demo-postgres-password
|
||||
POSTGRES_DATABASE=qqq
|
||||
MYSQL_USER=qqq
|
||||
MYSQL_PASSWORD=demo-mysql-password
|
||||
MYSQL_ROOT_PASSWORD=demo-mysql-root-password
|
||||
MYSQL_DATABASE=qqq
|
||||
MONGO_USER=qqq
|
||||
MONGO_PASSWORD=demo-mongo-password
|
||||
MONGO_DATABASE=qqq
|
||||
MONGO_REPLICA_SET=rs0
|
||||
MONGO_KEYFILE=demo-mongo-internal-replica-key-change-this-before-sharing
|
||||
MINIO_ROOT_USER=qqq
|
||||
MINIO_ROOT_PASSWORD=demo-minio-password
|
||||
MINIO_BUCKET=qqq-demo
|
||||
SFTP_USER=qqq
|
||||
SFTP_PASSWORD=demo-sftp-password
|
||||
RABBITMQ_USER=qqq
|
||||
RABBITMQ_PASSWORD=demo-rabbitmq-password
|
||||
ARTEMIS_USER=qqq
|
||||
ARTEMIS_PASSWORD=demo-artemis-password
|
||||
KEYCLOAK_ADMIN=admin
|
||||
KEYCLOAK_ADMIN_PASSWORD=demo-keycloak-admin-password
|
||||
OIDC_CLIENT_SECRET=demo-qqq-all-client-secret
|
||||
DEMO_ADMIN_PASSWORD=demo-admin-password
|
||||
DEMO_USER_PASSWORD=demo-user-password
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: Bug Report
|
||||
about: Report something in qqq-all that does not work
|
||||
title: "[BUG] "
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Bug Description
|
||||
|
||||
**Clear and concise description of what the bug is.**
|
||||
|
||||
## Expected vs Actual Behavior
|
||||
|
||||
**What you expected to happen:**
|
||||
- Expected behavior description
|
||||
|
||||
**What actually happened:**
|
||||
- Actual behavior description
|
||||
|
||||
## Steps to Reproduce
|
||||
|
||||
1. Start the stack with '...'
|
||||
2. Go to '...'
|
||||
3. Click on '...'
|
||||
4. See error
|
||||
|
||||
## Environment
|
||||
|
||||
**qqq-all Version:** [e.g., 4.1.0-SNAPSHOT, 4.1.0]
|
||||
**Profile:** [core or full]
|
||||
**Java Version:** [e.g., 21]
|
||||
**Docker Version:** [if using the full profile]
|
||||
**OS:** [e.g., macOS 15, Ubuntu 24.04, Windows 11 with WSL]
|
||||
|
||||
## Additional Context
|
||||
|
||||
**Add any other context about the problem here:**
|
||||
|
||||
- Screenshots (if applicable)
|
||||
- Error logs or stack traces
|
||||
- Related issues or pull requests
|
||||
|
||||
## Before Submitting
|
||||
|
||||
- [ ] Searched [existing issues](https://github.com/QRun-IO/qqq-all/issues) for duplicates
|
||||
- [ ] Checked whether this is a framework bug that belongs in [QRun-IO/qqq](https://github.com/QRun-IO/qqq/issues)
|
||||
@@ -0,0 +1,11 @@
|
||||
blank_issues_enabled: false
|
||||
contact_links:
|
||||
- name: QQQ Framework Issues
|
||||
url: https://github.com/QRun-IO/qqq/issues
|
||||
about: Bugs and feature requests for the QQQ framework itself
|
||||
- name: QQQ Documentation Wiki
|
||||
url: https://github.com/QRun-IO/qqq/wiki
|
||||
about: Complete documentation, guides, and tutorials for QQQ
|
||||
- name: GitHub Discussions
|
||||
url: https://github.com/QRun-IO/qqq/discussions
|
||||
about: Ask questions and discuss QQQ with the community
|
||||
@@ -0,0 +1,42 @@
|
||||
---
|
||||
name: Documentation Issue
|
||||
about: Report documentation problems or suggest improvements
|
||||
title: "[DOCS] "
|
||||
labels: documentation
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Documentation Issue
|
||||
|
||||
**What documentation issue are you reporting?**
|
||||
|
||||
- [ ] **Missing Documentation** - Something is not documented
|
||||
- [ ] **Outdated Information** - Documentation is incorrect or outdated
|
||||
- [ ] **Unclear Content** - Documentation is confusing or hard to understand
|
||||
- [ ] **Missing Examples** - Need more examples or code samples
|
||||
- [ ] **Broken Links** - Links don't work or go to wrong places
|
||||
- [ ] **Other** - Please describe below
|
||||
|
||||
## Description
|
||||
|
||||
**Clear and concise description of the documentation issue:**
|
||||
|
||||
## Location
|
||||
|
||||
**Where is this documentation issue located?**
|
||||
- **File/Page**: [e.g., README.md, CONTRIBUTING.md]
|
||||
- **Section**: [e.g., "Quick Start"]
|
||||
- **URL**: [if applicable]
|
||||
|
||||
## Suggested Improvement
|
||||
|
||||
**How would you improve this documentation?**
|
||||
- What information should be added?
|
||||
- How could it be made clearer?
|
||||
- What examples would be helpful?
|
||||
|
||||
## Before Submitting
|
||||
|
||||
- [ ] Searched [existing issues](https://github.com/QRun-IO/qqq-all/issues) for similar documentation requests
|
||||
- [ ] Checked whether this is about framework docs that belong in the [QQQ Wiki](https://github.com/QRun-IO/qqq/wiki)
|
||||
@@ -0,0 +1,37 @@
|
||||
---
|
||||
name: Feature Request
|
||||
about: Suggest something qqq-all should configure or demonstrate
|
||||
title: "[FEATURE] "
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
## Feature Description
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like:**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered:**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
## Use Case
|
||||
|
||||
**What is the use case for this feature?**
|
||||
- Which QQQ feature, backend, or qBit does it involve?
|
||||
- Which profile does it affect (`core`, `full`, or both)?
|
||||
- Who would benefit from it?
|
||||
|
||||
## Implementation Ideas
|
||||
|
||||
**Do you have any ideas about how this could be implemented?**
|
||||
- Technical approach suggestions
|
||||
- Any constraints or considerations
|
||||
|
||||
## Before Submitting
|
||||
|
||||
- [ ] Searched [existing issues](https://github.com/QRun-IO/qqq-all/issues) for similar requests
|
||||
- [ ] Checked whether this is a framework feature that belongs in [QRun-IO/qqq](https://github.com/QRun-IO/qqq/issues)
|
||||
@@ -0,0 +1,52 @@
|
||||
# Pull Request
|
||||
|
||||
## Description
|
||||
|
||||
**What does this PR do?**
|
||||
A clear and concise description of what this pull request accomplishes.
|
||||
|
||||
**Related Issue:**
|
||||
Closes #[issue_number]
|
||||
|
||||
## Type of Change
|
||||
|
||||
- [ ] **Bug Fix** - Fixes an existing issue
|
||||
- [ ] **New Feature** - Adds new functionality
|
||||
- [ ] **Breaking Change** - Fix or feature that would cause existing functionality to not work as expected
|
||||
- [ ] **Documentation Update** - Updates documentation
|
||||
- [ ] **Refactoring** - Code change that neither fixes a bug nor adds a feature
|
||||
- [ ] **Build / CI** - Changes to the Maven build, CircleCI, compose, or image
|
||||
- [ ] **Test Addition** - Adding missing tests or correcting existing tests
|
||||
|
||||
## Testing
|
||||
|
||||
**How has this been tested?**
|
||||
- [ ] **Unit Tests**: All unit tests pass
|
||||
- [ ] **Integration Tests**: Integration tests pass
|
||||
- [ ] **Profiles**: Checked the affected profile(s) (`core`, `full`)
|
||||
- [ ] **Manual Testing**: Tested manually in a development environment
|
||||
|
||||
**Test Commands:**
|
||||
```bash
|
||||
# Commands used for testing, and their results
|
||||
mvn -B verify
|
||||
```
|
||||
|
||||
## Checklist
|
||||
|
||||
**Before submitting this PR, please ensure:**
|
||||
|
||||
- [ ] **Code Style**: Follows QQQ's [Code Review Standards](https://github.com/QRun-IO/qqq/wiki/Code-Review-Standards)
|
||||
- [ ] **Tests**: All tests pass
|
||||
- [ ] **Documentation**: Updated the README or docs where behavior changed
|
||||
- [ ] **Secrets**: No secrets committed; any demo credentials are marked demo-only and overridable by env
|
||||
- [ ] **Breaking Changes**: Documented any breaking changes
|
||||
- [ ] **Commit Messages**: Follow conventional commit format
|
||||
- [ ] **Self Review**: Code has been reviewed by the author
|
||||
|
||||
## Additional Information
|
||||
|
||||
**Any additional information that reviewers should know:**
|
||||
- Screenshots (if applicable)
|
||||
- Dependencies added/removed
|
||||
- Migration notes
|
||||
@@ -0,0 +1,48 @@
|
||||
name: Publish develop image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [develop]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Check public package visibility
|
||||
id: package_visibility
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
if visibility="$(gh api /orgs/QRun-IO/packages/container/qqq-all --jq .visibility 2>/dev/null)" && [ "$visibility" = public ]; then
|
||||
echo 'publish=true' >> "$GITHUB_OUTPUT"
|
||||
echo 'The qqq-all container package is public; develop image publication is enabled.' >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
echo 'publish=false' >> "$GITHUB_OUTPUT"
|
||||
echo 'Skipped develop image publication: the qqq-all container package is not yet public or cannot be read. An owner must bootstrap the package and set it to Public before C9 enables publication.' >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '21'
|
||||
cache: maven
|
||||
- name: Verify application
|
||||
run: mvn -B -ntp verify
|
||||
- uses: docker/login-action@v3
|
||||
if: steps.package_visibility.outputs.publish == 'true'
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build and publish develop image
|
||||
if: steps.package_visibility.outputs.publish == 'true'
|
||||
run: |
|
||||
docker build \
|
||||
--label org.opencontainers.image.source=https://github.com/QRun-IO/qqq-all \
|
||||
--tag ghcr.io/qrun-io/qqq-all:develop .
|
||||
docker push ghcr.io/qrun-io/qqq-all:develop
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Smoke
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [develop]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
core:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
cache: maven
|
||||
- name: Check smoke assertions
|
||||
run: python3 -m unittest discover -s scripts -p 'test_*.py' -v
|
||||
- name: Verify and package core app
|
||||
run: mvn -B -ntp -pl qqq-all-app -am verify
|
||||
- name: Smoke packaged core over HTTP
|
||||
run: python3 scripts/run_core_smoke.py qqq-all-app/target/qqq-all-app.jar
|
||||
|
||||
full:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
PYTHONDONTWRITEBYTECODE: "1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "21"
|
||||
cache: maven
|
||||
- name: Package full app for Docker image
|
||||
run: mvn -B -ntp -pl qqq-all-app -am -DskipTests package
|
||||
- name: Smoke full Compose over HTTP
|
||||
run: python3 scripts/run_full_smoke.py
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
target/
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.iml
|
||||
.env
|
||||
/.env.local
|
||||
|
||||
.idea
|
||||
.vscode
|
||||
.claude/
|
||||
CLAUDE.md
|
||||
|
||||
#####################################
|
||||
## Eclipse / NVIM Modules for Java ##
|
||||
#####################################
|
||||
**/.settings/
|
||||
**/.classpath
|
||||
**/.factorypath
|
||||
**/.project
|
||||
|
||||
#############################################
|
||||
## Original contents from github template: ##
|
||||
#############################################
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
|
||||
.DS_Store
|
||||
*.swp
|
||||
.flattened-pom.xml
|
||||
dependency-reduced-pom.xml
|
||||
/.cache/
|
||||
@@ -0,0 +1,78 @@
|
||||
# Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our community include:
|
||||
|
||||
- **Demonstrating empathy and kindness** toward other people
|
||||
- **Being respectful** of differing opinions, viewpoints, and experiences
|
||||
- **Giving and gracefully accepting** constructive feedback
|
||||
- **Accepting responsibility** and apologizing to those affected by our mistakes
|
||||
- **Focusing on what is best** for the overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- **The use of sexualized language or imagery**, and sexual attention or advances of any kind
|
||||
- **Trolling, insulting or derogatory comments**, and personal or political attacks
|
||||
- **Public or private harassment**
|
||||
- **Publishing others' private information**, such as a physical or email address, without their explicit permission
|
||||
- **Other conduct which could reasonably be considered inappropriate** in a professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at **contact@qrun.io**. All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
**Community Impact**: A violation through a single incident or series of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq](https://www.contributor-covenant.org/faq). Translations are available at [https://www.contributor-covenant.org/translations](https://www.contributor-covenant.org/translations).
|
||||
|
||||
## Contact Information
|
||||
|
||||
- **Community Leaders**: contact@qrun.io
|
||||
- **Security Issues**: security@qrun.io (see [SECURITY.md](SECURITY.md))
|
||||
- **Company**: QRunIO, LLC
|
||||
- **Website**: https://qrun.io
|
||||
@@ -0,0 +1,46 @@
|
||||
# Contributing to qqq-all
|
||||
|
||||
qqq-all is open source and welcomes contributions. It is the reference build of [QQQ](https://github.com/QRun-IO/qqq) with every feature configured, so most framework changes belong in QQQ or the relevant qBit; changes here wire those pieces together, add demo data, or fix the build. For framework guides, see the [QQQ Wiki](https://github.com/QRun-IO/qqq/wiki).
|
||||
|
||||
## How to Contribute
|
||||
|
||||
1. **Report issues.** Found a bug or want a feature in the demo stack? [Open an issue](https://github.com/QRun-IO/qqq-all/issues/new/choose). Framework bugs go to [QRun-IO/qqq](https://github.com/QRun-IO/qqq/issues).
|
||||
2. **Contribute code.** Branch from `develop` as `feature/<issue>-<short-description>` and open the pull request against `develop`.
|
||||
3. **Improve docs.** Documentation fixes are welcome in the same way as code.
|
||||
|
||||
**Key requirements:**
|
||||
- Java 21 and Maven 3.8+
|
||||
- Follow QQQ's [Code Review Standards](https://github.com/QRun-IO/qqq/wiki/Code-Review-Standards)
|
||||
- Add or update tests for any behavior you change
|
||||
- Use [conventional commit](https://www.conventionalcommits.org/) messages
|
||||
- Never commit secrets; demo credentials must be marked demo-only and overridable by environment variables
|
||||
|
||||
## Development Setup
|
||||
|
||||
```bash
|
||||
git clone git@github.com:QRun-IO/qqq-all.git
|
||||
cd qqq-all
|
||||
mvn -B verify
|
||||
```
|
||||
|
||||
qqq-all tracks the QQQ version. Until QQQ 4.1 ships, the build uses `4.1.0-SNAPSHOT` artifacts from the [Sonatype Central snapshot repository](https://central.sonatype.com/repository/maven-snapshots/), which the parent `pom.xml` already declares.
|
||||
|
||||
## Contribution Checklist
|
||||
|
||||
- [ ] `mvn -B verify` passes locally
|
||||
- [ ] Tests cover the change
|
||||
- [ ] Code follows QQQ's code style
|
||||
- [ ] Commit messages follow the conventional commit format
|
||||
- [ ] Docs updated where behavior changed
|
||||
|
||||
## Getting Help
|
||||
|
||||
- **[QQQ Wiki](https://github.com/QRun-IO/qqq/wiki)**: framework guides
|
||||
- **[Issues](https://github.com/QRun-IO/qqq-all/issues)**: search existing issues or open a new one
|
||||
- **[Discussions](https://github.com/QRun-IO/qqq/discussions)**: ask questions
|
||||
|
||||
## Legal Notice
|
||||
|
||||
When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content, and that the content you contribute may be provided under the project license ([Apache-2.0](LICENSE)).
|
||||
|
||||
Please follow our [Code of Conduct](CODE_OF_CONDUCT.md). Report security issues privately as described in [SECURITY.md](SECURITY.md).
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
FROM eclipse-temurin:21-jre-jammy
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends curl \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& groupadd --system --gid 10001 qqq \
|
||||
&& useradd --system --uid 10001 --gid qqq --home-dir /app qqq \
|
||||
&& mkdir -p /app/data \
|
||||
&& chown -R qqq:qqq /app
|
||||
|
||||
WORKDIR /app
|
||||
COPY --chown=qqq:qqq qqq-all-app/target/qqq-all-app.jar /app/qqq-all.jar
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
ENV QQQ_ALL_DATA_DIR=/app/data
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=45s --retries=6 \
|
||||
CMD curl --fail --silent http://127.0.0.1:8080/health >/dev/null || exit 1
|
||||
ENTRYPOINT ["java", "-jar", "/app/qqq-all.jar"]
|
||||
@@ -0,0 +1,30 @@
|
||||
QQQ All
|
||||
Copyright 2026 QRunIO, LLC
|
||||
|
||||
This product includes software developed at QRunIO, LLC (https://qrun.io/).
|
||||
|
||||
Licensed under the Apache License, Version 2.0.
|
||||
|
||||
================================================================================
|
||||
|
||||
This software contains contributions from:
|
||||
|
||||
- James Maes
|
||||
|
||||
================================================================================
|
||||
|
||||
Third-Party Licenses:
|
||||
|
||||
This software depends on and may redistribute third-party open source software
|
||||
components, including the QQQ framework, qBits, JDBC drivers, and message broker
|
||||
clients. Each component has its own license. Please see the individual component
|
||||
documentation for license details.
|
||||
|
||||
================================================================================
|
||||
|
||||
Trademarks:
|
||||
|
||||
QQQ, qBits, qRun, qStudio, and the QRunIO logo are trademarks of QRunIO, LLC.
|
||||
Use of these trademarks must comply with QRunIO's Trademark Guidelines.
|
||||
|
||||
================================================================================
|
||||
@@ -0,0 +1,46 @@
|
||||
# qqq-all
|
||||
|
||||
A runnable reference app for QQQ 4.1 with two profiles: `core` uses local storage and embedded Artemis; `full` adds external storage, RabbitMQ, OpenSearch quick search, Keycloak, Mailpit, and the included qbits. It is a local demo under construction while QQQ 4.1 finishes. See the [design](docs/design.md), [plan](docs/plan.md), and [epic #1](https://github.com/QRun-IO/qqq-all/issues/1).
|
||||
|
||||
## Quick start
|
||||
|
||||
Install Java 21 and Maven, then build the app and its BOM from the repository root:
|
||||
|
||||
```bash
|
||||
mvn -B verify
|
||||
```
|
||||
|
||||
Run core from the packaged jar:
|
||||
|
||||
```bash
|
||||
java -jar qqq-all-app/target/qqq-all-app.jar
|
||||
```
|
||||
|
||||
Or copy the local demo settings and run core with Compose:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
docker compose --profile core up --build --wait
|
||||
```
|
||||
|
||||
To run full instead, stop core first, then use the same `.env` (or copy `.env.example` if starting with full):
|
||||
|
||||
```bash
|
||||
docker compose --profile full up --build --wait
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8080/` for the dashboard and `/health` for status. The full profile starts PostgreSQL, MySQL, MongoDB, MinIO, SFTP, OpenSearch, Artemis, RabbitMQ, Mailpit, and Keycloak. Its demo logins are `demo-admin` and `demo-user`; their sample passwords and the OIDC client secret come from your local `.env` (copied from [.env.example](.env.example)). The browser issuer is `http://keycloak.localhost:8081`; make that name resolve to loopback if your host does not already. Compose publishes demo ports on host loopback. The [app guide](qqq-all-app/README.md) lists the environment contract and broker-management check.
|
||||
|
||||
## Explore the app
|
||||
|
||||
Core seeds customers and orders in H2, order lines in SQLite, and product files under `./data`. Insert an order as Admin to publish an Artemis `orderEvents` message and trigger `syncOrder`; inspect its process trace. Run `SendWebhookEvent` as Admin, then inspect the demo webhook receipt. Core's mock Demo User can read but cannot edit webhook destinations or invoke delivery. Sample customer and order rows are merged on every start, so edits to those rows can be reset.
|
||||
|
||||
Full adds sample tables on PostgreSQL, MySQL, MongoDB, MinIO S3, and SFTP. It includes OpenSearch customer quick search, table views, process tracing, workflows, geo addresses, SFTP import, and webhook administration with Keycloak role permissions. The `syncOrder` completion publication to RabbitMQ is configured in metadata and depends on QQQ ESB [Task 9](https://github.com/QRun-IO/qqq/pull/786) landing in QQQ 4.1; the app does not publish it through a separate workaround.
|
||||
|
||||
To stop the full stack, run `docker compose --profile full down`. Add `--volumes` only when you intend to erase demo data. For a fresh Artemis volume, the configured login is required; old volumes created for anonymous access should be recreated. This reference stack uses demo credentials and is not a production deployment.
|
||||
|
||||
The [develop image workflow](.github/workflows/publish-image.yml) verifies the build and publishes to GHCR only after an organization owner bootstraps the container package and sets its visibility to public. Until then, image publication is skipped and local Compose remains available.
|
||||
|
||||
## Contributing and license
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md), the [Code of Conduct](CODE_OF_CONDUCT.md), and the [security policy](SECURITY.md). Licensed under Apache-2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# Security Policy
|
||||
|
||||
## Supported Versions
|
||||
|
||||
qqq-all versions track QQQ versions.
|
||||
|
||||
| Version | Supported | Notes |
|
||||
| ------- | --------- | ----- |
|
||||
| 4.1.x | Yes | In development on `develop` (`4.1.0-SNAPSHOT`) until QQQ 4.1 ships |
|
||||
|
||||
## Scope
|
||||
|
||||
qqq-all is a local demo and reference build. It is not a production deployment: production still needs DNS, TLS, backups, monitoring, and highly available brokers. Any demo credentials in this repository are for local use only and must be overridden before exposing a stack to a network.
|
||||
|
||||
Vulnerabilities in the QQQ framework or a qBit should be reported to that project. If you are unsure where an issue belongs, report it here and it will be routed.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
**Security vulnerabilities should NEVER be reported publicly.**
|
||||
|
||||
### Private Reporting
|
||||
|
||||
Use GitHub's private vulnerability reporting:
|
||||
**[Report a vulnerability](https://github.com/QRun-IO/qqq-all/security/advisories/new)**
|
||||
|
||||
Or email: **security@qrun.io**
|
||||
|
||||
### What to Include
|
||||
|
||||
- Description of the vulnerability
|
||||
- Steps to reproduce
|
||||
- Potential impact
|
||||
- qqq-all version and profile (`core` or `full`), Java version, OS, and Docker version if relevant
|
||||
|
||||
### Response Timeline
|
||||
|
||||
| Stage | Timeline |
|
||||
|-------|----------|
|
||||
| Initial response | 24 hours |
|
||||
| Assessment | 3 business days |
|
||||
| Resolution | Based on severity |
|
||||
|
||||
## For Contributors
|
||||
|
||||
- Dependencies must not introduce HIGH or CRITICAL vulnerabilities
|
||||
- Secrets must never be committed
|
||||
- Follow QQQ's secure coding practices ([CODE_STYLE.md](https://github.com/QRun-IO/qqq/blob/develop/CODE_STYLE.md))
|
||||
|
||||
## Contact
|
||||
|
||||
- **Security issues**: security@qrun.io
|
||||
- **General contact**: contact@qrun.io
|
||||
- **Organization**: [QRun-IO](https://github.com/QRun-IO)
|
||||
+290
@@ -0,0 +1,290 @@
|
||||
name: qqq-all
|
||||
|
||||
x-app-image: &app-image
|
||||
build:
|
||||
context: .
|
||||
image: qqq-all:local
|
||||
volumes:
|
||||
- app-data:/app/data
|
||||
ports:
|
||||
- "127.0.0.1:${QQQ_ALL_PORT:-8080}:8080"
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "--fail", "--silent", "http://127.0.0.1:8080/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 6
|
||||
start_period: 45s
|
||||
|
||||
services:
|
||||
app-core:
|
||||
<<: *app-image
|
||||
profiles: [core]
|
||||
environment:
|
||||
QQQ_ALL_PROFILE: core
|
||||
QQQ_ALL_PORT: "8080"
|
||||
QQQ_ALL_BIND_HOST: 0.0.0.0
|
||||
|
||||
app-full:
|
||||
<<: *app-image
|
||||
profiles: [full]
|
||||
environment:
|
||||
QQQ_ALL_PROFILE: full
|
||||
QQQ_ALL_PORT: "8080"
|
||||
QQQ_ALL_BIND_HOST: 0.0.0.0
|
||||
QQQ_ALL_POSTGRES_HOST: postgres
|
||||
QQQ_ALL_POSTGRES_DATABASE: ${POSTGRES_DATABASE:-qqq}
|
||||
QQQ_ALL_POSTGRES_USER: ${POSTGRES_USER:-qqq}
|
||||
QQQ_ALL_POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD}
|
||||
QQQ_ALL_MYSQL_HOST: mysql
|
||||
QQQ_ALL_MYSQL_DATABASE: ${MYSQL_DATABASE:-qqq}
|
||||
QQQ_ALL_MYSQL_USER: ${MYSQL_USER:-qqq}
|
||||
QQQ_ALL_MYSQL_PASSWORD: ${MYSQL_PASSWORD:?set MYSQL_PASSWORD}
|
||||
QQQ_ALL_MONGO_HOST: mongo
|
||||
QQQ_ALL_MONGO_DATABASE: ${MONGO_DATABASE:-qqq}
|
||||
QQQ_ALL_MONGO_USER: ${MONGO_USER:-qqq}
|
||||
QQQ_ALL_MONGO_PASSWORD: ${MONGO_PASSWORD:?set MONGO_PASSWORD}
|
||||
QQQ_ALL_MONGO_REPLICA_SET: ${MONGO_REPLICA_SET:-rs0}
|
||||
QQQ_ALL_S3_ENDPOINT: http://minio:9000
|
||||
QQQ_ALL_S3_BUCKET: ${MINIO_BUCKET:-qqq-demo}
|
||||
QQQ_ALL_S3_ACCESS_KEY: ${MINIO_ROOT_USER:-qqq}
|
||||
QQQ_ALL_S3_SECRET_KEY: ${MINIO_ROOT_PASSWORD:?set MINIO_ROOT_PASSWORD}
|
||||
QQQ_ALL_SFTP_HOST: sftp
|
||||
QQQ_ALL_SFTP_USER: ${SFTP_USER:-qqq}
|
||||
QQQ_ALL_SFTP_PASSWORD: ${SFTP_PASSWORD:?set SFTP_PASSWORD}
|
||||
QQQ_ALL_ARTEMIS_URL: tcp://artemis:61616
|
||||
QQQ_ALL_ARTEMIS_USER: ${ARTEMIS_USER:-qqq}
|
||||
QQQ_ALL_ARTEMIS_PASSWORD: ${ARTEMIS_PASSWORD:?set ARTEMIS_PASSWORD}
|
||||
QQQ_ALL_ARTEMIS_MANAGEMENT_URL: http://artemis:8161
|
||||
QQQ_ALL_RABBITMQ_URL: amqp://rabbitmq:5672/%2F
|
||||
QQQ_ALL_RABBITMQ_USER: ${RABBITMQ_USER:-qqq}
|
||||
QQQ_ALL_RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD:?set RABBITMQ_PASSWORD}
|
||||
QQQ_ALL_RABBITMQ_MANAGEMENT_URL: http://rabbitmq:15672
|
||||
QQQ_ALL_OPENSEARCH_HOST: opensearch
|
||||
QQQ_ALL_SMTP_HOST: mailpit
|
||||
QQQ_ALL_OIDC_BASE_URL: http://keycloak.localhost:${KEYCLOAK_PORT:-8081}/realms/qqq-all
|
||||
QQQ_ALL_OIDC_CLIENT_ID: qqq-all
|
||||
QQQ_ALL_OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:?set OIDC_CLIENT_SECRET}
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
mysql: {condition: service_healthy}
|
||||
mongo-init: {condition: service_completed_successfully}
|
||||
minio-init: {condition: service_completed_successfully}
|
||||
sftp: {condition: service_healthy}
|
||||
opensearch: {condition: service_healthy}
|
||||
artemis: {condition: service_healthy}
|
||||
rabbitmq: {condition: service_healthy}
|
||||
mailpit: {condition: service_healthy}
|
||||
keycloak: {condition: service_healthy}
|
||||
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
profiles: [full]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DATABASE:-qqq}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-qqq}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD}
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
- ./infra/postgres:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$$POSTGRES_USER\" -d \"$$POSTGRES_DB\""]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
mysql:
|
||||
image: mysql:8.4
|
||||
profiles: [full]
|
||||
environment:
|
||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-qqq}
|
||||
MYSQL_USER: ${MYSQL_USER:-qqq}
|
||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:?set MYSQL_PASSWORD}
|
||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?set MYSQL_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- mysql-data:/var/lib/mysql
|
||||
- ./infra/mysql:/docker-entrypoint-initdb.d:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mysqladmin ping -h 127.0.0.1 -u root -p\"$$MYSQL_ROOT_PASSWORD\" --silent"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
start_period: 20s
|
||||
|
||||
mongo:
|
||||
image: mongo:7
|
||||
profiles: [full]
|
||||
entrypoint: ["bash", "/start.sh"]
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: ${MONGO_USER:-qqq}
|
||||
MONGO_INITDB_ROOT_PASSWORD: ${MONGO_PASSWORD:?set MONGO_PASSWORD}
|
||||
MONGO_REPLICA_SET: ${MONGO_REPLICA_SET:-rs0}
|
||||
MONGO_KEYFILE: ${MONGO_KEYFILE:?set MONGO_KEYFILE}
|
||||
volumes:
|
||||
- mongo-data:/data/db
|
||||
- mongo-config:/data/configdb
|
||||
- ./infra/mongo/start.sh:/start.sh:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "mongosh --quiet -u \"$$MONGO_INITDB_ROOT_USERNAME\" -p \"$$MONGO_INITDB_ROOT_PASSWORD\" --authenticationDatabase admin --eval 'db.adminCommand({ping:1}).ok' | grep -q 1"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
mongo-init:
|
||||
image: mongo:7
|
||||
profiles: [full]
|
||||
depends_on:
|
||||
mongo: {condition: service_healthy}
|
||||
environment:
|
||||
MONGO_REPLICA_SET: ${MONGO_REPLICA_SET:-rs0}
|
||||
MONGO_USER: ${MONGO_USER:-qqq}
|
||||
MONGO_PASSWORD: ${MONGO_PASSWORD:?set MONGO_PASSWORD}
|
||||
volumes:
|
||||
- ./infra/mongo/init.sh:/init.sh:ro
|
||||
entrypoint: ["bash", "/init.sh"]
|
||||
restart: "no"
|
||||
|
||||
minio:
|
||||
build:
|
||||
context: ./infra/minio
|
||||
image: qqq-all-minio:local
|
||||
profiles: [full]
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-qqq}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?set MINIO_ROOT_PASSWORD}
|
||||
volumes:
|
||||
- minio-data:/data
|
||||
ports:
|
||||
- "127.0.0.1:9001:9001"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9000/minio/health/live"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
minio-init:
|
||||
image: public.ecr.aws/aws-cli/aws-cli:2.27.41
|
||||
profiles: [full]
|
||||
depends_on:
|
||||
minio: {condition: service_healthy}
|
||||
environment:
|
||||
AWS_ACCESS_KEY_ID: ${MINIO_ROOT_USER:-qqq}
|
||||
AWS_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD:?set MINIO_ROOT_PASSWORD}
|
||||
AWS_DEFAULT_REGION: us-east-1
|
||||
MINIO_BUCKET: ${MINIO_BUCKET:-qqq-demo}
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command: ["aws --endpoint-url http://minio:9000 s3api head-bucket --bucket \"$$MINIO_BUCKET\" >/dev/null 2>&1 || aws --endpoint-url http://minio:9000 s3api create-bucket --bucket \"$$MINIO_BUCKET\""]
|
||||
restart: "no"
|
||||
|
||||
sftp:
|
||||
image: atmoz/sftp:alpine
|
||||
profiles: [full]
|
||||
command: "${SFTP_USER:-qqq}:${SFTP_PASSWORD:?set SFTP_PASSWORD}:1001:1001:upload"
|
||||
volumes:
|
||||
- sftp-data:/home/${SFTP_USER:-qqq}/upload
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pgrep sshd >/dev/null"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
opensearch:
|
||||
image: opensearchproject/opensearch:2.19.1
|
||||
profiles: [full]
|
||||
environment:
|
||||
discovery.type: single-node
|
||||
DISABLE_SECURITY_PLUGIN: "true"
|
||||
OPENSEARCH_JAVA_OPTS: -Xms512m -Xmx512m
|
||||
volumes:
|
||||
- opensearch-data:/usr/share/opensearch/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "curl --fail --silent http://127.0.0.1:9200/_cluster/health >/dev/null"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
start_period: 30s
|
||||
|
||||
artemis:
|
||||
image: apache/activemq-artemis:2.42.0-alpine
|
||||
profiles: [full]
|
||||
environment:
|
||||
ARTEMIS_USER: ${ARTEMIS_USER:-qqq}
|
||||
ARTEMIS_PASSWORD: ${ARTEMIS_PASSWORD:?set ARTEMIS_PASSWORD}
|
||||
ANONYMOUS_LOGIN: "false"
|
||||
volumes:
|
||||
- artemis-data:/var/lib/artemis-instance
|
||||
ports:
|
||||
- "127.0.0.1:8161:8161"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8161/console/"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:4-management-alpine
|
||||
profiles: [full]
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_USER:-qqq}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_PASSWORD:?set RABBITMQ_PASSWORD}
|
||||
volumes:
|
||||
- rabbitmq-data:/var/lib/rabbitmq
|
||||
ports:
|
||||
- "127.0.0.1:15672:15672"
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
mailpit:
|
||||
image: axllent/mailpit:v1.22.3
|
||||
profiles: [full]
|
||||
ports:
|
||||
- "127.0.0.1:8025:8025"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8025/api/v1/info"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
keycloak:
|
||||
image: quay.io/keycloak/keycloak:26.2.5
|
||||
profiles: [full]
|
||||
networks:
|
||||
default:
|
||||
aliases: [keycloak.localhost]
|
||||
command: ["start-dev", "--import-realm"]
|
||||
environment:
|
||||
KC_BOOTSTRAP_ADMIN_USERNAME: ${KEYCLOAK_ADMIN:-admin}
|
||||
KC_BOOTSTRAP_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:?set KEYCLOAK_ADMIN_PASSWORD}
|
||||
KC_HEALTH_ENABLED: "true"
|
||||
KC_HOSTNAME: http://keycloak.localhost:${KEYCLOAK_PORT:-8081}
|
||||
KC_HTTP_ENABLED: "true"
|
||||
KC_HTTP_PORT: ${KEYCLOAK_PORT:-8081}
|
||||
OIDC_CLIENT_SECRET: ${OIDC_CLIENT_SECRET:?set OIDC_CLIENT_SECRET}
|
||||
DEMO_ADMIN_PASSWORD: ${DEMO_ADMIN_PASSWORD:?set DEMO_ADMIN_PASSWORD}
|
||||
DEMO_USER_PASSWORD: ${DEMO_USER_PASSWORD:?set DEMO_USER_PASSWORD}
|
||||
QQQ_ALL_PORT: ${QQQ_ALL_PORT:-8080}
|
||||
volumes:
|
||||
- ./infra/keycloak/realm.json:/opt/keycloak/data/import/realm.json:ro
|
||||
ports:
|
||||
- "127.0.0.1:${KEYCLOAK_PORT:-8081}:${KEYCLOAK_PORT:-8081}"
|
||||
healthcheck:
|
||||
test: ["CMD", "bash", "-c", "{ printf 'HEAD /health/ready HTTP/1.0\r\n\r\n' >&0; grep 'HTTP/1.0 200'; } 0<>/dev/tcp/127.0.0.1/9000"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 30
|
||||
start_period: 30s
|
||||
|
||||
volumes:
|
||||
app-data:
|
||||
postgres-data:
|
||||
mysql-data:
|
||||
mongo-data:
|
||||
mongo-config:
|
||||
minio-data:
|
||||
sftp-data:
|
||||
opensearch-data:
|
||||
artemis-data:
|
||||
rabbitmq-data:
|
||||
@@ -0,0 +1,51 @@
|
||||
{
|
||||
"realm": "qqq-all",
|
||||
"enabled": true,
|
||||
"displayName": "QQQ All Demo",
|
||||
"registrationAllowed": false,
|
||||
"loginWithEmailAllowed": true,
|
||||
"roles": {
|
||||
"realm": [
|
||||
{"name": "admin", "description": "Full demo permissions"},
|
||||
{"name": "viewer", "description": "Read-only demo permissions"}
|
||||
]
|
||||
},
|
||||
"clients": [
|
||||
{
|
||||
"clientId": "qqq-all",
|
||||
"name": "QQQ All Demo",
|
||||
"enabled": true,
|
||||
"protocol": "openid-connect",
|
||||
"publicClient": false,
|
||||
"clientAuthenticatorType": "client-secret",
|
||||
"secret": "${OIDC_CLIENT_SECRET}",
|
||||
"standardFlowEnabled": true,
|
||||
"directAccessGrantsEnabled": false,
|
||||
"redirectUris": ["http://localhost:${QQQ_ALL_PORT}/*", "http://127.0.0.1:${QQQ_ALL_PORT}/*"],
|
||||
"webOrigins": ["http://localhost:${QQQ_ALL_PORT}", "http://127.0.0.1:${QQQ_ALL_PORT}"],
|
||||
"defaultClientScopes": ["web-origins", "acr", "profile", "roles", "email"]
|
||||
}
|
||||
],
|
||||
"users": [
|
||||
{
|
||||
"username": "demo-admin",
|
||||
"email": "admin@example.test",
|
||||
"firstName": "Demo",
|
||||
"lastName": "Admin",
|
||||
"enabled": true,
|
||||
"emailVerified": true,
|
||||
"realmRoles": ["admin"],
|
||||
"credentials": [{"type": "password", "value": "${DEMO_ADMIN_PASSWORD}", "temporary": false}]
|
||||
},
|
||||
{
|
||||
"username": "demo-user",
|
||||
"email": "user@example.test",
|
||||
"firstName": "Demo",
|
||||
"lastName": "User",
|
||||
"enabled": true,
|
||||
"emailVerified": true,
|
||||
"realmRoles": ["viewer"],
|
||||
"credentials": [{"type": "password", "value": "${DEMO_USER_PASSWORD}", "temporary": false}]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
FROM golang:1.24-alpine AS build
|
||||
RUN apk add --no-cache git
|
||||
RUN git clone --depth 1 --branch RELEASE.2025-09-06T17-38-46Z https://github.com/minio/minio.git /src
|
||||
WORKDIR /src
|
||||
RUN CGO_ENABLED=0 go build -trimpath -o /minio .
|
||||
|
||||
FROM alpine:3.20
|
||||
RUN apk add --no-cache ca-certificates \
|
||||
&& addgroup -S -g 10001 minio \
|
||||
&& adduser -S -u 10001 -G minio minio \
|
||||
&& mkdir /data \
|
||||
&& chown minio:minio /data
|
||||
COPY --from=build /minio /usr/local/bin/minio
|
||||
USER 10001:10001
|
||||
EXPOSE 9000 9001
|
||||
ENTRYPOINT ["minio"]
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
for attempt in {1..30}; do
|
||||
if mongosh --host mongo --quiet -u "${MONGO_USER}" -p "${MONGO_PASSWORD}" --authenticationDatabase admin \
|
||||
--eval 'try { rs.status().ok } catch (e) { if (e.codeName === "NotYetInitialized") { rs.initiate({_id: process.env.MONGO_REPLICA_SET, members: [{_id: 0, host: "mongo:27017"}]}).ok } else { throw e } }' | grep -q 1; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo 'Mongo replica set did not initialize' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
printf '%s' "${MONGO_KEYFILE}" | base64 > /data/configdb/keyfile
|
||||
chmod 400 /data/configdb/keyfile
|
||||
chown mongodb:mongodb /data/configdb/keyfile
|
||||
exec docker-entrypoint.sh mongod --replSet "${MONGO_REPLICA_SET}" --bind_ip_all --auth --keyFile /data/configdb/keyfile
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE IF NOT EXISTS supplier_order (
|
||||
id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
reference VARCHAR(120) NOT NULL
|
||||
);
|
||||
|
||||
INSERT IGNORE INTO supplier_order (id, reference) VALUES (1, 'DEMO-SUPPLIER-001');
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE IF NOT EXISTS warehouse_customer (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
name VARCHAR(120) NOT NULL
|
||||
);
|
||||
|
||||
INSERT INTO warehouse_customer (id, name) VALUES (1, 'Demo Warehouse Customer')
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
@@ -0,0 +1,90 @@
|
||||
-- C4's OAuth2 session tables and qbit-user-role-permissions tables.
|
||||
-- Names follow QInstanceEnricher's camelCase-to-snake_case backend mapping.
|
||||
CREATE TABLE IF NOT EXISTS user_session (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
uuid VARCHAR(40) UNIQUE,
|
||||
access_token TEXT,
|
||||
user_id VARCHAR(100)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS redirect_state (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
state VARCHAR(45) UNIQUE,
|
||||
redirect_uri VARCHAR(4096),
|
||||
create_date TIMESTAMPTZ
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "user" (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
email VARCHAR(250),
|
||||
full_name VARCHAR(250)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
name VARCHAR(100) NOT NULL UNIQUE,
|
||||
description VARCHAR(500)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS permission (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
name VARCHAR(250) NOT NULL UNIQUE,
|
||||
description VARCHAR(500),
|
||||
object_type VARCHAR(50),
|
||||
object_label VARCHAR(250)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS role_permission_int (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
role_id INTEGER NOT NULL REFERENCES role(id),
|
||||
permission_id INTEGER NOT NULL REFERENCES permission(id),
|
||||
UNIQUE (role_id, permission_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_role_int (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
user_id INTEGER NOT NULL REFERENCES "user"(id),
|
||||
role_id INTEGER NOT NULL REFERENCES role(id),
|
||||
UNIQUE (user_id, role_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_permission_int (
|
||||
id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
create_date TIMESTAMPTZ,
|
||||
modify_date TIMESTAMPTZ,
|
||||
user_id INTEGER NOT NULL REFERENCES "user"(id),
|
||||
permission_id INTEGER NOT NULL REFERENCES permission(id),
|
||||
UNIQUE (user_id, permission_id)
|
||||
);
|
||||
|
||||
INSERT INTO role (name, description) VALUES
|
||||
('admin', 'All QQQ All demo tables'),
|
||||
('viewer', 'Read-only QQQ All demo tables')
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO permission (name, object_type, object_label)
|
||||
SELECT table_name || '.' || action, 'table', table_name
|
||||
FROM (VALUES
|
||||
('customer'), ('order'), ('orderLine'), ('product'),
|
||||
('warehouseCustomer'), ('supplierOrder'), ('shipment'), ('document'), ('importFile')
|
||||
) AS tables(table_name)
|
||||
CROSS JOIN (VALUES ('read'), ('insert'), ('edit'), ('delete')) AS actions(action)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO role_permission_int (role_id, permission_id)
|
||||
SELECT role.id, permission.id
|
||||
FROM role CROSS JOIN permission
|
||||
WHERE role.name = 'admin' OR (role.name = 'viewer' AND permission.name LIKE '%.read')
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Add the webhook qbit's protected resources to the demo OIDC roles.
|
||||
-- Runs after C6's 02-auth-and-roles.sql during PostgreSQL initialization.
|
||||
INSERT INTO permission (name, object_type, object_label)
|
||||
SELECT table_name || '.' || action, 'table', table_name
|
||||
FROM (VALUES
|
||||
('webhook'), ('webhookSubscription'), ('webhookEvent'),
|
||||
('webhookEventContent'), ('webhookEventSendLog'),
|
||||
('scheduledJob'), ('scheduledJobParameter')
|
||||
) AS tables(table_name)
|
||||
CROSS JOIN (VALUES ('read'), ('insert'), ('edit'), ('delete')) AS actions(action)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO permission (name, object_type, object_label)
|
||||
SELECT process_name || '.hasAccess', 'process', process_name
|
||||
FROM (VALUES
|
||||
('SendWebhookEvent'), ('SendTestEventToWebhook'), ('ManageWebhookHealth')
|
||||
) AS processes(process_name)
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO role_permission_int (role_id, permission_id)
|
||||
SELECT role.id, permission.id
|
||||
FROM role CROSS JOIN permission
|
||||
WHERE (role.name = 'admin' OR (role.name = 'viewer' AND permission.name LIKE '%.read'))
|
||||
AND (permission.name LIKE 'webhook.%'
|
||||
OR permission.name LIKE 'webhookSubscription.%'
|
||||
OR permission.name LIKE 'webhookEvent.%'
|
||||
OR permission.name LIKE 'webhookEventContent.%'
|
||||
OR permission.name LIKE 'webhookEventSendLog.%'
|
||||
OR permission.name LIKE 'scheduledJob.%'
|
||||
OR permission.name LIKE 'scheduledJobParameter.%'
|
||||
OR permission.name IN ('SendWebhookEvent.hasAccess',
|
||||
'SendTestEventToWebhook.hasAccess', 'ManageWebhookHealth.hasAccess'))
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,15 @@
|
||||
/* Give the full-profile demo admin service-level ESB visibility and controls.
|
||||
The viewer role keeps table READ without broker-wide message access. */
|
||||
INSERT INTO permission (name, object_type, object_label)
|
||||
VALUES
|
||||
('esbView.hasAccess', 'app', 'ESB'),
|
||||
('esbOperate.hasAccess', 'process', 'ESB operations'),
|
||||
('esbDelete.hasAccess', 'process', 'ESB message deletion')
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO role_permission_int (role_id, permission_id)
|
||||
SELECT role.id, permission.id
|
||||
FROM role CROSS JOIN permission
|
||||
WHERE role.name = 'admin'
|
||||
AND permission.name IN ('esbView.hasAccess', 'esbOperate.hasAccess', 'esbDelete.hasAccess')
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- Read-only API catalog, transient notes, and the fixed JavaScript calculation.
|
||||
INSERT INTO permission (name, object_type, object_label)
|
||||
VALUES
|
||||
('apiCatalog.read', 'table', 'API Catalog'),
|
||||
('demoNote.read', 'table', 'Demo Note (Transient)'),
|
||||
('demoNote.insert', 'table', 'Demo Note (Transient)'),
|
||||
('demoNote.edit', 'table', 'Demo Note (Transient)'),
|
||||
('demoNote.delete', 'table', 'Demo Note (Transient)'),
|
||||
('calculateOrderTotal.hasAccess', 'process', 'Calculate Order Total (JavaScript)')
|
||||
ON CONFLICT (name) DO NOTHING;
|
||||
|
||||
INSERT INTO role_permission_int (role_id, permission_id)
|
||||
SELECT role.id, permission.id
|
||||
FROM role CROSS JOIN permission
|
||||
WHERE permission.name IN ('apiCatalog.read', 'demoNote.read', 'demoNote.insert',
|
||||
'demoNote.edit', 'demoNote.delete', 'calculateOrderTotal.hasAccess')
|
||||
AND (role.name = 'admin' OR (role.name = 'viewer' AND permission.name IN ('apiCatalog.read', 'demoNote.read')))
|
||||
ON CONFLICT (role_id, permission_id) DO NOTHING;
|
||||
@@ -0,0 +1,125 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>QQQ All</name>
|
||||
<description>QQQ with every feature configured and working out of the box: a tested stack BOM and a reference application.</description>
|
||||
<url>https://github.com/QRun-IO/qqq-all</url>
|
||||
<licenses>
|
||||
<license>
|
||||
<name>Apache License, Version 2.0</name>
|
||||
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
|
||||
<distribution>repo</distribution>
|
||||
</license>
|
||||
</licenses>
|
||||
<scm>
|
||||
<connection>scm:git:https://github.com/QRun-IO/qqq-all.git</connection>
|
||||
<developerConnection>scm:git:ssh://git@github.com/QRun-IO/qqq-all.git</developerConnection>
|
||||
<url>https://github.com/QRun-IO/qqq-all</url>
|
||||
<tag>HEAD</tag>
|
||||
</scm>
|
||||
<developers>
|
||||
<developer>
|
||||
<id>kingsrook</id>
|
||||
<name>Kingsrook, LLC</name>
|
||||
<email>pub@qrun.io</email>
|
||||
<organization>Kingsrook, LLC</organization>
|
||||
<organizationUrl>https://qrun.io</organizationUrl>
|
||||
</developer>
|
||||
</developers>
|
||||
|
||||
<modules>
|
||||
<module>qqq-all-bom</module>
|
||||
<module>qqq-all-bom-test</module>
|
||||
<module>qqq-all-app</module>
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<!-- qqq-all versions track QQQ versions. -->
|
||||
<revision>4.1.0-SNAPSHOT</revision>
|
||||
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<maven.compiler.release>21</maven.compiler.release>
|
||||
</properties>
|
||||
|
||||
<repositories>
|
||||
<!-- QQQ 4.1.0-SNAPSHOT and other QRun-IO snapshots are published here until 4.1 ships. -->
|
||||
<repository>
|
||||
<id>central-portal-snapshots</id>
|
||||
<name>Sonatype Central Portal Snapshots</name>
|
||||
<url>https://central.sonatype.com/repository/maven-snapshots/</url>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>always</updatePolicy>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<!-- Pinned because CI's system Maven (3.6.3) defaults to plugins that predate maven.compiler.release and JUnit 5. -->
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.3.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.14.1</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.5.4</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
<plugins>
|
||||
<!-- Resolve ${revision} in installed and deployed POMs (CI sets it per branch). -->
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>flatten-maven-plugin</artifactId>
|
||||
<version>1.7.3</version>
|
||||
<configuration>
|
||||
<updatePomFile>true</updatePomFile>
|
||||
<flattenMode>resolveCiFriendliesOnly</flattenMode>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>flatten</id>
|
||||
<phase>process-resources</phase>
|
||||
<goals>
|
||||
<goal>flatten</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>flatten.clean</id>
|
||||
<phase>clean</phase>
|
||||
<goals>
|
||||
<goal>clean</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,118 @@
|
||||
# Core reference app
|
||||
|
||||
Build with Java 21 and Maven, then start the standalone core profile:
|
||||
|
||||
```sh
|
||||
mvn -pl qqq-all-app -am verify
|
||||
java -jar qqq-all-app/target/qqq-all-app.jar
|
||||
```
|
||||
|
||||
The core app binds to `127.0.0.1` and serves the Next dashboard at `http://127.0.0.1:8080/` and health at `/health`. Set `QQQ_ALL_PORT` to change the port and `QQQ_ALL_DATA_DIR` to change the default `./data` directory. On first start it seeds customers and orders in H2, order lines in SQLite, and products as JSON files. Artemis runs in the same JVM; inserts and updates to `order` publish to the `orderEvents` topic and trigger `syncOrder`.
|
||||
|
||||
`QQQ_ALL_BIND_HOST` can select another interface when intentionally running behind a container port mapping. The Compose core service sets it to `0.0.0.0` inside the container while publishing only on host loopback.
|
||||
|
||||
Core uses mock authentication. The `sessionId` cookie selects the two fixed demo identities: `aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa` for Admin and `dddddddd-dddd-4ddd-8ddd-dddddddddddd` for Demo User. Any other session ID uses Demo User. Admin can read and write the customer, order, order-line, product, and address tables and open the ESB overview at `/qqq/v1/esb/overview`; Demo User can read those tables but cannot write them or open the ESB overview. These identities are for local demonstrations. Quick search is disabled in core because it requires OpenSearch; the customer list remains available through the normal table query API.
|
||||
|
||||
The core demo seeds a customer table view, a shipping address linked to the geo country/state/city tables, and an order review workflow. The `RunRecordWorkflow` process can run that workflow against an order; `syncOrder` writes a process trace after an order event. It also seeds an active `orderStored` webhook subscription to its receiver at `/demo/order-webhook`. Insert an order as Admin, run `SendWebhookEvent` as Admin, and inspect `/demo/order-webhook-receipts` to see the delivered payload. Demo User can read webhook records but cannot edit their configuration or invoke the delivery process. The receiver is available only in the core profile, which Compose publishes on host loopback.
|
||||
|
||||
## Full profile
|
||||
|
||||
Set `QQQ_ALL_PROFILE=full` to use external services. The full profile requires an explicit `QQQ_ALL_BIND_HOST`; use `127.0.0.1` for local-only access or deliberately set another interface when a reverse proxy needs it. `QQQ_ALL_PORT` defaults to `8080`. The full profile replaces core's mock authentication with Keycloak OIDC. It does not start an embedded broker.
|
||||
|
||||
Configure the following environment variables before starting the same jar:
|
||||
|
||||
| Service | Required variables | Optional variables (default) |
|
||||
| --- | --- | --- |
|
||||
| PostgreSQL | `QQQ_ALL_POSTGRES_HOST`, `QQQ_ALL_POSTGRES_DATABASE`, `QQQ_ALL_POSTGRES_USER`, `QQQ_ALL_POSTGRES_PASSWORD` | `QQQ_ALL_POSTGRES_PORT` (5432) |
|
||||
| MySQL | `QQQ_ALL_MYSQL_HOST`, `QQQ_ALL_MYSQL_DATABASE`, `QQQ_ALL_MYSQL_USER`, `QQQ_ALL_MYSQL_PASSWORD` | `QQQ_ALL_MYSQL_PORT` (3306) |
|
||||
| MongoDB replica set | `QQQ_ALL_MONGO_HOST`, `QQQ_ALL_MONGO_DATABASE`, `QQQ_ALL_MONGO_USER`, `QQQ_ALL_MONGO_PASSWORD`, `QQQ_ALL_MONGO_REPLICA_SET` | `QQQ_ALL_MONGO_PORT` (27017), `QQQ_ALL_MONGO_AUTH_DATABASE` (admin) |
|
||||
| MinIO S3 | `QQQ_ALL_S3_ENDPOINT`, `QQQ_ALL_S3_BUCKET`, `QQQ_ALL_S3_ACCESS_KEY`, `QQQ_ALL_S3_SECRET_KEY` | `QQQ_ALL_S3_REGION` (us-east-1) |
|
||||
| SFTP | `QQQ_ALL_SFTP_HOST`, `QQQ_ALL_SFTP_USER`, `QQQ_ALL_SFTP_PASSWORD` | `QQQ_ALL_SFTP_PORT` (22), `QQQ_ALL_SFTP_BASE_PATH` (/upload) |
|
||||
| ESB | `QQQ_ALL_ARTEMIS_URL`, `QQQ_ALL_ARTEMIS_USER`, `QQQ_ALL_ARTEMIS_PASSWORD`, `QQQ_ALL_ARTEMIS_MANAGEMENT_URL`, `QQQ_ALL_RABBITMQ_URL`, `QQQ_ALL_RABBITMQ_USER`, `QQQ_ALL_RABBITMQ_PASSWORD`, `QQQ_ALL_RABBITMQ_MANAGEMENT_URL` | — |
|
||||
| Mailpit SMTP | `QQQ_ALL_SMTP_HOST` | `QQQ_ALL_SMTP_PORT` (1025) |
|
||||
| Keycloak OIDC | `QQQ_ALL_OIDC_BASE_URL`, `QQQ_ALL_OIDC_CLIENT_ID`, `QQQ_ALL_OIDC_CLIENT_SECRET` | `QQQ_ALL_OIDC_EXTERNAL_BASE_URL` (base URL), `QQQ_ALL_OIDC_SCOPES` (`openid email profile`) |
|
||||
| OpenSearch quick search | `QQQ_ALL_OPENSEARCH_HOST` | `QQQ_ALL_OPENSEARCH_PORT` (9200), `QQQ_ALL_OPENSEARCH_INDEX` (`qqq-all-customers`), `QQQ_ALL_OPENSEARCH_USER`, `QQQ_ALL_OPENSEARCH_PASSWORD`, `QQQ_ALL_OPENSEARCH_SSL` (false) |
|
||||
|
||||
The full app adds sample tables on each external backend, `orderEvents` on Artemis, and `orderSyncEvents` on RabbitMQ. Quick search is configured for customer `name` and `email`; run `quickSearchFullReindex` after OpenSearch and the customer data are ready. The SFTP integration adds its import source and staging tables plus `SFTPImportFileSyncProcess`; `externalImportFile` remains the direct SFTP file sample. Keycloak realm roles resolve by name against the PostgreSQL `role` table from `qbit-user-role-permissions`, then become QQQ session permissions. Unknown roles receive no permissions. Webhook tables and delivery processes require explicit permissions: the viewer role receives read access, while the admin role can edit destinations and run delivery. The Compose profile provisions demo SQL tables, OAuth session and redirect-state tables, qbit permission tables and roles, and the MinIO bucket on first startup; `infra/postgres/03-webhook-permissions.sql` adds webhook grants after the role seed.
|
||||
|
||||
The full-profile admin receives ESB service visibility, queue controls, and message deletion through `infra/postgres/04-esb-permissions.sql`; the viewer role does not. The full smoke checks the RabbitMQ process-completion event through QQQ's authenticated ESB message endpoint, which decodes the broker's JMS message. Fresh PostgreSQL volumes apply this SQL automatically. For a running full-profile stack with an existing volume, apply the idempotent grant file once:
|
||||
|
||||
```bash
|
||||
COMPOSE_PROFILES=full docker compose exec -T postgres sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"' < infra/postgres/04-esb-permissions.sql
|
||||
```
|
||||
|
||||
Then sign in as Admin and open the ESB overview. The Viewer role must remain unable to open it.
|
||||
|
||||
On startup, the full demo creates its remaining PostgreSQL qbit tables from the registered metadata and checks every expected column and type. The hand-maintained domain, OAuth, and role tables stay under `infra/postgres`. If a persisted qbit table is missing a required column or has a different type, startup fails with a migration/reset message instead of silently accepting it. The full-profile RabbitMQ completion-event smoke requires QQQ's process publishing and permission-scoped ESB message endpoint; the broker management smoke below can run independently.
|
||||
|
||||
After starting the full Compose profile, run the opt-in broker management smoke test with the same broker credentials. For the supplied demo environment:
|
||||
|
||||
```sh
|
||||
set -a
|
||||
. ./.env.example
|
||||
set +a
|
||||
QQQ_ALL_COMPOSE_BROKERS=true mvn -pl qqq-all-app -am -Dtest=FullProfileBrokerIntegrationTest -Dsurefire.failIfNoSpecifiedTests=false test
|
||||
```
|
||||
|
||||
The test uses the loopback management ports to read and pause/resume the Artemis subscription queue, then creates, reads, purges, and deletes a temporary RabbitMQ queue. For a customized `.env`, source that file instead. It is skipped during ordinary `mvn verify`.
|
||||
|
||||
## Local runtime demonstrations (#21)
|
||||
|
||||
Both profiles include the BOM-managed API backend and JavaScript module. The shaded
|
||||
JAR retains Nashorn's `ScriptEngineFactory` service registration. No extra service,
|
||||
API key, script editor, or user-supplied code is needed.
|
||||
|
||||
| Demo | Behavior | Access |
|
||||
| --- | --- | --- |
|
||||
| `apiCatalog` | QQQ API-backed table reads three synthetic products from this app's `/demo/catalog` HTTP endpoint; native queries page through the endpoint and get-by-ID uses `/demo/catalog/{id}`. | Admin and Demo/Viewer can read; neither receives write grants. |
|
||||
| `calculateOrderTotal` | Executes fixed JavaScript through `ExecuteCodeAction`: quantity × unit price in cents → `totalCents`. It changes no records. | Admin only. |
|
||||
| `demoNote` | Memory-backed table, seeded with `Transient demo note` on every start and cleared on shutdown. | Admin can edit; Demo/Viewer can read. |
|
||||
|
||||
The internal catalog URL follows `QQQ_ALL_BIND_HOST` and the configured HTTP port.
|
||||
IPv4/IPv6 wildcard listeners use their corresponding loopback address; literal
|
||||
IPv6 hosts are bracketed correctly in the URL.
|
||||
|
||||
The catalog endpoint exposes **only synthetic public demo data**. It is not an
|
||||
outbound proxy and does not forward session credentials. The adapter supports
|
||||
ascending ID order, limit/skip pagination, and one exact ID filter; unsupported
|
||||
filters and sorts fail explicitly. Native get of an absent ID returns no record.
|
||||
The endpoint rejects invalid or excessive page sizes (maximum 1000).
|
||||
|
||||
With the core JAR running on port 8080, exercise the real QQQ routes:
|
||||
|
||||
```sh
|
||||
curl -fsS -H 'Content-Type: application/json' -d '{}' http://127.0.0.1:8080/qqq/v1/table/apiCatalog/query
|
||||
curl -fsS http://127.0.0.1:8080/data/apiCatalog/103
|
||||
curl -fsS -H 'Cookie: sessionId=aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa' -H 'Content-Type: application/json' -d '{}' 'http://127.0.0.1:8080/processes/calculateOrderTotal/run?quantity=3&unitPriceCents=1250'
|
||||
```
|
||||
|
||||
The last response contains `values.totalCents: 3750`. Quantity must be an integer
|
||||
in 1..1000; unit price must be an integer in 0..1000000 cents. The process does not
|
||||
accept code from the caller. This demonstration does not alter stored-script or
|
||||
Test-mode behavior.
|
||||
|
||||
Memory notes are deliberately **not persisted** with the data directory or a
|
||||
Compose volume. Restarting discards edits and restores the seed. Like the existing
|
||||
QQQ memory and ESB runtime singletons, this demo assumes one application per JVM.
|
||||
The memory lifecycle touches only `demoNote`; it never resets the global store.
|
||||
|
||||
Full-profile PostgreSQL now uses QQQ's first-party `PostgreSQLBackendMetaData` and
|
||||
strategy, including driver/URL selection, quoted identifiers, default-value
|
||||
inserts, generated IDs, null binding, and UTC timestamp handling. Existing qbit
|
||||
schema provisioning and compatibility checks remain in place.
|
||||
|
||||
Fresh full-profile volumes apply `infra/postgres/05-runtime-demo-permissions.sql`.
|
||||
For an existing volume, apply the idempotent grants and then sign in again:
|
||||
|
||||
```sh
|
||||
COMPOSE_PROFILES=full docker compose exec -T postgres sh -c 'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"' < infra/postgres/05-runtime-demo-permissions.sql
|
||||
```
|
||||
|
||||
`mvn -pl qqq-all-app -am verify` includes native local API, calculation/permission,
|
||||
memory restart, and packaged-JAR checks. `scripts/run_core_smoke.py` and
|
||||
`scripts/run_full_smoke.py` verify these routes with actual Admin and restricted
|
||||
sessions; full smoke also retains the OIDC, qbit, and broker checks. The opt-in
|
||||
`PostgresCompatibilityTest` uses `QQQ_ALL_TEST_POSTGRES_PORT` and
|
||||
`QQQ_ALL_TEST_POSTGRES_PASSWORD` against a local `qqq` database/user; it creates and
|
||||
drops only a uniquely named test table. It is skipped during ordinary verify.
|
||||
All eight included qbits, their explicit deferrals, and release gates are unchanged.
|
||||
@@ -0,0 +1,107 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qqq-all-app</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QQQ All - Reference Application</name>
|
||||
<description>Reference QQQ application with every backend, qBit, and the ESB wired, plus seeded demo data.</description>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-bom</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-core</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-api</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-language-support-javascript</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-rdbms</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-postgres</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-mongodb</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-sqlite</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-backend-module-filesystem</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-middleware-javalin</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-middleware-health</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-esb</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qqq</groupId><artifactId>qqq-frontend-next</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-user-role-permissions</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-quick-search</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-customizable-table-views</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-standard-process-trace</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-webhooks</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-workflows</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-geo-data</artifactId></dependency>
|
||||
<dependency><groupId>com.kingsrook.qbits</groupId><artifactId>qbit-sftp-data-integration</artifactId></dependency>
|
||||
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId></dependency>
|
||||
<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId></dependency>
|
||||
<dependency><groupId>com.h2database</groupId><artifactId>h2</artifactId></dependency>
|
||||
<dependency><groupId>org.xerial</groupId><artifactId>sqlite-jdbc</artifactId></dependency>
|
||||
<dependency><groupId>org.apache.artemis</groupId><artifactId>artemis-jakarta-server</artifactId><version>2.57.0</version></dependency>
|
||||
<dependency><groupId>com.rabbitmq.jms</groupId><artifactId>rabbitmq-jms</artifactId></dependency>
|
||||
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>6.0.2</version><scope>test</scope></dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>qqq-all-app</finalName>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-shade-plugin</artifactId>
|
||||
<version>3.6.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<phase>package</phase>
|
||||
<goals><goal>shade</goal></goals>
|
||||
<configuration>
|
||||
<transformers>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
|
||||
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
|
||||
<mainClass>com.kingsrook.qqq.all.ProfileLauncher</mainClass>
|
||||
</transformer>
|
||||
</transformers>
|
||||
<filters>
|
||||
<filter>
|
||||
<artifact>*:*</artifact>
|
||||
<excludes><exclude>META-INF/*.SF</exclude><exclude>META-INF/*.DSA</exclude><exclude>META-INF/*.RSA</exclude></excludes>
|
||||
</filter>
|
||||
</filters>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>3.5.6</version>
|
||||
<configuration>
|
||||
<systemPropertyVariables>
|
||||
<qqqAllJar>${project.build.directory}/${project.build.finalName}.jar</qqqAllJar>
|
||||
</systemPropertyVariables>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals><goal>integration-test</goal><goal>verify</goal></goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.actions.scripts.ExecuteCodeAction;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.scripts.ExecuteCodeInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.scripts.ExecuteCodeOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeType;
|
||||
|
||||
/** Execute a fixed, side-effect-free JavaScript calculation through QQQ. */
|
||||
public class CalculateOrderTotalStep implements BackendStep
|
||||
{
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
Integer quantity = input.getValueInteger("quantity");
|
||||
Integer unitPriceCents = input.getValueInteger("unitPriceCents");
|
||||
if(quantity == null || quantity < 1 || quantity > 1000
|
||||
|| unitPriceCents == null || unitPriceCents < 0 || unitPriceCents > 1_000_000)
|
||||
{
|
||||
throw new QException("Supply quantity 1..1000 and unitPriceCents 0..1000000");
|
||||
}
|
||||
ExecuteCodeOutput result = new ExecuteCodeOutput();
|
||||
new ExecuteCodeAction().run(new ExecuteCodeInput()
|
||||
.withCodeReference(new QCodeReference().withCodeType(QCodeType.JAVA_SCRIPT)
|
||||
.withInlineCode("return quantity * unitPriceCents;"))
|
||||
.withInput(Map.of("quantity", quantity, "unitPriceCents", unitPriceCents)), result);
|
||||
output.addValue("totalCents", ((Number) result.getOutput()).intValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
/** Creates the small, repeatable core demo data set before the web server starts. */
|
||||
final class CoreData
|
||||
{
|
||||
private CoreData()
|
||||
{
|
||||
}
|
||||
|
||||
static String h2DatabaseName(Path dataDirectory)
|
||||
{
|
||||
return dataDirectory.resolve("h2/qqq-all").toAbsolutePath().toString();
|
||||
}
|
||||
|
||||
static Path sqlitePath(Path dataDirectory)
|
||||
{
|
||||
return dataDirectory.resolve("sqlite/qqq-all.db");
|
||||
}
|
||||
|
||||
static void seed(Path dataDirectory) throws IOException, SQLException
|
||||
{
|
||||
Files.createDirectories(dataDirectory.resolve("h2"));
|
||||
Files.createDirectories(dataDirectory.resolve("sqlite"));
|
||||
Files.createDirectories(dataDirectory.resolve("files/products"));
|
||||
|
||||
try(Connection connection = DriverManager.getConnection(
|
||||
"jdbc:h2:file:" + h2DatabaseName(dataDirectory) + ";MODE=MySQL;DB_CLOSE_DELAY=-1", "sa", "");
|
||||
Statement statement = connection.createStatement())
|
||||
{
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS customer (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name VARCHAR(120), email VARCHAR(200))");
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, order_no VARCHAR(40), customer_id INTEGER, status VARCHAR(40))");
|
||||
statement.execute("MERGE INTO customer (id, name, email) KEY (id) VALUES (1, 'Ada Lovelace', 'ada@example.test'), (2, 'Grace Hopper', 'grace@example.test')");
|
||||
statement.execute("MERGE INTO orders (id, order_no, customer_id, status) KEY (id) VALUES (1, 'ORD-1001', 1, 'NEW')");
|
||||
}
|
||||
|
||||
try(Connection connection = DriverManager.getConnection("jdbc:sqlite:" + sqlitePath(dataDirectory));
|
||||
Statement statement = connection.createStatement())
|
||||
{
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS order_line (id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER, quantity INTEGER)");
|
||||
statement.execute("INSERT OR IGNORE INTO order_line (id, order_id, product_id, quantity) VALUES (1, 1, 1, 2)");
|
||||
}
|
||||
|
||||
Path product = dataDirectory.resolve("files/products/1.json");
|
||||
if(Files.notExists(product))
|
||||
{
|
||||
Files.writeString(product, "{\"id\":1,\"name\":\"QRun Starter Kit\",\"price\":29.00}\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import com.kingsrook.qqq.backend.core.instances.QRuntimeServiceInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.esb.runtime.QEsbRuntime;
|
||||
|
||||
/** Launches the ESB subscriber through the common QQQ application launcher. */
|
||||
public class CoreEsbRuntimeService implements QRuntimeServiceInterface
|
||||
{
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return "coreEsb";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(QInstance instance)
|
||||
{
|
||||
QEsbRuntime.getInstance().start(instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop()
|
||||
{
|
||||
QEsbRuntime.getInstance().stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.file.Path;
|
||||
import com.kingsrook.qbits.webhooks.actions.WebhookSubscriptionsHelper;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationLauncher;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationLauncherConfig;
|
||||
import org.apache.activemq.artemis.core.config.Configuration;
|
||||
import org.apache.activemq.artemis.core.config.impl.ConfigurationImpl;
|
||||
import org.apache.activemq.artemis.core.server.embedded.EmbeddedActiveMQ;
|
||||
|
||||
/** Owns the embedded broker and launcher as one closeable core profile. */
|
||||
final class CoreRuntime implements AutoCloseable
|
||||
{
|
||||
private final EmbeddedActiveMQ broker;
|
||||
private final QApplicationLauncher launcher;
|
||||
private final Thread shutdownHook;
|
||||
|
||||
private CoreRuntime(EmbeddedActiveMQ broker, QApplicationLauncher launcher)
|
||||
{
|
||||
this.broker = broker;
|
||||
this.launcher = launcher;
|
||||
this.shutdownHook = new Thread(this::close, "qqq-all-core-shutdown");
|
||||
Runtime.getRuntime().addShutdownHook(shutdownHook);
|
||||
}
|
||||
|
||||
static CoreRuntime launch(Path dataDirectory, Integer port) throws Exception
|
||||
{
|
||||
return launch(dataDirectory, port, "127.0.0.1");
|
||||
}
|
||||
|
||||
static CoreRuntime launch(Path dataDirectory, Integer port, String bindHost) throws Exception
|
||||
{
|
||||
CoreData.seed(dataDirectory);
|
||||
Integer brokerPort = findFreePort();
|
||||
Path brokerDirectory = dataDirectory.resolve("artemis").toAbsolutePath();
|
||||
String brokerUrl = "tcp://127.0.0.1:" + brokerPort;
|
||||
DemoOrderWebhookReceiver.clear();
|
||||
DemoQBitData.ensureSchema(dataDirectory, new QqqAllApplication(dataDirectory, brokerUrl, true, port, bindHost).defineQInstance(), port);
|
||||
Configuration configuration = new ConfigurationImpl()
|
||||
.setPersistenceEnabled(false).setSecurityEnabled(false).setJMXManagementEnabled(false)
|
||||
.setBindingsDirectory(brokerDirectory.resolve("bindings").toString())
|
||||
.setJournalDirectory(brokerDirectory.resolve("journal").toString())
|
||||
.setPagingDirectory(brokerDirectory.resolve("paging").toString())
|
||||
.setLargeMessagesDirectory(brokerDirectory.resolve("large-messages").toString())
|
||||
.addAcceptorConfiguration("tcp", brokerUrl);
|
||||
EmbeddedActiveMQ broker = new EmbeddedActiveMQ().setConfiguration(configuration);
|
||||
broker.start();
|
||||
try
|
||||
{
|
||||
QApplicationLauncher launcher = QApplicationLauncher.run(
|
||||
new QqqAllApplication(dataDirectory, brokerUrl, true, port, bindHost),
|
||||
new QApplicationLauncherConfig().withRegisterShutdownHook(false)
|
||||
.withServerCustomizer(server -> server.withPort(port)
|
||||
.withJavalinConfigCustomizer(config -> config.jetty.host = bindHost)));
|
||||
QContext.init(launcher.getQInstance(), new QSystemUserSession());
|
||||
try
|
||||
{
|
||||
WebhookSubscriptionsHelper.clearMemoizations();
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
return new CoreRuntime(broker, launcher);
|
||||
}
|
||||
catch(Exception | LinkageError e)
|
||||
{
|
||||
broker.stop();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static Integer findFreePort() throws IOException
|
||||
{
|
||||
try(ServerSocket socket = new ServerSocket(0))
|
||||
{
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
|
||||
QApplicationLauncher getLauncher()
|
||||
{
|
||||
return launcher;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close()
|
||||
{
|
||||
launcher.stop();
|
||||
try
|
||||
{
|
||||
broker.stop();
|
||||
}
|
||||
catch(Exception e)
|
||||
{
|
||||
throw new IllegalStateException("Could not stop embedded Artemis", e);
|
||||
}
|
||||
if(Thread.currentThread() != shutdownHook)
|
||||
{
|
||||
Runtime.getRuntime().removeShutdownHook(shutdownHook);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.module.api.actions.BaseAPIActionUtil;
|
||||
|
||||
/** The local catalog supports ascending ID pages and optional exact ID selection. */
|
||||
public class DemoCatalogApi extends BaseAPIActionUtil
|
||||
{
|
||||
@Override
|
||||
public String buildUrlSuffixForSingleRecordGet(Serializable primaryKey) throws QException
|
||||
{
|
||||
try
|
||||
{
|
||||
return "/" + Integer.parseInt(String.valueOf(primaryKey));
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
throw new QException("Invalid catalog ID", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Integer getApiStandardLimit()
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String buildQueryStringForGet(QQueryFilter filter, Integer limit, Integer skip, Map<String, QFieldMetaData> fields) throws QException
|
||||
{
|
||||
String query = "?limit=" + (limit == null ? 2 : limit) + "&skip=" + (skip == null ? 0 : skip);
|
||||
if(filter != null)
|
||||
{
|
||||
if(!filter.getSubFilters().isEmpty() || filter.getBooleanOperator() != QQueryFilter.BooleanOperator.AND
|
||||
|| filter.getCriteria().size() > 1 || filter.getOrderBys().stream().anyMatch(order -> !"id".equals(order.getFieldName()) || !order.getIsAscending()))
|
||||
{
|
||||
throw new QException("Demo catalog supports ascending ID order and one exact ID filter only");
|
||||
}
|
||||
if(!filter.getCriteria().isEmpty())
|
||||
{
|
||||
var criterion = filter.getCriteria().getFirst();
|
||||
if(!"id".equals(criterion.getFieldName()) || criterion.getOperator() != QCriteriaOperator.EQUALS || criterion.getValues().size() != 1)
|
||||
{
|
||||
throw new QException("Demo catalog supports one exact ID filter only");
|
||||
}
|
||||
try
|
||||
{
|
||||
query += "&id=" + Integer.parseInt(String.valueOf(criterion.getValues().getFirst()));
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
throw new QException("Invalid catalog ID", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return query;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountOutput doCount(QTableMetaData table, CountInput input) throws QException
|
||||
{
|
||||
QQueryFilter filter = input.getFilter() == null ? new QQueryFilter() : input.getFilter().clone();
|
||||
filter.setLimit(null);
|
||||
filter.setSkip(null);
|
||||
return new CountOutput().withCount(doQuery(table, new QueryInput(table.getName()).withFilter(filter)).getRecords().size());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface;
|
||||
import io.javalin.config.JavalinConfig;
|
||||
import static io.javalin.apibuilder.ApiBuilder.get;
|
||||
|
||||
/** Synthetic public supplier data, owned by the same server as the reference app. */
|
||||
public class DemoCatalogRoutes implements QJavalinRouteProviderInterface
|
||||
{
|
||||
private static final List<Map<String, Object>> CATALOG = List.of(
|
||||
Map.of("id", 101, "name", "Starter Kit", "unitPriceCents", 2500),
|
||||
Map.of("id", 102, "name", "Refill Pack", "unitPriceCents", 1250),
|
||||
Map.of("id", 103, "name", "Shipping Box", "unitPriceCents", 300));
|
||||
|
||||
@Override
|
||||
public void setQInstance(QInstance instance)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void acceptJavalinConfig(JavalinConfig config)
|
||||
{
|
||||
config.routes.apiBuilder(() ->
|
||||
{
|
||||
get("/demo/catalog/{id}", context ->
|
||||
{
|
||||
try
|
||||
{
|
||||
int id = Integer.parseInt(context.pathParam("id"));
|
||||
var row = CATALOG.stream().filter(item -> Integer.valueOf(id).equals(item.get("id"))).findFirst();
|
||||
if(row.isPresent())
|
||||
{
|
||||
context.json(row.get());
|
||||
}
|
||||
else
|
||||
{
|
||||
context.status(404);
|
||||
}
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
context.status(400);
|
||||
}
|
||||
});
|
||||
get("/demo/catalog", context ->
|
||||
{
|
||||
try
|
||||
{
|
||||
int skip = Integer.parseInt(context.queryParamAsClass("skip", String.class).getOrDefault("0"));
|
||||
int limit = Integer.parseInt(context.queryParamAsClass("limit", String.class).getOrDefault("2"));
|
||||
Integer id = context.queryParam("id") == null ? null : Integer.valueOf(context.queryParam("id"));
|
||||
if(skip < 0 || limit < 1 || limit > 1000)
|
||||
{
|
||||
context.status(400);
|
||||
return;
|
||||
}
|
||||
context.json(CATALOG.stream().filter(row -> id == null || id.equals(row.get("id")))
|
||||
.skip(skip).limit(limit).toList());
|
||||
}
|
||||
catch(NumberFormatException e)
|
||||
{
|
||||
context.status(400);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.webhooks.actions.WebhookEventTypeCustomizerInterface;
|
||||
import com.kingsrook.qbits.webhooks.model.WebhookEventContent;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.utils.JsonUtils;
|
||||
|
||||
/** Builds a self-contained demo payload without requiring a separate public API definition. */
|
||||
public class DemoOrderWebhookContent implements WebhookEventTypeCustomizerInterface
|
||||
{
|
||||
@Override
|
||||
public WebhookEventContent buildEventContent(QRecord record, String eventType, String apiName, String apiVersion)
|
||||
{
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("eventType", eventType);
|
||||
body.put("orderNo", record.getValueString("orderNo"));
|
||||
body.put("orderId", record.getValueInteger("id"));
|
||||
return new WebhookEventContent().withPostBody(JsonUtils.toJson(body));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinRouteProviderInterface;
|
||||
import io.javalin.config.JavalinConfig;
|
||||
import static io.javalin.apibuilder.ApiBuilder.get;
|
||||
import static io.javalin.apibuilder.ApiBuilder.post;
|
||||
|
||||
/** Local receiver that makes successful order webhook delivery visible in the core demo. */
|
||||
public class DemoOrderWebhookReceiver implements QJavalinRouteProviderInterface
|
||||
{
|
||||
private static final List<String> RECEIPTS = new CopyOnWriteArrayList<>();
|
||||
|
||||
static void clear()
|
||||
{
|
||||
RECEIPTS.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setQInstance(QInstance instance)
|
||||
{
|
||||
}
|
||||
|
||||
@Override
|
||||
public void acceptJavalinConfig(JavalinConfig config)
|
||||
{
|
||||
config.routes.apiBuilder(() ->
|
||||
{
|
||||
post("/demo/order-webhook", context ->
|
||||
{
|
||||
String body = context.body();
|
||||
if(body.length() > 8192)
|
||||
{
|
||||
context.status(413);
|
||||
return;
|
||||
}
|
||||
RECEIPTS.add(body);
|
||||
if(RECEIPTS.size() > 20)
|
||||
{
|
||||
RECEIPTS.removeFirst();
|
||||
}
|
||||
context.status(200).result("ok");
|
||||
});
|
||||
get("/demo/order-webhook-receipts", context -> context.json(List.copyOf(RECEIPTS)));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.jdbc.ConnectionManager;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
|
||||
/** Creates repeatable local tables for the qbit metadata exposed by core. */
|
||||
final class DemoQBitData
|
||||
{
|
||||
/** These tables have hand-maintained PostgreSQL DDL in infra/postgres/01 and 02. */
|
||||
private static final Set<String> POSTGRES_MANAGED_TABLES = Set.of("warehouse_customer", "user_session",
|
||||
"redirect_state", "user", "role", "permission", "role_permission_int", "user_role_int",
|
||||
"user_permission_int");
|
||||
|
||||
private DemoQBitData()
|
||||
{
|
||||
}
|
||||
|
||||
static void ensureSchema(Path dataDirectory, QInstance instance, Integer port) throws SQLException
|
||||
{
|
||||
try(Connection connection = DriverManager.getConnection(
|
||||
"jdbc:h2:file:" + CoreData.h2DatabaseName(dataDirectory) + ";MODE=MySQL;DB_CLOSE_DELAY=-1", "sa", "");
|
||||
Statement statement = connection.createStatement())
|
||||
{
|
||||
for(QTableMetaData table : instance.getTables().values())
|
||||
{
|
||||
if(!"h2".equals(table.getBackendName()) || "customer".equals(table.getName()) || "order".equals(table.getName()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
String tableName = table.getBackendDetails() instanceof RDBMSTableBackendDetails details
|
||||
? details.getTableName() : table.getName();
|
||||
List<String> columns = new ArrayList<>();
|
||||
for(QFieldMetaData field : table.getFields().values())
|
||||
{
|
||||
String name = field.getBackendName() == null ? field.getName() : field.getBackendName();
|
||||
String type = sqlType(field.getType());
|
||||
String identity = field.getName().equals(table.getPrimaryKeyField())
|
||||
&& (field.getType() == QFieldType.INTEGER || field.getType() == QFieldType.LONG)
|
||||
? " GENERATED BY DEFAULT AS IDENTITY" : "";
|
||||
String primaryKey = field.getName().equals(table.getPrimaryKeyField()) ? " PRIMARY KEY" : "";
|
||||
columns.add(identifier(name) + " " + type + identity + primaryKey);
|
||||
}
|
||||
if(!columns.isEmpty())
|
||||
{
|
||||
statement.execute("CREATE TABLE IF NOT EXISTS " + identifier(tableName)
|
||||
+ " (" + String.join(", ", columns) + ")");
|
||||
}
|
||||
}
|
||||
statement.execute("MERGE INTO shipping_country (id, name, alpha2_code) KEY (id) VALUES (1, 'United States', 'US')");
|
||||
statement.execute("MERGE INTO shipping_stateProvince (id, name, country_id) KEY (id) VALUES (1, 'Illinois', 1)");
|
||||
statement.execute("MERGE INTO shipping_city (id, name, state_province_id, latitude, longitude) KEY (id) "
|
||||
+ "VALUES (1, 'Chicago', 1, 41.8781, -87.6298)");
|
||||
statement.execute("MERGE INTO address (id, customer_id, line1, city_id) KEY (id) "
|
||||
+ "VALUES (1, 1, '1 Demo Street', 1)");
|
||||
statement.execute("MERGE INTO customizable_table (id, table_name, is_active, default_table_view_id) KEY (id) "
|
||||
+ "VALUES (1, 'customer', true, 1)");
|
||||
statement.execute("MERGE INTO table_view (id, customizable_table_id, name) KEY (id) "
|
||||
+ "VALUES (1, 1, 'Customer Directory')");
|
||||
statement.execute("MERGE INTO table_view_field (id, table_view_id, field_name, access_level) KEY (id) VALUES "
|
||||
+ "(1, 1, 'customer.id', 'READ_ONLY'), "
|
||||
+ "(2, 1, 'customer.name', 'EDITABLE_OPTIONAL'), "
|
||||
+ "(3, 1, 'customer.email', 'EDITABLE_OPTIONAL')");
|
||||
statement.execute("MERGE INTO workflow (id, name, workflow_type_name, table_name, current_workflow_revision_id) "
|
||||
+ "KEY (id) VALUES (1, 'Order Status Review', 'RecordWorkflow', 'order', 1)");
|
||||
statement.execute("MERGE INTO workflow_revision (id, workflow_id, version_no, start_step_no, commit_message, author) "
|
||||
+ "KEY (id) VALUES (1, 1, 1, 1, 'Demo order review', 'qqq-all')");
|
||||
statement.execute("MERGE INTO workflow_step (id, workflow_revision_id, step_no, workflow_step_type_name, summary, input_values_json) "
|
||||
+ "KEY (id) VALUES (1, 1, 1, 'updateInputRecordField', 'Mark order reviewed', "
|
||||
+ "'{\"fieldName\":\"status\",\"value\":\"REVIEWED\"}')");
|
||||
statement.execute("MERGE INTO webhook (id, name, url, active_status_id, health_status_id) KEY (id) "
|
||||
+ "VALUES (1, 'Local Order Receiver', 'http://127.0.0.1:" + port + "/demo/order-webhook', 1, 1)");
|
||||
statement.execute("MERGE INTO webhook_subscription (id, webhook_id, webhook_event_type_name, "
|
||||
+ "active_status_id, api_name, api_version, create_date) KEY (id) "
|
||||
+ "VALUES (1, 1, 'orderStored', 1, 'none', 'none', CURRENT_TIMESTAMP)");
|
||||
}
|
||||
}
|
||||
|
||||
static void ensurePostgresSchema(QInstance instance) throws SQLException
|
||||
{
|
||||
RDBMSBackendMetaData backend = (RDBMSBackendMetaData) instance.getBackend("postgres");
|
||||
try(Connection connection = DriverManager.getConnection(ConnectionManager.getJdbcUrl(backend),
|
||||
backend.getUsername(), backend.getPassword());
|
||||
Statement statement = connection.createStatement())
|
||||
{
|
||||
for(String sql : postgresSchemaStatements(instance))
|
||||
{
|
||||
statement.execute(sql);
|
||||
}
|
||||
for(QTableMetaData table : postgresQBitTables(instance))
|
||||
{
|
||||
assertPostgresColumns(connection, table);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static List<String> postgresSchemaStatements(QInstance instance)
|
||||
{
|
||||
List<String> statements = new ArrayList<>();
|
||||
for(QTableMetaData table : postgresQBitTables(instance))
|
||||
{
|
||||
String tableName = postgresTableName(table);
|
||||
List<String> columns = new ArrayList<>();
|
||||
for(QFieldMetaData field : table.getFields().values())
|
||||
{
|
||||
String name = field.getBackendName() == null ? field.getName() : field.getBackendName();
|
||||
String identity = field.getName().equals(table.getPrimaryKeyField())
|
||||
&& (field.getType() == QFieldType.INTEGER || field.getType() == QFieldType.LONG)
|
||||
? " GENERATED BY DEFAULT AS IDENTITY" : "";
|
||||
String primaryKey = field.getName().equals(table.getPrimaryKeyField()) ? " PRIMARY KEY" : "";
|
||||
columns.add(postgresIdentifier(name) + " " + postgresSqlType(field.getType()) + identity + primaryKey);
|
||||
}
|
||||
statements.add("CREATE TABLE IF NOT EXISTS " + postgresIdentifier(tableName)
|
||||
+ " (" + String.join(", ", columns) + ")");
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
private static List<QTableMetaData> postgresQBitTables(QInstance instance)
|
||||
{
|
||||
return instance.getTables().values().stream()
|
||||
.filter(table -> "postgres".equals(table.getBackendName()) && !table.getFields().isEmpty())
|
||||
.filter(table -> !POSTGRES_MANAGED_TABLES.contains(postgresTableName(table)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String postgresTableName(QTableMetaData table)
|
||||
{
|
||||
return table.getBackendDetails() instanceof RDBMSTableBackendDetails details
|
||||
? details.getTableName() : table.getName();
|
||||
}
|
||||
|
||||
private static void assertPostgresColumns(Connection connection, QTableMetaData table) throws SQLException
|
||||
{
|
||||
String tableName = postgresTableName(table);
|
||||
Map<String, String> actual = new HashMap<>();
|
||||
try(PreparedStatement query = connection.prepareStatement("SELECT column_name, data_type "
|
||||
+ "FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ?"))
|
||||
{
|
||||
query.setString(1, tableName);
|
||||
try(ResultSet rows = query.executeQuery())
|
||||
{
|
||||
while(rows.next())
|
||||
{
|
||||
actual.put(rows.getString(1), rows.getString(2));
|
||||
}
|
||||
}
|
||||
}
|
||||
for(QFieldMetaData field : table.getFields().values())
|
||||
{
|
||||
String columnName = field.getBackendName() == null ? field.getName() : field.getBackendName();
|
||||
String expectedType = postgresInformationSchemaType(field.getType());
|
||||
String actualType = actual.get(columnName);
|
||||
if(!expectedType.equals(actualType))
|
||||
{
|
||||
throw new SQLException("Full-profile table " + tableName + " column " + columnName
|
||||
+ " must be " + expectedType + "; found " + (actualType == null ? "missing" : actualType)
|
||||
+ ". Recreate the demo volume or migrate the persisted schema.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String postgresInformationSchemaType(QFieldType type)
|
||||
{
|
||||
return switch(type)
|
||||
{
|
||||
case INTEGER -> "integer";
|
||||
case LONG -> "bigint";
|
||||
case DECIMAL -> "numeric";
|
||||
case BOOLEAN -> "boolean";
|
||||
case DATE -> "date";
|
||||
case TIME -> "time without time zone";
|
||||
case DATE_TIME -> "timestamp without time zone";
|
||||
case BLOB -> "bytea";
|
||||
case STRING, PASSWORD -> "character varying";
|
||||
case TEXT, HTML -> "text";
|
||||
};
|
||||
}
|
||||
|
||||
private static String postgresIdentifier(String value)
|
||||
{
|
||||
if(value == null || !value.matches("[A-Za-z][A-Za-z0-9_]*"))
|
||||
{
|
||||
throw new IllegalArgumentException("Unsupported demo schema identifier");
|
||||
}
|
||||
return "\"" + value + "\"";
|
||||
}
|
||||
|
||||
private static String postgresSqlType(QFieldType type)
|
||||
{
|
||||
return switch(type)
|
||||
{
|
||||
case INTEGER -> "INTEGER";
|
||||
case LONG -> "BIGINT";
|
||||
case DECIMAL -> "DECIMAL(20,6)";
|
||||
case BOOLEAN -> "BOOLEAN";
|
||||
case DATE -> "DATE";
|
||||
case TIME -> "TIME";
|
||||
case DATE_TIME -> "TIMESTAMP";
|
||||
case BLOB -> "BYTEA";
|
||||
case STRING, PASSWORD -> "VARCHAR(4000)";
|
||||
case TEXT, HTML -> "TEXT";
|
||||
};
|
||||
}
|
||||
|
||||
private static String identifier(String value)
|
||||
{
|
||||
if(value == null || !value.matches("[A-Za-z][A-Za-z0-9_]*"))
|
||||
{
|
||||
throw new IllegalArgumentException("Unsupported demo schema identifier");
|
||||
}
|
||||
if("value".equalsIgnoreCase(value) || "key".equalsIgnoreCase(value))
|
||||
{
|
||||
return "`" + value + "`";
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static String sqlType(QFieldType type)
|
||||
{
|
||||
return switch(type)
|
||||
{
|
||||
case INTEGER -> "INTEGER";
|
||||
case LONG -> "BIGINT";
|
||||
case DECIMAL -> "DECIMAL(20,6)";
|
||||
case BOOLEAN -> "BOOLEAN";
|
||||
case DATE -> "DATE";
|
||||
case TIME -> "TIME";
|
||||
case DATE_TIME -> "TIMESTAMP";
|
||||
case BLOB -> "BLOB";
|
||||
case STRING, PASSWORD -> "VARCHAR(4000)";
|
||||
case TEXT, HTML -> "CLOB";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.customizabletableviews.CustomizableTableViewsQBitConfig;
|
||||
import com.kingsrook.qbits.customizabletableviews.CustomizableTableViewsQBitProducer;
|
||||
import com.kingsrook.qbits.quicksearch.QuickSearchQBitConfig;
|
||||
import com.kingsrook.qbits.quicksearch.QuickSearchQBitProducer;
|
||||
import com.kingsrook.qbits.quicksearch.SearchableFieldConfig;
|
||||
import com.kingsrook.qbits.sftpdataintegration.SFTPDataIntegrationQBitConfig;
|
||||
import com.kingsrook.qbits.sftpdataintegration.SFTPDataIntegrationQBitProducer;
|
||||
import com.kingsrook.qbits.geodata.GeoDataQBitConfig;
|
||||
import com.kingsrook.qbits.geodata.GeoDataQBitProducer;
|
||||
import com.kingsrook.qbits.standardprocesstrace.StandardProcessTraceQBitConfig;
|
||||
import com.kingsrook.qbits.standardprocesstrace.StandardProcessTraceQBitProducer;
|
||||
import com.kingsrook.qbits.standardprocesstrace.utils.StandardProcessTracer;
|
||||
import com.kingsrook.qbits.webhooks.WebhooksQBitConfig;
|
||||
import com.kingsrook.qbits.webhooks.WebhooksQBitProducer;
|
||||
import com.kingsrook.qbits.webhooks.model.WebhookEventCategory;
|
||||
import com.kingsrook.qbits.webhooks.registry.WebhookEventType;
|
||||
import com.kingsrook.qbits.webhooks.registry.WebhooksRegistry;
|
||||
import com.kingsrook.qbits.workflows.WorkflowsQBitConfig;
|
||||
import com.kingsrook.qbits.workflows.WorkflowsQBitProducer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.instances.QInstanceEnricher;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.producers.MetaDataCustomizerInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.ProvidedOrSuppliedTableConfig;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.QBitMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValue;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSource;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.possiblevalues.QPossibleValueSourceType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.TablesPossibleValueSourceMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.processes.QQQProcessesMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.tables.QQQTablesMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.savedbulkloadprofiles.SavedBulkLoadProfileMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.savedreports.SavedReportsMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.scheduledjobs.ScheduledJobsMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.common.TimeZonePossibleValueSourceMetaDataProvider;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.scheduleing.simple.SimpleSchedulerMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
|
||||
/** Registers the locally usable qbits against the demo's relational backend. */
|
||||
final class DemoQBits
|
||||
{
|
||||
private DemoQBits()
|
||||
{
|
||||
}
|
||||
|
||||
static void addCore(QInstance instance, String backendName) throws QException
|
||||
{
|
||||
new QQQTablesMetaDataProvider().defineAll(instance, backendName, backendName, null);
|
||||
new QQQProcessesMetaDataProvider().defineAll(instance, backendName, backendName, null);
|
||||
instance.addScheduler(new SimpleSchedulerMetaData().withName("demoScheduler"));
|
||||
new ScheduledJobsMetaDataProvider().defineAll(instance, backendName, null);
|
||||
instance.addPossibleValueSource(new TimeZonePossibleValueSourceMetaDataProvider().produce());
|
||||
instance.addPossibleValueSource(TablesPossibleValueSourceMetaDataProvider.defineTablesPossibleValueSource(instance));
|
||||
instance.addPossibleValueSource(new QPossibleValueSource().withName("apiName")
|
||||
.withType(QPossibleValueSourceType.ENUM).withIdType(QFieldType.STRING)
|
||||
.withEnumValues(List.of(new QPossibleValue<>("none", "No API in this demo"))));
|
||||
instance.addPossibleValueSource(new QPossibleValueSource().withName("apiVersion")
|
||||
.withType(QPossibleValueSourceType.ENUM).withIdType(QFieldType.STRING)
|
||||
.withEnumValues(List.of(new QPossibleValue<>("none", "No API version"))));
|
||||
if(instance.getPossibleValueSource("role") == null)
|
||||
{
|
||||
instance.addPossibleValueSource(new QPossibleValueSource().withName("role")
|
||||
.withType(QPossibleValueSourceType.ENUM).withIdType(QFieldType.INTEGER)
|
||||
.withEnumValues(List.of(new QPossibleValue<>(0, "No role"))));
|
||||
}
|
||||
|
||||
MetaDataCustomizerInterface<QTableMetaData> tableCustomizer =
|
||||
(i, table) ->
|
||||
{
|
||||
table.setBackendName(backendName);
|
||||
table.setBackendDetails(new RDBMSTableBackendDetails()
|
||||
.withTableName(QInstanceEnricher.inferBackendName(table.getName())));
|
||||
QInstanceEnricher.setInferredFieldBackendNames(table);
|
||||
return table;
|
||||
};
|
||||
|
||||
new CustomizableTableViewsQBitProducer()
|
||||
.withQBitConfig(new CustomizableTableViewsQBitConfig()
|
||||
.withTableMetaDataCustomizer(tableCustomizer))
|
||||
.produce(instance).addSelfToInstance(instance);
|
||||
CustomizableTableViewsQBitProducer.activateTableMetaDataPersonalizerInterface(instance);
|
||||
|
||||
StandardProcessTraceQBitConfig traceConfig = new StandardProcessTraceQBitConfig()
|
||||
.withTableMetaDataCustomizer(tableCustomizer);
|
||||
StandardProcessTracer.setStandardProcessTraceQBitConfig(traceConfig);
|
||||
new StandardProcessTraceQBitProducer()
|
||||
.withStandardProcessTraceQBitConfig(traceConfig)
|
||||
.produce(instance).addSelfToInstance(instance);
|
||||
instance.getProcess("syncOrder").setProcessTracerCodeReference(new QCodeReference(StandardProcessTracer.class));
|
||||
|
||||
new WebhooksQBitProducer()
|
||||
.withQBitConfig(new WebhooksQBitConfig().withDefaultBackendNameForTables(backendName)
|
||||
.withSchedulerName("demoScheduler")
|
||||
.withTableMetaDataCustomizer(tableCustomizer))
|
||||
.produce(instance).addSelfToInstance(instance);
|
||||
WebhooksRegistry.ofOrWithNew(instance).registerWebhookEventType(new WebhookEventType()
|
||||
.withName("orderStored").withLabel("Order Stored")
|
||||
.withCategory(WebhookEventCategory.STORE).withTableName("order")
|
||||
.withCustomizer(new QCodeReference(DemoOrderWebhookContent.class)));
|
||||
|
||||
new WorkflowsQBitProducer()
|
||||
.withQBitConfig(new WorkflowsQBitConfig().withTableMetaDataCustomizer(tableCustomizer))
|
||||
.produce(instance).addSelfToInstance(instance);
|
||||
|
||||
new GeoDataQBitProducer()
|
||||
.withConfig(new GeoDataQBitConfig().withBackendName(backendName).withTableNamePrefix("shipping"))
|
||||
.produce(instance, "shipping-geo");
|
||||
instance.addTable(new QTableMetaData().withName("shipping_country").withLabel("Country")
|
||||
.withBackendName(backendName).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("alpha2Code", QFieldType.STRING).withBackendName("alpha2_code")));
|
||||
instance.addTable(new QTableMetaData().withName("shipping_stateProvince").withLabel("State Province")
|
||||
.withBackendName(backendName).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("countryId", QFieldType.INTEGER).withBackendName("country_id")
|
||||
.withPossibleValueSourceName("shipping_country")));
|
||||
instance.addTable(new QTableMetaData().withName("shipping_city").withLabel("City")
|
||||
.withBackendName(backendName).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("stateProvinceId", QFieldType.INTEGER).withBackendName("state_province_id")
|
||||
.withPossibleValueSourceName("shipping_stateProvince"))
|
||||
.withField(new QFieldMetaData("latitude", QFieldType.DECIMAL))
|
||||
.withField(new QFieldMetaData("longitude", QFieldType.DECIMAL)));
|
||||
instance.addTable(new QTableMetaData().withName("address").withLabel("Address")
|
||||
.withBackendName(backendName).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("customerId", QFieldType.INTEGER).withBackendName("customer_id"))
|
||||
.withField(new QFieldMetaData("line1", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("cityId", QFieldType.INTEGER).withBackendName("city_id")
|
||||
.withPossibleValueSourceName("shipping_city")));
|
||||
}
|
||||
|
||||
static void addFull(QInstance instance, FullProfileSettings settings) throws QException
|
||||
{
|
||||
QuickSearchQBitConfig searchConfig = new QuickSearchQBitConfig()
|
||||
.withBackendName("postgres")
|
||||
.withOpensearchHost(settings.get("OPENSEARCH_HOST"))
|
||||
.withOpensearchPort(settings.port("OPENSEARCH_PORT", "9200"))
|
||||
.withOpensearchIndexName(settings.getOrDefault("OPENSEARCH_INDEX", "qqq-all-customers"))
|
||||
.withOpensearchUsername(settings.get("OPENSEARCH_USER"))
|
||||
.withOpensearchPassword(settings.get("OPENSEARCH_PASSWORD"))
|
||||
.withUseSsl(Boolean.parseBoolean(settings.getOrDefault("OPENSEARCH_SSL", "false")))
|
||||
.withSearchableTable("customer", List.of(new SearchableFieldConfig("name"),
|
||||
new SearchableFieldConfig("email")));
|
||||
new QuickSearchQBitProducer().withConfig(searchConfig).produce(instance);
|
||||
instance.addQBit(new QBitMetaData().withGroupId("com.kingsrook.qbits")
|
||||
.withArtifactId("quick-search").withVersion("0.2.1-SNAPSHOT").withConfig(searchConfig));
|
||||
|
||||
new SavedBulkLoadProfileMetaDataProvider().defineAll(instance, "postgres", null);
|
||||
new SavedReportsMetaDataProvider().defineAll(instance, "postgres", "sftp", null);
|
||||
new SFTPDataIntegrationQBitProducer().withSftpDataIntegrationQBitConfig(new SFTPDataIntegrationQBitConfig()
|
||||
.withSourceFileTableConfig(ProvidedOrSuppliedTableConfig.provideTableUsingBackendNamed("sftp"))
|
||||
.withDestinationFileTableConfig(ProvidedOrSuppliedTableConfig.provideTableUsingBackendNamed("sftp"))
|
||||
.withStagingFileTableConfig(ProvidedOrSuppliedTableConfig.provideTableUsingBackendNamed("files"))
|
||||
.withSchedulerName("demoScheduler")
|
||||
.withTableMetaDataCustomizer((i, table) ->
|
||||
{
|
||||
if(table.getBackendName() == null)
|
||||
{
|
||||
table.setBackendName("postgres");
|
||||
table.setBackendDetails(new RDBMSTableBackendDetails()
|
||||
.withTableName(QInstanceEnricher.inferBackendName(table.getName())));
|
||||
QInstanceEnricher.setInferredFieldBackendNames(table);
|
||||
}
|
||||
return table;
|
||||
})).produce(instance, "demo-import");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFunctionInputMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QFunctionOutputMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.Capability;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import com.kingsrook.qqq.backend.module.api.model.AuthorizationType;
|
||||
import com.kingsrook.qqq.backend.module.api.model.metadata.APIBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.api.model.metadata.APITableBackendDetails;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
|
||||
|
||||
/** Shared, local-only demonstrations included in both profiles. */
|
||||
final class DemoRuntimeFeatures
|
||||
{
|
||||
private DemoRuntimeFeatures()
|
||||
{
|
||||
}
|
||||
|
||||
static void add(QInstance instance, int port, String bindHost) throws QException
|
||||
{
|
||||
instance.addBackend(new APIBackendMetaData().withName("demoApi")
|
||||
.withBaseUrl(catalogBaseUrl(bindHost, port))
|
||||
.withAuthorizationType(AuthorizationType.NONE).withContentType("application/json")
|
||||
.withActionUtil(new QCodeReference(DemoCatalogApi.class)));
|
||||
instance.addTable(new QTableMetaData().withName("apiCatalog").withLabel("API Catalog")
|
||||
.withBackendName("demoApi").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new APITableBackendDetails().withTablePath("/catalog"))
|
||||
.withCapabilities(Capability.TABLE_QUERY, Capability.TABLE_GET, Capability.TABLE_COUNT)
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("unitPriceCents", QFieldType.INTEGER)));
|
||||
instance.addBackend(new QBackendMetaData().withName("transientMemory").withBackendType(MemoryBackendModule.class));
|
||||
instance.addTable(new QTableMetaData().withName("demoNote").withLabel("Demo Note (Transient)")
|
||||
.withBackendName("transientMemory").withPrimaryKeyField("id")
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("text", QFieldType.STRING)));
|
||||
instance.withRuntimeService(new QCodeReference(TransientNotesService.class));
|
||||
instance.addProcess(new QProcessMetaData().withName("calculateOrderTotal").withLabel("Calculate Order Total (JavaScript)")
|
||||
.withPermissionRules(new QPermissionRules().withLevel(PermissionLevel.HAS_ACCESS_PERMISSION))
|
||||
.withStep(new QBackendStepMetaData().withName("calculate")
|
||||
.withCode(new QCodeReference(CalculateOrderTotalStep.class))
|
||||
.withInputData(new QFunctionInputMetaData().withFieldList(List.of(
|
||||
new QFieldMetaData("quantity", QFieldType.INTEGER),
|
||||
new QFieldMetaData("unitPriceCents", QFieldType.INTEGER))))
|
||||
.withOutputMetaData(new QFunctionOutputMetaData().withFieldList(List.of(
|
||||
new QFieldMetaData("totalCents", QFieldType.INTEGER))))));
|
||||
QJavalinMetaData.ofOrWithNew(instance).withAdditionalRouteProviderReference(new QCodeReference(DemoCatalogRoutes.class));
|
||||
}
|
||||
|
||||
private static String catalogBaseUrl(String bindHost, int port) throws QException
|
||||
{
|
||||
try
|
||||
{
|
||||
InetAddress address = InetAddress.getByName(bindHost);
|
||||
String host = address.isAnyLocalAddress()
|
||||
? (address instanceof Inet6Address ? "::1" : "127.0.0.1") : bindHost;
|
||||
return new URI("http", null, host, port, "/demo", null, null).toASCIIString();
|
||||
}
|
||||
catch(UnknownHostException | URISyntaxException e)
|
||||
{
|
||||
throw new QException("Could not derive demo catalog URL from HTTP bind host", e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.QPermissionRules;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleCustomizerInterface;
|
||||
|
||||
/** Fixed identities for local mock authentication; the session cookie selects one. */
|
||||
public class DemoUsers implements QAuthenticationModuleCustomizerInterface
|
||||
{
|
||||
public static final String ADMIN_SESSION = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
public static final String DEMO_SESSION = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
|
||||
private static final List<String> DEMO_TABLES = List.of("customer", "order", "orderLine", "product", "address");
|
||||
private static final List<String> WEBHOOK_TABLES = List.of("webhook", "webhookSubscription",
|
||||
"webhookEvent", "webhookEventContent", "webhookEventSendLog", "scheduledJob", "scheduledJobParameter");
|
||||
private static final List<String> WEBHOOK_PROCESSES = List.of("SendWebhookEvent",
|
||||
"SendTestEventToWebhook", "ManageWebhookHealth");
|
||||
|
||||
static void protectDemoTables(QInstance instance)
|
||||
{
|
||||
for(String tableName : DEMO_TABLES)
|
||||
{
|
||||
instance.getTable(tableName).setPermissionRules(new QPermissionRules()
|
||||
.withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS));
|
||||
}
|
||||
protectWebhookResources(instance);
|
||||
}
|
||||
|
||||
static void protectWebhookResources(QInstance instance)
|
||||
{
|
||||
for(String tableName : WEBHOOK_TABLES)
|
||||
{
|
||||
instance.getTable(tableName).setPermissionRules(new QPermissionRules()
|
||||
.withLevel(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS));
|
||||
}
|
||||
for(String processName : WEBHOOK_PROCESSES)
|
||||
{
|
||||
instance.getProcess(processName).setPermissionRules(new QPermissionRules()
|
||||
.withLevel(PermissionLevel.HAS_ACCESS_PERMISSION));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customizeSession(QInstance instance, QSession session, Map<String, Object> context)
|
||||
{
|
||||
session.withPermissions("apiCatalog.read", "demoNote.read");
|
||||
Boolean admin = ADMIN_SESSION.equals(session.getUuid());
|
||||
String name = admin ? "Admin" : "Demo User";
|
||||
String userId = admin ? "core:admin" : "core:demo";
|
||||
session.getUser().setIdReference(userId);
|
||||
session.getUser().setFullName(name);
|
||||
for(String tableName : DEMO_TABLES)
|
||||
{
|
||||
session.withPermission(tableName + ".read");
|
||||
if(admin)
|
||||
{
|
||||
session.withPermissions(tableName + ".insert", tableName + ".edit", tableName + ".delete");
|
||||
}
|
||||
}
|
||||
for(String tableName : WEBHOOK_TABLES)
|
||||
{
|
||||
session.withPermission(tableName + ".read");
|
||||
if(admin)
|
||||
{
|
||||
session.withPermissions(tableName + ".insert", tableName + ".edit", tableName + ".delete");
|
||||
}
|
||||
}
|
||||
if(admin)
|
||||
{
|
||||
session.withPermissions("calculateOrderTotal.hasAccess", "demoNote.insert", "demoNote.edit", "demoNote.delete");
|
||||
session.withPermissions("esbView.hasAccess", "esbOperate.hasAccess", "esbDelete.hasAccess");
|
||||
for(String processName : WEBHOOK_PROCESSES)
|
||||
{
|
||||
session.withPermission(processName + ".hasAccess");
|
||||
}
|
||||
}
|
||||
session.withValueForFrontend("user", new LinkedHashMap<>(Map.of("name", name, "email", userId + "@example.test")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import com.kingsrook.qbits.userrolepermissions.model.Role;
|
||||
import com.kingsrook.qbits.userrolepermissions.utils.PermissionManager;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.QAuthenticationModuleCustomizerInterface;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
|
||||
/** Resolves Keycloak realm roles through qbit-user-role-permissions. */
|
||||
public class FullOidcSessionCustomizer implements QAuthenticationModuleCustomizerInterface
|
||||
{
|
||||
@Override
|
||||
public void customizeSession(QInstance instance, QSession session, Map<String, Object> context)
|
||||
{
|
||||
Set<String> roles = realmRoles(context.get("idToken") instanceof JSONObject idToken ? idToken : null);
|
||||
if(roles.isEmpty() && context.get("jwtPayloadJsonObject") instanceof JSONObject accessToken)
|
||||
{
|
||||
roles = realmRoles(accessToken);
|
||||
}
|
||||
try
|
||||
{
|
||||
session.setPermissions(permissionsForRoles(roles));
|
||||
}
|
||||
catch(QException e)
|
||||
{
|
||||
throw new IllegalStateException("Could not resolve OIDC role permissions", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static Set<String> realmRoles(JSONObject claims)
|
||||
{
|
||||
if(claims == null)
|
||||
{
|
||||
return Set.of();
|
||||
}
|
||||
JSONObject realmAccess = claims.optJSONObject("realm_access");
|
||||
JSONArray values = realmAccess == null ? null : realmAccess.optJSONArray("roles");
|
||||
if(values == null)
|
||||
{
|
||||
return Set.of();
|
||||
}
|
||||
Set<String> roles = new HashSet<>();
|
||||
for(Integer i = 0; i < values.length(); i++)
|
||||
{
|
||||
if(values.opt(i) instanceof String role && !role.isBlank())
|
||||
{
|
||||
roles.add(role);
|
||||
}
|
||||
}
|
||||
return roles;
|
||||
}
|
||||
|
||||
protected Set<String> permissionsForRoles(Set<String> roles) throws QException
|
||||
{
|
||||
if(roles.isEmpty())
|
||||
{
|
||||
return Set.of();
|
||||
}
|
||||
QSession previousSession = QContext.getQSession();
|
||||
try
|
||||
{
|
||||
QContext.setQSession(new QSystemUserSession());
|
||||
Set<Integer> roleIds = new QueryAction().execute(new QueryInput(Role.TABLE_NAME)
|
||||
.withFilter(new QQueryFilter().withCriteria("name", QCriteriaOperator.IN, roles)))
|
||||
.getRecords().stream().map(record -> record.getValueInteger("id")).collect(Collectors.toSet());
|
||||
return PermissionManager.getInstance().getEffectivePermissionsForRoles(roleIds);
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.setQSession(previousSession);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qbits.userrolepermissions.UserRolePermissionsQBitConfig;
|
||||
import com.kingsrook.qbits.userrolepermissions.UserRolePermissionsQBitProducer;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.instances.AbstractQQQApplication;
|
||||
import com.kingsrook.qqq.backend.core.instances.QInstanceEnricher;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.AuthScope;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.OAuth2AuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.messaging.email.EmailMessagingProviderMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.qbits.ProvidedOrSuppliedTableConfig;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.implementations.metadata.RedirectStateMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.implementations.metadata.UserSessionMetaDataProducer;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.implementations.model.UserSession;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.base.model.metadata.Cardinality;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.base.model.metadata.RecordFormat;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.model.metadata.S3TableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.sftp.model.metadata.SFTPBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.sftp.model.metadata.SFTPTableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.module.mongodb.model.metadata.MongoDBBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.mongodb.model.metadata.MongoDBTableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.postgres.model.metadata.PostgreSQLBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
import com.kingsrook.qqq.esb.model.EsbDestinationType;
|
||||
import com.kingsrook.qqq.esb.model.EsbInstanceMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbProcessEvent;
|
||||
import com.kingsrook.qqq.esb.model.EsbProcessMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbProcessPublication;
|
||||
import com.kingsrook.qqq.esb.model.EsbProviderType;
|
||||
import com.kingsrook.qqq.esb.model.QEsbDestinationMetaData;
|
||||
import com.kingsrook.qqq.esb.model.QEsbProviderMetaData;
|
||||
|
||||
/** Extends the core demo with external services selected by the full profile. */
|
||||
final class FullProfileApplication extends AbstractQQQApplication
|
||||
{
|
||||
private final Path dataDirectory;
|
||||
private final FullProfileSettings settings;
|
||||
private final boolean provisionSchema;
|
||||
|
||||
FullProfileApplication(Path dataDirectory, FullProfileSettings settings)
|
||||
{
|
||||
this(dataDirectory, settings, false);
|
||||
}
|
||||
|
||||
FullProfileApplication(Path dataDirectory, FullProfileSettings settings, boolean provisionSchema)
|
||||
{
|
||||
this.dataDirectory = dataDirectory;
|
||||
this.settings = settings;
|
||||
this.provisionSchema = provisionSchema;
|
||||
}
|
||||
|
||||
@Override
|
||||
public QInstance defineQInstance() throws QException
|
||||
{
|
||||
QInstance instance = new QqqAllApplication(dataDirectory, settings.get("ARTEMIS_URL"), false, settings.port("PORT", "8080"), settings.get("BIND_HOST")).defineQInstance();
|
||||
addBackends(instance);
|
||||
addTables(instance);
|
||||
addAuthentication(instance);
|
||||
addEsb(instance);
|
||||
DemoQBits.addCore(instance, "postgres");
|
||||
DemoQBits.addFull(instance, settings);
|
||||
// OIDC and ESB sessions use string user IDs, unlike the qbit's default integer user ID.
|
||||
instance.getTable("processTrace").getField("userId").setType(QFieldType.STRING);
|
||||
DemoUsers.protectWebhookResources(instance);
|
||||
for(QTableMetaData table : instance.getTables().values())
|
||||
{
|
||||
if(!"postgres".equals(table.getBackendName()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if(table.getBackendDetails() == null)
|
||||
{
|
||||
table.setBackendDetails(new RDBMSTableBackendDetails()
|
||||
.withTableName(QInstanceEnricher.inferBackendName(table.getName())));
|
||||
}
|
||||
QInstanceEnricher.setInferredFieldBackendNames(table);
|
||||
}
|
||||
|
||||
EmailMessagingProviderMetaData mail = new EmailMessagingProviderMetaData()
|
||||
.withSmtpServer(settings.get("SMTP_HOST"))
|
||||
.withSmtpPort(settings.getOrDefault("SMTP_PORT", "1025"));
|
||||
mail.setName("mailpit");
|
||||
instance.addMessagingProvider(mail);
|
||||
if(provisionSchema)
|
||||
{
|
||||
try
|
||||
{
|
||||
DemoQBitData.ensurePostgresSchema(instance);
|
||||
}
|
||||
catch(SQLException e)
|
||||
{
|
||||
throw new QException("Could not provision full-profile qbit tables", e);
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void addBackends(QInstance instance)
|
||||
{
|
||||
instance.addBackend(new PostgreSQLBackendMetaData().withName("postgres")
|
||||
.withHostName(settings.get("POSTGRES_HOST")).withPort(settings.port("POSTGRES_PORT", "5432"))
|
||||
.withDatabaseName(settings.get("POSTGRES_DATABASE"))
|
||||
.withUsername(settings.get("POSTGRES_USER")).withPassword(settings.get("POSTGRES_PASSWORD")));
|
||||
instance.addBackend(new RDBMSBackendMetaData().withName("mysql").withVendor("mysql")
|
||||
.withHostName(settings.get("MYSQL_HOST")).withPort(settings.port("MYSQL_PORT", "3306"))
|
||||
.withDatabaseName(settings.get("MYSQL_DATABASE"))
|
||||
.withUsername(settings.get("MYSQL_USER")).withPassword(settings.get("MYSQL_PASSWORD")));
|
||||
instance.addBackend(new MongoDBBackendMetaData().withName("mongo")
|
||||
.withHost(settings.get("MONGO_HOST")).withPort(settings.port("MONGO_PORT", "27017"))
|
||||
.withDatabaseName(settings.get("MONGO_DATABASE"))
|
||||
.withUsername(settings.get("MONGO_USER")).withPassword(settings.get("MONGO_PASSWORD"))
|
||||
.withAuthSourceDatabase(settings.getOrDefault("MONGO_AUTH_DATABASE", "admin"))
|
||||
.withUrlSuffix("replicaSet=" + settings.get("MONGO_REPLICA_SET"))
|
||||
.withTransactionsSupported(true));
|
||||
instance.addBackend(new MinioBackendMetaData(settings.get("S3_ENDPOINT")).withName("s3")
|
||||
.withBucketName(settings.get("S3_BUCKET"))
|
||||
.withAccessKey(settings.get("S3_ACCESS_KEY")).withSecretKey(settings.get("S3_SECRET_KEY"))
|
||||
.withRegion(settings.getOrDefault("S3_REGION", "us-east-1")));
|
||||
instance.addBackend(new SFTPBackendMetaData().withName("sftp")
|
||||
.withHostName(settings.get("SFTP_HOST")).withPort(settings.port("SFTP_PORT", "22"))
|
||||
.withUsername(settings.get("SFTP_USER")).withPassword(settings.get("SFTP_PASSWORD"))
|
||||
.withBasePath(settings.getOrDefault("SFTP_BASE_PATH", "/upload")));
|
||||
}
|
||||
|
||||
private void addTables(QInstance instance)
|
||||
{
|
||||
instance.addTable(new QTableMetaData().withName("warehouseCustomer").withLabel("Warehouse Customer")
|
||||
.withBackendName("postgres").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new RDBMSTableBackendDetails().withTableName("warehouse_customer"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING)));
|
||||
instance.addTable(new QTableMetaData().withName("supplierOrder").withLabel("Supplier Order")
|
||||
.withBackendName("mysql").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new RDBMSTableBackendDetails().withTableName("supplier_order"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("reference", QFieldType.STRING)));
|
||||
instance.addTable(new QTableMetaData().withName("shipment").withLabel("Shipment")
|
||||
.withBackendName("mongo").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new MongoDBTableBackendDetails().withTableName("shipment"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.STRING).withBackendName("_id"))
|
||||
.withField(new QFieldMetaData("tracking", QFieldType.STRING)));
|
||||
instance.addTable(new QTableMetaData().withName("document").withLabel("Document")
|
||||
.withBackendName("s3").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new S3TableBackendDetails().withBasePath("documents")
|
||||
.withRecordFormat(RecordFormat.JSON).withCardinality(Cardinality.MANY).withGlob("*.json"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING)));
|
||||
instance.addTable(new QTableMetaData().withName("externalImportFile").withLabel("External Import File")
|
||||
.withBackendName("sftp").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new SFTPTableBackendDetails().withBasePath("imports")
|
||||
.withRecordFormat(RecordFormat.JSON).withCardinality(Cardinality.MANY).withGlob("*.json"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING)));
|
||||
}
|
||||
|
||||
private void addAuthentication(QInstance instance) throws QException
|
||||
{
|
||||
instance.addTable(new UserSessionMetaDataProducer("postgres").produce(instance));
|
||||
instance.addTable(new RedirectStateMetaDataProducer("postgres").produce(instance));
|
||||
|
||||
UserRolePermissionsQBitConfig qbitConfig = new UserRolePermissionsQBitConfig()
|
||||
.withUserTableConfig(ProvidedOrSuppliedTableConfig.provideTableUsingBackendNamed("postgres"))
|
||||
.withTableMetaDataCustomizer((i, table) ->
|
||||
{
|
||||
table.setBackendName("postgres");
|
||||
table.setBackendDetails(new RDBMSTableBackendDetails()
|
||||
.withTableName(QInstanceEnricher.inferBackendName(table.getName())));
|
||||
QInstanceEnricher.setInferredFieldBackendNames(table);
|
||||
return table;
|
||||
});
|
||||
new UserRolePermissionsQBitProducer().withUserRolePermissionsQBitConfig(qbitConfig).produce(instance);
|
||||
|
||||
instance.registerAuthenticationProvider(AuthScope.instanceDefault(), new OAuth2AuthenticationMetaData()
|
||||
.withBaseUrl(settings.get("OIDC_BASE_URL"))
|
||||
.withExternalBaseUrl(settings.getOrDefault("OIDC_EXTERNAL_BASE_URL", settings.get("OIDC_BASE_URL")))
|
||||
.withClientId(settings.get("OIDC_CLIENT_ID"))
|
||||
.withClientSecret(settings.get("OIDC_CLIENT_SECRET"))
|
||||
.withScopes(settings.getOrDefault("OIDC_SCOPES", "openid email profile"))
|
||||
.withUserSessionTableName(UserSession.TABLE_NAME)
|
||||
.withRedirectStateTableName(RedirectStateMetaDataProducer.TABLE_NAME)
|
||||
.withCustomizer(new QCodeReference(FullOidcSessionCustomizer.class))
|
||||
.withName("keycloak"));
|
||||
}
|
||||
|
||||
private void addEsb(QInstance instance)
|
||||
{
|
||||
EsbInstanceMetaData.of(instance)
|
||||
.getProvider("artemis")
|
||||
.withUsername(settings.get("ARTEMIS_USER"))
|
||||
.withPassword(settings.get("ARTEMIS_PASSWORD"))
|
||||
.withManagementUrl(settings.get("ARTEMIS_MANAGEMENT_URL"))
|
||||
.withManagementUsername(settings.get("ARTEMIS_USER"))
|
||||
.withManagementPassword(settings.get("ARTEMIS_PASSWORD"));
|
||||
EsbInstanceMetaData.of(instance)
|
||||
.withProvider(new QEsbProviderMetaData().withName("rabbitmq")
|
||||
.withType(EsbProviderType.RABBITMQ).withUrl(settings.get("RABBITMQ_URL"))
|
||||
.withUsername(settings.get("RABBITMQ_USER")).withPassword(settings.get("RABBITMQ_PASSWORD"))
|
||||
.withManagementUrl(settings.get("RABBITMQ_MANAGEMENT_URL"))
|
||||
.withManagementUsername(settings.get("RABBITMQ_USER"))
|
||||
.withManagementPassword(settings.get("RABBITMQ_PASSWORD")))
|
||||
.withDestination(new QEsbDestinationMetaData().withName("orderSyncEvents")
|
||||
.withType(EsbDestinationType.QUEUE).withProviderName("rabbitmq")
|
||||
.withDestinationName("qqq.all.orderSyncEvents"));
|
||||
EsbProcessMetaData.ofOrWithNew(instance.getProcess("syncOrder"))
|
||||
.withPublication(new EsbProcessPublication().withDestinationName("orderSyncEvents")
|
||||
.withEvents(List.of(EsbProcessEvent.COMPLETED)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Validated environment settings for the external services in the full profile. */
|
||||
final class FullProfileSettings
|
||||
{
|
||||
private static final List<String> REQUIRED = List.of(
|
||||
"BIND_HOST",
|
||||
"POSTGRES_HOST", "POSTGRES_DATABASE", "POSTGRES_USER", "POSTGRES_PASSWORD",
|
||||
"MYSQL_HOST", "MYSQL_DATABASE", "MYSQL_USER", "MYSQL_PASSWORD",
|
||||
"MONGO_HOST", "MONGO_DATABASE", "MONGO_USER", "MONGO_PASSWORD", "MONGO_REPLICA_SET",
|
||||
"S3_ENDPOINT", "S3_BUCKET", "S3_ACCESS_KEY", "S3_SECRET_KEY",
|
||||
"SFTP_HOST", "SFTP_USER", "SFTP_PASSWORD",
|
||||
"ARTEMIS_URL", "ARTEMIS_USER", "ARTEMIS_PASSWORD", "ARTEMIS_MANAGEMENT_URL",
|
||||
"RABBITMQ_URL", "RABBITMQ_USER", "RABBITMQ_PASSWORD", "RABBITMQ_MANAGEMENT_URL",
|
||||
"SMTP_HOST", "OIDC_BASE_URL", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET",
|
||||
"OPENSEARCH_HOST");
|
||||
|
||||
private final Map<String, String> values;
|
||||
|
||||
private FullProfileSettings(Map<String, String> values)
|
||||
{
|
||||
this.values = Map.copyOf(values);
|
||||
}
|
||||
|
||||
static FullProfileSettings from(Map<String, String> environment)
|
||||
{
|
||||
for(String name : REQUIRED)
|
||||
{
|
||||
if(environment.get("QQQ_ALL_" + name) == null || environment.get("QQQ_ALL_" + name).isBlank())
|
||||
{
|
||||
throw new IllegalArgumentException("Missing required environment variable QQQ_ALL_" + name);
|
||||
}
|
||||
}
|
||||
return new FullProfileSettings(environment);
|
||||
}
|
||||
|
||||
String get(String name)
|
||||
{
|
||||
return values.get("QQQ_ALL_" + name);
|
||||
}
|
||||
|
||||
String getOrDefault(String name, String defaultValue)
|
||||
{
|
||||
String value = get(name);
|
||||
return value == null || value.isBlank() ? defaultValue : value;
|
||||
}
|
||||
|
||||
Integer port(String name, String defaultValue)
|
||||
{
|
||||
Integer port = Integer.valueOf(getOrDefault(name, defaultValue));
|
||||
if(port < 1 || port > 65535)
|
||||
{
|
||||
throw new IllegalArgumentException("Invalid port in QQQ_ALL_" + name);
|
||||
}
|
||||
return port;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.model.metadata.S3BackendMetaData;
|
||||
|
||||
/** S3 metadata with an explicit endpoint for MinIO. */
|
||||
public final class MinioBackendMetaData extends S3BackendMetaData
|
||||
{
|
||||
private final String endpoint;
|
||||
|
||||
public MinioBackendMetaData(String endpoint)
|
||||
{
|
||||
this.endpoint = endpoint;
|
||||
setBackendType(MinioBackendModule.class);
|
||||
}
|
||||
|
||||
public String getEndpoint()
|
||||
{
|
||||
return endpoint;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import com.amazonaws.auth.AWSStaticCredentialsProvider;
|
||||
import com.amazonaws.auth.BasicAWSCredentials;
|
||||
import com.amazonaws.client.builder.AwsClientBuilder;
|
||||
import com.amazonaws.services.s3.AmazonS3;
|
||||
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
|
||||
import com.amazonaws.services.s3.model.S3ObjectSummary;
|
||||
import com.kingsrook.qqq.backend.core.actions.interfaces.CountInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.interfaces.DeleteInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.interfaces.InsertInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.interfaces.QStorageInterface;
|
||||
import com.kingsrook.qqq.backend.core.actions.interfaces.QueryInterface;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleDispatcher;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.base.actions.AbstractBaseFilesystemAction;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.S3BackendModule;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.AbstractS3Action;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.S3CountAction;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.S3DeleteAction;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.S3InsertAction;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.S3QueryAction;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.S3StorageAction;
|
||||
|
||||
/** Routes every S3 operation to the configured MinIO endpoint. */
|
||||
public final class MinioBackendModule extends S3BackendModule
|
||||
{
|
||||
static
|
||||
{
|
||||
QBackendModuleDispatcher.registerBackendModule(new MinioBackendModule());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getBackendType()
|
||||
{
|
||||
return "minio";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Class<? extends QBackendMetaData> getBackendMetaDataClass()
|
||||
{
|
||||
return MinioBackendMetaData.class;
|
||||
}
|
||||
|
||||
private static AmazonS3 client(QBackendMetaData metadata)
|
||||
{
|
||||
MinioBackendMetaData minio = (MinioBackendMetaData) metadata;
|
||||
return AmazonS3ClientBuilder.standard()
|
||||
.withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(minio.getEndpoint(), minio.getRegion()))
|
||||
.withPathStyleAccessEnabled(true)
|
||||
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(minio.getAccessKey(), minio.getSecretKey())))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public AbstractBaseFilesystemAction<S3ObjectSummary> getActionBase()
|
||||
{
|
||||
return new AbstractS3Action()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public QueryInterface getQueryInterface()
|
||||
{
|
||||
return new S3QueryAction()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public InsertInterface getInsertInterface()
|
||||
{
|
||||
return new S3InsertAction()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public CountInterface getCountInterface()
|
||||
{
|
||||
return new S3CountAction()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeleteInterface getDeleteInterface()
|
||||
{
|
||||
return new S3DeleteAction()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public QStorageInterface getStorageInterface()
|
||||
{
|
||||
return new S3StorageAction()
|
||||
{
|
||||
@Override
|
||||
protected AmazonS3 buildAmazonS3ClientFromBackendMetaData(QBackendMetaData metadata)
|
||||
{
|
||||
return client(metadata);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationLauncher;
|
||||
import com.kingsrook.qqq.middleware.javalin.QApplicationLauncherConfig;
|
||||
|
||||
/** Selects the standalone or externally backed reference application. */
|
||||
public final class ProfileLauncher
|
||||
{
|
||||
private ProfileLauncher()
|
||||
{
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
launch(System.getenv());
|
||||
}
|
||||
|
||||
static String profile(Map<String, String> environment)
|
||||
{
|
||||
String selected = environment.getOrDefault("QQQ_ALL_PROFILE", "core");
|
||||
if(!"core".equals(selected) && !"full".equals(selected))
|
||||
{
|
||||
throw new IllegalArgumentException("QQQ_ALL_PROFILE must be core or full");
|
||||
}
|
||||
return selected;
|
||||
}
|
||||
|
||||
static void launch(Map<String, String> environment) throws Exception
|
||||
{
|
||||
String selected = profile(environment);
|
||||
Path dataDirectory = Path.of(environment.getOrDefault("QQQ_ALL_DATA_DIR", "./data"));
|
||||
Integer port = Integer.valueOf(environment.getOrDefault("QQQ_ALL_PORT", "8080"));
|
||||
if("core".equals(selected))
|
||||
{
|
||||
CoreRuntime.launch(dataDirectory, port, environment.getOrDefault("QQQ_ALL_BIND_HOST", "127.0.0.1"));
|
||||
return;
|
||||
}
|
||||
|
||||
FullProfileSettings settings = FullProfileSettings.from(environment);
|
||||
CoreData.seed(dataDirectory);
|
||||
QApplicationLauncher.run(new FullProfileApplication(dataDirectory, settings, true),
|
||||
new QApplicationLauncherConfig().withRegisterShutdownHook(true)
|
||||
.withServerCustomizer(server -> server.withPort(port)
|
||||
.withJavalinConfigCustomizer(config -> config.jetty.host = settings.get("BIND_HOST"))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.BackendStep;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.instances.AbstractQQQApplication;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.MetaDataProducerHelper;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.AuthScope;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.code.QCodeReference;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QBackendStepMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.processes.QProcessMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.processes.tracing.ProcessTracerKeyRecordMessage;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.base.model.metadata.Cardinality;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.base.model.metadata.RecordFormat;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.local.model.metadata.FilesystemBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.local.model.metadata.FilesystemTableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.module.sqlite.model.metadata.SQLiteBackendMetaData;
|
||||
import com.kingsrook.qqq.esb.envelope.EsbEvent;
|
||||
import com.kingsrook.qqq.esb.api.EsbJavalinMetaDataProducer;
|
||||
import com.kingsrook.qqq.esb.metadata.EsbAppMetaDataProducer;
|
||||
import com.kingsrook.qqq.esb.model.EsbDestinationType;
|
||||
import com.kingsrook.qqq.esb.model.EsbInstanceMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbProcessMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbProviderType;
|
||||
import com.kingsrook.qqq.esb.model.EsbTableEvent;
|
||||
import com.kingsrook.qqq.esb.model.EsbTableMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbTablePublication;
|
||||
import com.kingsrook.qqq.esb.model.EsbTrigger;
|
||||
import com.kingsrook.qqq.esb.model.QEsbDestinationMetaData;
|
||||
import com.kingsrook.qqq.esb.model.QEsbProviderMetaData;
|
||||
import com.kingsrook.qqq.esb.runtime.EsbTriggerHandler;
|
||||
import com.kingsrook.qqq.middleware.health.JavalinHealthRouteProvider;
|
||||
import com.kingsrook.qqq.middleware.health.indicators.MemoryHealthIndicator;
|
||||
import com.kingsrook.qqq.middleware.health.model.metadata.HealthCheckMetaData;
|
||||
import com.kingsrook.qqq.middleware.javalin.QJavalinMetaData;
|
||||
|
||||
/** The self-contained core QQQ reference application. */
|
||||
public final class QqqAllApplication extends AbstractQQQApplication
|
||||
{
|
||||
private final Path dataDirectory;
|
||||
private final String brokerUrl;
|
||||
private final boolean includeDemoQbits;
|
||||
private final int httpPort;
|
||||
private final String bindHost;
|
||||
|
||||
public QqqAllApplication(Path dataDirectory, String brokerUrl)
|
||||
{
|
||||
this(dataDirectory, brokerUrl, true);
|
||||
}
|
||||
|
||||
QqqAllApplication(Path dataDirectory, String brokerUrl, boolean includeDemoQbits)
|
||||
{
|
||||
this(dataDirectory, brokerUrl, includeDemoQbits, 8080);
|
||||
}
|
||||
|
||||
QqqAllApplication(Path dataDirectory, String brokerUrl, boolean includeDemoQbits, int httpPort)
|
||||
{
|
||||
this(dataDirectory, brokerUrl, includeDemoQbits, httpPort, "127.0.0.1");
|
||||
}
|
||||
|
||||
QqqAllApplication(Path dataDirectory, String brokerUrl, boolean includeDemoQbits, int httpPort, String bindHost)
|
||||
{
|
||||
this.bindHost = bindHost;
|
||||
this.httpPort = httpPort;
|
||||
this.dataDirectory = dataDirectory;
|
||||
this.brokerUrl = brokerUrl;
|
||||
this.includeDemoQbits = includeDemoQbits;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception
|
||||
{
|
||||
Path dataDirectory = Path.of(System.getenv().getOrDefault("QQQ_ALL_DATA_DIR", "./data"));
|
||||
Integer port = Integer.valueOf(System.getenv().getOrDefault("QQQ_ALL_PORT", "8080"));
|
||||
CoreRuntime.launch(dataDirectory, port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public QInstance defineQInstance() throws QException
|
||||
{
|
||||
QInstance instance = new QInstance().withFailOnMetaDataProducerError(true);
|
||||
instance.registerAuthenticationProvider(AuthScope.instanceDefault(), new QAuthenticationMetaData()
|
||||
.withName("mock").withType(QAuthenticationType.MOCK)
|
||||
.withCustomizer(new QCodeReference(DemoUsers.class)));
|
||||
|
||||
instance.addBackend(new RDBMSBackendMetaData()
|
||||
.withName("h2").withVendor("h2").withHostName("file")
|
||||
.withDatabaseName(CoreData.h2DatabaseName(dataDirectory)).withUsername("sa"));
|
||||
instance.addBackend(new SQLiteBackendMetaData().withName("sqlite")
|
||||
.withPath(CoreData.sqlitePath(dataDirectory).toAbsolutePath().toString()));
|
||||
instance.addBackend(new FilesystemBackendMetaData().withName("files")
|
||||
.withBasePath(dataDirectory.resolve("files").toAbsolutePath().toString()));
|
||||
|
||||
instance.addTable(new QTableMetaData().withName("customer").withLabel("Customer")
|
||||
.withBackendName("h2").withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("email", QFieldType.STRING)));
|
||||
instance.addTable(new QTableMetaData().withName("order").withLabel("Order")
|
||||
.withBackendName("h2").withBackendDetails(new RDBMSTableBackendDetails().withTableName("orders"))
|
||||
.withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("orderNo", QFieldType.STRING).withBackendName("order_no"))
|
||||
.withField(new QFieldMetaData("customerId", QFieldType.INTEGER).withBackendName("customer_id"))
|
||||
.withField(new QFieldMetaData("status", QFieldType.STRING))
|
||||
.withSupplementalMetaData(new EsbTableMetaData().withPublication(new EsbTablePublication()
|
||||
.withDestinationName("orderEvents").withEvents(List.of(EsbTableEvent.INSERT, EsbTableEvent.UPDATE)))));
|
||||
instance.addTable(new QTableMetaData().withName("orderLine").withLabel("Order Line")
|
||||
.withBackendName("sqlite").withBackendDetails(new RDBMSTableBackendDetails().withTableName("order_line"))
|
||||
.withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("orderId", QFieldType.INTEGER).withBackendName("order_id"))
|
||||
.withField(new QFieldMetaData("productId", QFieldType.INTEGER).withBackendName("product_id"))
|
||||
.withField(new QFieldMetaData("quantity", QFieldType.INTEGER)));
|
||||
instance.addTable(new QTableMetaData().withName("product").withLabel("Product")
|
||||
.withBackendName("files").withPrimaryKeyField("id")
|
||||
.withBackendDetails(new FilesystemTableBackendDetails()
|
||||
.withBasePath("products").withRecordFormat(RecordFormat.JSON)
|
||||
.withCardinality(Cardinality.MANY).withGlob("*.json"))
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("price", QFieldType.DECIMAL)));
|
||||
|
||||
instance.addProcess(new QProcessMetaData().withName("syncOrder").withLabel("Sync Order")
|
||||
.withTableName("order")
|
||||
.withStep(new QBackendStepMetaData().withName("sync")
|
||||
.withCode(new QCodeReference(SyncOrderStep.class)))
|
||||
.withSupplementalMetaData(new EsbProcessMetaData()
|
||||
.withTrigger(new EsbTrigger().withDestinationName("orderEvents"))));
|
||||
|
||||
EsbInstanceMetaData.of(instance).withInstanceName("qqqAll")
|
||||
.withProvider(new QEsbProviderMetaData().withName("artemis")
|
||||
.withType(EsbProviderType.ACTIVEMQ_ARTEMIS).withUrl(brokerUrl))
|
||||
.withDestination(new QEsbDestinationMetaData().withName("orderEvents")
|
||||
.withType(EsbDestinationType.TOPIC).withProviderName("artemis")
|
||||
.withDestinationName("qqq.all.orderEvents"));
|
||||
instance.withRuntimeService(new QCodeReference(CoreEsbRuntimeService.class));
|
||||
MetaDataProducerHelper.processAllMetaDataProducersInPackage(instance, EsbAppMetaDataProducer.class.getPackageName());
|
||||
new EsbJavalinMetaDataProducer().produce(instance);
|
||||
|
||||
instance.withSupplementalMetaData(new HealthCheckMetaData().withEnabled(true)
|
||||
.withEndpointPath("/health").withIndicators(List.of(new MemoryHealthIndicator().withThreshold(99))));
|
||||
QJavalinMetaData.ofOrWithNew(instance)
|
||||
.withAdditionalRouteProviderReference(new QCodeReference(JavalinHealthRouteProvider.class));
|
||||
if(includeDemoQbits)
|
||||
{
|
||||
DemoQBits.addCore(instance, "h2");
|
||||
DemoUsers.protectDemoTables(instance);
|
||||
QJavalinMetaData.ofOrWithNew(instance)
|
||||
.withAdditionalRouteProviderReference(new QCodeReference(DemoOrderWebhookReceiver.class));
|
||||
}
|
||||
DemoRuntimeFeatures.add(instance, httpPort, bindHost);
|
||||
return instance;
|
||||
}
|
||||
|
||||
/** A visible effect for the demo and for the ESB integration test. */
|
||||
public static final class SyncOrderStep implements BackendStep
|
||||
{
|
||||
private static final AtomicInteger RUN_COUNT = new AtomicInteger();
|
||||
|
||||
@Override
|
||||
public void run(RunBackendStepInput input, RunBackendStepOutput output) throws QException
|
||||
{
|
||||
if(input.getValue(EsbTriggerHandler.VALUE_ESB_MESSAGES) instanceof List<?> messages)
|
||||
{
|
||||
for(Object message : messages)
|
||||
{
|
||||
if(message instanceof EsbEvent event
|
||||
&& event.getSource().endsWith("/table/order") && event.getSubject() != null)
|
||||
{
|
||||
Integer orderId = Integer.valueOf(event.getSubject());
|
||||
input.getProcessTracer().ifPresent(tracer -> tracer.handleMessage(input,
|
||||
new ProcessTracerKeyRecordMessage("order", orderId)));
|
||||
}
|
||||
}
|
||||
}
|
||||
RUN_COUNT.incrementAndGet();
|
||||
}
|
||||
|
||||
public static Integer getRunCount()
|
||||
{
|
||||
return RUN_COUNT.get();
|
||||
}
|
||||
|
||||
public static void reset()
|
||||
{
|
||||
RUN_COUNT.set(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.List;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.DeleteAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.instances.QRuntimeServiceInterface;
|
||||
import com.kingsrook.qqq.backend.core.logging.QLogger;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.delete.DeleteInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
|
||||
/** Seed and clear only the application's transient memory table. */
|
||||
public class TransientNotesService implements QRuntimeServiceInterface
|
||||
{
|
||||
private static final QLogger LOG = QLogger.getLogger(TransientNotesService.class);
|
||||
private QInstance instance;
|
||||
|
||||
@Override
|
||||
public String getName()
|
||||
{
|
||||
return "transientDemoNotes";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(QInstance instance) throws QException
|
||||
{
|
||||
this.instance = instance;
|
||||
var previous = QContext.capture();
|
||||
try
|
||||
{
|
||||
QContext.init(instance, new QSystemUserSession());
|
||||
clearNotes();
|
||||
new InsertAction().execute(new InsertInput("demoNote").withRecords(List.of(
|
||||
new QRecord().withValue("id", 1).withValue("text", "Transient demo note"))));
|
||||
}
|
||||
catch(QException | RuntimeException failure)
|
||||
{
|
||||
try
|
||||
{
|
||||
clearNotes();
|
||||
}
|
||||
catch(Exception cleanup)
|
||||
{
|
||||
failure.addSuppressed(cleanup);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.init(previous);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop()
|
||||
{
|
||||
var previous = QContext.capture();
|
||||
try
|
||||
{
|
||||
QContext.init(instance, new QSystemUserSession());
|
||||
clearNotes();
|
||||
}
|
||||
catch(Exception failure)
|
||||
{
|
||||
LOG.warn("Could not clear transient demo notes", failure);
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.init(previous);
|
||||
}
|
||||
}
|
||||
|
||||
private void clearNotes() throws QException
|
||||
{
|
||||
new DeleteAction().execute(new DeleteInput("demoNote").withQueryFilter(new QQueryFilter()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qbits.webhooks.model.WebhookEventStatus;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.RunProcessAction;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
|
||||
import com.kingsrook.qqq.backend.core.actions.processes.QProcessCallbackFactory;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.authentication.implementations.MockAuthenticationModule;
|
||||
import com.kingsrook.qqq.esb.runtime.EsbTriggerState;
|
||||
import com.kingsrook.qqq.esb.runtime.QEsbRuntime;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Exercises the assembled core application, including its real broker and backends. */
|
||||
class CoreApplicationTest
|
||||
{
|
||||
@TempDir
|
||||
Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void bootsQueriesEveryTableAndProcessesOrderEvents() throws Exception
|
||||
{
|
||||
Integer port;
|
||||
try(ServerSocket socket = new ServerSocket(0))
|
||||
{
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
|
||||
QqqAllApplication.SyncOrderStep.reset();
|
||||
try(CoreRuntime runtime = CoreRuntime.launch(dataDirectory, port))
|
||||
{
|
||||
HttpClient client = HttpClient.newHttpClient();
|
||||
HttpResponse<String> health = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/health")).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, health.statusCode());
|
||||
assertTrue(health.body().contains("\"UP\""));
|
||||
|
||||
assertNotNull(runtime.getLauncher().getQInstance().getApp("esb"));
|
||||
HttpResponse<String> adminEsb = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/qqq/v1/esb/overview"))
|
||||
.header("Cookie", "sessionId=" + DemoUsers.ADMIN_SESSION).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, adminEsb.statusCode(), adminEsb.body());
|
||||
assertTrue(adminEsb.body().contains("\"destinations\""));
|
||||
HttpResponse<String> viewerEsb = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/qqq/v1/esb/overview"))
|
||||
.header("Cookie", "sessionId=" + DemoUsers.DEMO_SESSION).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(403, viewerEsb.statusCode());
|
||||
|
||||
HttpResponse<String> dashboard = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://localhost:" + port + "/")).build(),
|
||||
HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, dashboard.statusCode());
|
||||
assertTrue(dashboard.body().contains("html"));
|
||||
|
||||
HttpResponse<String> demoRead = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/qqq/v1/table/order/query"))
|
||||
.header("Cookie", "sessionId=" + DemoUsers.DEMO_SESSION)
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{}"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, demoRead.statusCode(), demoRead.body());
|
||||
HttpResponse<String> demoInsert = insertOrder(client, port, DemoUsers.DEMO_SESSION, "ORD-DENIED");
|
||||
assertEquals(403, demoInsert.statusCode());
|
||||
assertEquals(403, updateWebhook(client, port, DemoUsers.DEMO_SESSION,
|
||||
"webhook", "{\"url\":\"http://127.0.0.1:1/\"}").statusCode());
|
||||
assertEquals(403, updateWebhook(client, port, DemoUsers.DEMO_SESSION,
|
||||
"webhookSubscription", "{\"activeStatusId\":3}").statusCode());
|
||||
assertEquals(403, runWebhookProcess(client, port, DemoUsers.DEMO_SESSION).statusCode());
|
||||
assertEquals(200, updateWebhook(client, port, DemoUsers.ADMIN_SESSION,
|
||||
"webhook", "{\"url\":\"http://127.0.0.1:" + port + "/demo/order-webhook\"}").statusCode());
|
||||
assertEquals(200, updateWebhook(client, port, DemoUsers.ADMIN_SESSION,
|
||||
"webhookSubscription", "{\"activeStatusId\":1}").statusCode());
|
||||
HttpResponse<String> adminInsert = insertOrder(client, port, DemoUsers.ADMIN_SESSION, "ORD-ADMIN");
|
||||
assertEquals(200, adminInsert.statusCode(), adminInsert.body());
|
||||
assertEquals(200, runWebhookProcess(client, port, DemoUsers.ADMIN_SESSION).statusCode());
|
||||
|
||||
QContext.init(runtime.getLauncher().getQInstance(), new QSystemUserSession());
|
||||
try
|
||||
{
|
||||
MockAuthenticationModule mockAuth = new MockAuthenticationModule();
|
||||
assertEquals("core:admin", mockAuth.createSession(runtime.getLauncher().getQInstance(),
|
||||
Map.of("sessionId", DemoUsers.ADMIN_SESSION)).getUser().getIdReference());
|
||||
assertEquals("core:demo", mockAuth.createSession(runtime.getLauncher().getQInstance(),
|
||||
Map.of("sessionId", DemoUsers.DEMO_SESSION)).getUser().getIdReference());
|
||||
|
||||
for(String table : List.of("customer", "order", "orderLine", "product", "address", "shipping_city"))
|
||||
{
|
||||
assertFalse(new QueryAction().execute(new QueryInput(table)).getRecords().isEmpty(), table);
|
||||
}
|
||||
assertEquals("Customer Directory", new QueryAction().execute(new QueryInput("TableView"))
|
||||
.getRecords().getFirst().getValueString("name"));
|
||||
assertEquals("Order Status Review", new QueryAction().execute(new QueryInput("workflow"))
|
||||
.getRecords().getFirst().getValueString("name"));
|
||||
|
||||
waitFor(() -> QEsbRuntime.getInstance().getRunner("syncOrder.orderEvents") != null
|
||||
&& QEsbRuntime.getInstance().getRunner("syncOrder.orderEvents").getState() == EsbTriggerState.RUNNING);
|
||||
Integer insertedOrderId = new InsertAction().execute(new InsertInput("order").withRecords(List.of(
|
||||
new QRecord().withValue("orderNo", "ORD-1002")
|
||||
.withValue("customerId", 2).withValue("status", "NEW"))))
|
||||
.getRecords().getFirst().getValueInteger("id");
|
||||
waitFor(() -> QqqAllApplication.SyncOrderStep.getRunCount() > 0);
|
||||
waitFor(() -> new QueryAction().execute(new QueryInput("processTrace")).getRecords().stream()
|
||||
.anyMatch(trace -> insertedOrderId.equals(trace.getValueInteger("keyRecordId"))));
|
||||
waitFor(() -> !new QueryAction().execute(new QueryInput("webhookEvent")).getRecords().isEmpty());
|
||||
|
||||
HttpResponse<String> receipts = client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/demo/order-webhook-receipts"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, receipts.statusCode(), receipts.body());
|
||||
waitFor(() -> client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/demo/order-webhook-receipts"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString()).body().contains("ORD-ADMIN"));
|
||||
waitFor(() -> new QueryAction().execute(new QueryInput("webhookEvent")).getRecords().stream()
|
||||
.anyMatch(event -> WebhookEventStatus.DELIVERED.getId().equals(event.getValueInteger("eventStatusId"))));
|
||||
|
||||
RunProcessInput workflow = new RunProcessInput();
|
||||
workflow.setProcessName("RunRecordWorkflow");
|
||||
workflow.setCallback(QProcessCallbackFactory.forPrimaryKey("id", 1));
|
||||
workflow.addValue("tableName", "order");
|
||||
workflow.addValue("workflowId", 1);
|
||||
workflow.setFrontendStepBehavior(RunProcessInput.FrontendStepBehavior.SKIP);
|
||||
new RunProcessAction().execute(workflow);
|
||||
assertFalse(new QueryAction().execute(new QueryInput("workflowRunLog")).getRecords().isEmpty());
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static HttpResponse<String> updateWebhook(HttpClient client, Integer port, String sessionId,
|
||||
String tableName, String body) throws Exception
|
||||
{
|
||||
return client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/data/" + tableName + "/1"))
|
||||
.header("Cookie", "sessionId=" + sessionId)
|
||||
.header("Content-Type", "application/json")
|
||||
.method("PATCH", HttpRequest.BodyPublishers.ofString(body))
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static HttpResponse<String> runWebhookProcess(HttpClient client, Integer port, String sessionId)
|
||||
throws Exception
|
||||
{
|
||||
return client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/processes/SendWebhookEvent/run?webhookId=1"))
|
||||
.header("Cookie", "sessionId=" + sessionId)
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{}"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static HttpResponse<String> insertOrder(HttpClient client, Integer port, String sessionId, String orderNo)
|
||||
throws Exception
|
||||
{
|
||||
return client.send(HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/data/order/"))
|
||||
.header("Cookie", "sessionId=" + sessionId)
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{\"orderNo\":\"" + orderNo
|
||||
+ "\",\"customerId\":1,\"status\":\"NEW\"}"))
|
||||
.build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
|
||||
private static void waitFor(java.util.concurrent.Callable<Boolean> condition) throws Exception
|
||||
{
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(15).toNanos();
|
||||
while(!condition.call() && System.nanoTime() < deadline)
|
||||
{
|
||||
Thread.sleep(50);
|
||||
}
|
||||
assertTrue(condition.call());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Exercises the shaded entry point and its HTTP API after packaging. */
|
||||
class CoreJarIT
|
||||
{
|
||||
@TempDir
|
||||
Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void packagedApplicationServesSeededData() throws Exception
|
||||
{
|
||||
Integer port;
|
||||
try(ServerSocket socket = new ServerSocket(0))
|
||||
{
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
|
||||
Path jar = Path.of(System.getProperty("qqqAllJar"));
|
||||
Path log = dataDirectory.resolve("app.log");
|
||||
ProcessBuilder builder = new ProcessBuilder(
|
||||
Path.of(System.getProperty("java.home"), "bin", "java").toString(), "-jar", jar.toString());
|
||||
builder.environment().put("QQQ_ALL_PROFILE", "core");
|
||||
builder.environment().put("QQQ_ALL_PORT", port.toString());
|
||||
builder.environment().put("QQQ_ALL_DATA_DIR", dataDirectory.resolve("data").toString());
|
||||
builder.redirectErrorStream(true).redirectOutput(log.toFile());
|
||||
Process process = builder.start();
|
||||
try
|
||||
{
|
||||
try(HttpClient client = HttpClient.newHttpClient())
|
||||
{
|
||||
URI healthUri = URI.create("http://127.0.0.1:" + port + "/health");
|
||||
HttpResponse<String> health = awaitHealth(client, healthUri, process, log);
|
||||
assertEquals(200, health.statusCode());
|
||||
assertTrue(health.body().contains("\"UP\""));
|
||||
assertTrue(Files.readString(log).contains("{127.0.0.1:" + port + "}"),
|
||||
"Core profile must bind only to loopback");
|
||||
|
||||
HttpRequest query = HttpRequest.newBuilder()
|
||||
.uri(URI.create("http://127.0.0.1:" + port + "/qqq/v1/table/customer/query"))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{}"))
|
||||
.build();
|
||||
HttpResponse<String> customers = client.send(query, HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, customers.statusCode(), customers.body());
|
||||
assertTrue(customers.body().contains("Ada Lovelace"));
|
||||
for(String table : java.util.List.of("apiCatalog", "demoNote"))
|
||||
{
|
||||
var result = client.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port
|
||||
+ "/qqq/v1/table/" + table + "/query")).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{}")).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, result.statusCode(), result.body());
|
||||
var records = new org.json.JSONObject(result.body()).getJSONArray("records");
|
||||
assertEquals(table.equals("apiCatalog") ? 3 : 1, records.length());
|
||||
}
|
||||
var calculation = client.send(HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port
|
||||
+ "/processes/calculateOrderTotal/run?quantity=3&unitPriceCents=1250"))
|
||||
.header("Cookie", "sessionId=" + DemoUsers.ADMIN_SESSION).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString("{}")).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, calculation.statusCode(), calculation.body());
|
||||
assertEquals(3750, new org.json.JSONObject(calculation.body()).getJSONObject("values").getInt("totalCents"));
|
||||
}
|
||||
try(var packaged = new java.util.jar.JarFile(jar.toFile()))
|
||||
{
|
||||
var service = packaged.getJarEntry("META-INF/services/javax.script.ScriptEngineFactory");
|
||||
org.junit.jupiter.api.Assertions.assertNotNull(service);
|
||||
try(var input = packaged.getInputStream(service))
|
||||
{
|
||||
assertTrue(new String(input.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8)
|
||||
.contains("org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory"));
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
process.destroy();
|
||||
if(!process.waitFor(5, TimeUnit.SECONDS))
|
||||
{
|
||||
process.destroyForcibly();
|
||||
process.waitFor();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"::1", "::", "0:0:0:0:0:0:0:0", "0.0.0.0"})
|
||||
void packagedCatalogUsesConfiguredListener(String bindHost) throws Exception
|
||||
{
|
||||
String clientHost = bindHost.contains(":") ? "::1" : "127.0.0.1";
|
||||
int port;
|
||||
try(ServerSocket socket = new ServerSocket(0, 50, java.net.InetAddress.getByName(clientHost)))
|
||||
{
|
||||
port = socket.getLocalPort();
|
||||
}
|
||||
URI base = new URI("http", null, clientHost, port, "/", null, null);
|
||||
Path log = dataDirectory.resolve("bound-app.log");
|
||||
ProcessBuilder builder = new ProcessBuilder(Path.of(System.getProperty("java.home"), "bin", "java").toString(),
|
||||
"-jar", System.getProperty("qqqAllJar"));
|
||||
builder.environment().put("QQQ_ALL_PROFILE", "core");
|
||||
builder.environment().put("QQQ_ALL_BIND_HOST", bindHost);
|
||||
builder.environment().put("QQQ_ALL_PORT", Integer.toString(port));
|
||||
builder.environment().put("QQQ_ALL_DATA_DIR", dataDirectory.resolve("bound-data").toString());
|
||||
builder.redirectErrorStream(true).redirectOutput(log.toFile());
|
||||
Process process = builder.start();
|
||||
try(HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build())
|
||||
{
|
||||
assertEquals(200, awaitHealth(client, base.resolve("health"), process, log).statusCode());
|
||||
var direct = client.send(HttpRequest.newBuilder(base.resolve("demo/catalog"))
|
||||
.timeout(Duration.ofSeconds(10)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, direct.statusCode(), "Configured listener must serve its catalog before testing the backend");
|
||||
assertEquals(2, new org.json.JSONArray(direct.body()).length());
|
||||
|
||||
var all = catalogQuery(client, base, "{}");
|
||||
assertEquals(java.util.List.of(101, 102, 103), all.toList().stream()
|
||||
.map(row -> ((java.util.Map<?, ?>) ((java.util.Map<?, ?>) row).get("values")).get("id")).toList());
|
||||
for(int skip = 0; skip < 3; skip++)
|
||||
{
|
||||
var page = catalogQuery(client, base, "{\"filter\":{\"skip\":" + skip + ",\"limit\":1}}");
|
||||
assertEquals(1, page.length());
|
||||
assertEquals(java.util.List.of(101, 102, 103).get(skip), page.getJSONObject(0).getJSONObject("values").getInt("id"));
|
||||
}
|
||||
assertEquals(0, catalogQuery(client, base, "{\"filter\":{\"skip\":3,\"limit\":1}}").length());
|
||||
var get = client.send(HttpRequest.newBuilder(base.resolve("data/apiCatalog/103"))
|
||||
.timeout(Duration.ofSeconds(10)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, get.statusCode(), get.body());
|
||||
assertEquals("Shipping Box", new org.json.JSONObject(get.body()).getJSONObject("values").getString("name"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
process.destroy();
|
||||
if(!process.waitFor(5, TimeUnit.SECONDS))
|
||||
{
|
||||
process.destroyForcibly();
|
||||
assertTrue(process.waitFor(5, TimeUnit.SECONDS), "Owned packaged process must stop");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static org.json.JSONArray catalogQuery(HttpClient client, URI base, String body) throws Exception
|
||||
{
|
||||
var response = client.send(HttpRequest.newBuilder(base.resolve("qqq/v1/table/apiCatalog/query"))
|
||||
.timeout(Duration.ofSeconds(10)).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body)).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, response.statusCode(), response.body());
|
||||
return new org.json.JSONObject(response.body()).getJSONArray("records");
|
||||
}
|
||||
|
||||
private static HttpResponse<String> awaitHealth(HttpClient client, URI uri, Process process, Path log) throws Exception
|
||||
{
|
||||
long deadline = System.nanoTime() + Duration.ofSeconds(30).toNanos();
|
||||
while(System.nanoTime() < deadline && process.isAlive())
|
||||
{
|
||||
try
|
||||
{
|
||||
return client.send(HttpRequest.newBuilder().uri(uri).build(), HttpResponse.BodyHandlers.ofString());
|
||||
}
|
||||
catch(java.net.ConnectException e)
|
||||
{
|
||||
Thread.sleep(100);
|
||||
}
|
||||
}
|
||||
throw new AssertionError("Packaged app did not become healthy. Output:\n" + Files.readString(log));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import com.kingsrook.qbits.webhooks.registry.WebhooksRegistry;
|
||||
import com.kingsrook.qbits.workflows.definition.WorkflowsRegistry;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class CoreQBitsTest
|
||||
{
|
||||
@TempDir Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void coreExposesLocalQbitsAndOrderTrace() throws Exception
|
||||
{
|
||||
QInstance instance = new QqqAllApplication(dataDirectory, "tcp://127.0.0.1:61616").defineQInstance();
|
||||
new QInstanceValidator().validate(instance);
|
||||
Set<String> artifacts = instance.getQBits().values().stream()
|
||||
.map(qbit -> qbit.getArtifactId()).collect(Collectors.toSet());
|
||||
assertTrue(artifacts.containsAll(Set.of("customizable-table-views", "standard-process-trace",
|
||||
"webhooks", "workflows", "qbit-geo-data")));
|
||||
assertNotNull(instance.getTable("TableView"));
|
||||
assertNotNull(instance.getTable("processTrace"));
|
||||
assertNotNull(instance.getTable("webhook"));
|
||||
assertNotNull(instance.getTable("workflow"));
|
||||
assertNotNull(instance.getProcess("syncOrder").getProcessTracerCodeReference());
|
||||
assertNotNull(WebhooksRegistry.of(instance).getWebhookEventType("orderStored"));
|
||||
assertNotNull(WorkflowsRegistry.of(instance).getWorkflowType("RecordWorkflow"));
|
||||
assertNotNull(instance.getTable("address").getField("cityId").getPossibleValueSourceName());
|
||||
assertTrue(artifacts.stream().noneMatch("quick-search"::equals));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import com.kingsrook.qbits.userrolepermissions.model.Role;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.AuthScope;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.QAuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.implementations.memory.MemoryBackendModule;
|
||||
import org.json.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/** Keycloak realm roles must flow through the role permission resolver on login and resume. */
|
||||
class FullOidcSessionCustomizerTest
|
||||
{
|
||||
@Test
|
||||
void resolvesRolesBeforeAnAuthenticationSessionExists()
|
||||
{
|
||||
QInstance instance = new QInstance();
|
||||
instance.registerAuthenticationProvider(AuthScope.instanceDefault(),
|
||||
new QAuthenticationMetaData().withName("mock").withType(QAuthenticationType.MOCK));
|
||||
instance.addBackend(new QBackendMetaData().withName("memory")
|
||||
.withBackendType(MemoryBackendModule.class));
|
||||
instance.addTable(new QTableMetaData().withName(Role.TABLE_NAME).withBackendName("memory")
|
||||
.withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("name", QFieldType.STRING)));
|
||||
|
||||
QContext.init(instance, null);
|
||||
try
|
||||
{
|
||||
QSession session = new QSession();
|
||||
new FullOidcSessionCustomizer().customizeSession(instance, session,
|
||||
Map.of("idToken", new JSONObject("{\"realm_access\":{\"roles\":[\"viewer\"]}}")));
|
||||
assertEquals(Set.of(), session.getPermissions());
|
||||
assertNull(QContext.getQSession());
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void mapsIdTokenRolesToSessionPermissions()
|
||||
{
|
||||
RecordingCustomizer customizer = new RecordingCustomizer();
|
||||
QSession session = new QSession();
|
||||
customizer.customizeSession(null, session, Map.of("idToken", new JSONObject("{\"realm_access\":{\"roles\":[\"admin\",\"viewer\"]}}")));
|
||||
assertEquals(Set.of("admin", "viewer"), customizer.requestedRoles);
|
||||
assertEquals(Set.of("customer.read"), session.getPermissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesAccessTokenRolesOnSessionResumeAndDoesNotGrantUnknownRoles()
|
||||
{
|
||||
RecordingCustomizer customizer = new RecordingCustomizer();
|
||||
QSession session = new QSession();
|
||||
customizer.customizeSession(null, session, Map.of("jwtPayloadJsonObject", new JSONObject("{\"realm_access\":{\"roles\":[\"viewer\"]}}")));
|
||||
assertEquals(Set.of("viewer"), customizer.requestedRoles);
|
||||
|
||||
QSession noRoles = new QSession();
|
||||
customizer.customizeSession(null, noRoles, Map.of("jwtPayloadJsonObject", new JSONObject("{}")));
|
||||
assertEquals(Set.of(), noRoles.getPermissions());
|
||||
}
|
||||
|
||||
@Test
|
||||
void usesAccessTokenRolesWhenIdTokenHasNoRealmRoles()
|
||||
{
|
||||
RecordingCustomizer customizer = new RecordingCustomizer();
|
||||
QSession session = new QSession();
|
||||
customizer.customizeSession(null, session, Map.of(
|
||||
"idToken", new JSONObject("{\"email\":\"demo@example.test\"}"),
|
||||
"jwtPayloadJsonObject", new JSONObject("{\"realm_access\":{\"roles\":[\"viewer\"]}}")));
|
||||
assertEquals(Set.of("viewer"), customizer.requestedRoles);
|
||||
}
|
||||
|
||||
private static class RecordingCustomizer extends FullOidcSessionCustomizer
|
||||
{
|
||||
private Set<String> requestedRoles;
|
||||
|
||||
@Override
|
||||
protected Set<String> permissionsForRoles(Set<String> roles)
|
||||
{
|
||||
requestedRoles = roles;
|
||||
return roles.isEmpty() ? Set.of() : Set.of("customer.read");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.esb.management.ArtemisJolokiaAdapter;
|
||||
import com.kingsrook.qqq.esb.management.EsbBrokerNames;
|
||||
import com.kingsrook.qqq.esb.management.RabbitManagementAdapter;
|
||||
import com.kingsrook.qqq.esb.model.EsbInstanceMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbProviderType;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Opt-in smoke test against the local full Compose brokers and their management APIs. */
|
||||
@EnabledIfEnvironmentVariable(named = "QQQ_ALL_COMPOSE_BROKERS", matches = "true")
|
||||
class FullProfileBrokerIntegrationTest
|
||||
{
|
||||
@TempDir
|
||||
Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void managesQueuesWithFullProfileCredentials() throws Exception
|
||||
{
|
||||
Map<String, String> environment = FullProfileTest.environment();
|
||||
environment.put("QQQ_ALL_ARTEMIS_USER", System.getenv("ARTEMIS_USER"));
|
||||
environment.put("QQQ_ALL_ARTEMIS_PASSWORD", System.getenv("ARTEMIS_PASSWORD"));
|
||||
environment.put("QQQ_ALL_ARTEMIS_MANAGEMENT_URL", "http://127.0.0.1:8161");
|
||||
environment.put("QQQ_ALL_RABBITMQ_USER", System.getenv("RABBITMQ_USER"));
|
||||
environment.put("QQQ_ALL_RABBITMQ_PASSWORD", System.getenv("RABBITMQ_PASSWORD"));
|
||||
environment.put("QQQ_ALL_RABBITMQ_MANAGEMENT_URL", "http://127.0.0.1:15672");
|
||||
QInstance instance = new FullProfileApplication(dataDirectory, FullProfileSettings.from(environment)).defineQInstance();
|
||||
EsbInstanceMetaData esb = EsbInstanceMetaData.of(instance);
|
||||
|
||||
ArtemisJolokiaAdapter artemis = new ArtemisJolokiaAdapter(esb.getProvider("artemis"));
|
||||
String subscription = EsbBrokerNames.subscriptionQueue(EsbProviderType.ACTIVEMQ_ARTEMIS,
|
||||
"qqq.all.orderEvents", "syncOrder.qqq.all.orderEvents");
|
||||
assertTrue(artemis.getQueueInfo(subscription).isPresent());
|
||||
try
|
||||
{
|
||||
artemis.pauseQueue(subscription);
|
||||
assertTrue(artemis.getQueueInfo(subscription).orElseThrow().paused());
|
||||
}
|
||||
finally
|
||||
{
|
||||
artemis.resumeQueue(subscription);
|
||||
}
|
||||
assertFalse(artemis.getQueueInfo(subscription).orElseThrow().paused());
|
||||
|
||||
RabbitManagementAdapter rabbit = new RabbitManagementAdapter(esb.getProvider("rabbitmq"));
|
||||
String queueName = "qqq.all.c6.managementProbe." + UUID.randomUUID();
|
||||
String queueUrl = "http://127.0.0.1:15672/api/queues/%2F/" + queueName;
|
||||
String credentials = environment.get("QQQ_ALL_RABBITMQ_USER") + ":" + environment.get("QQQ_ALL_RABBITMQ_PASSWORD");
|
||||
String authorization = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
|
||||
try(HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build())
|
||||
{
|
||||
HttpRequest create = HttpRequest.newBuilder(URI.create(queueUrl))
|
||||
.header("Authorization", authorization).header("Content-Type", "application/json")
|
||||
.PUT(HttpRequest.BodyPublishers.ofString("{\"durable\":true,\"auto_delete\":false,\"arguments\":{}}"))
|
||||
.build();
|
||||
assertEquals(201, client.send(create, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
try
|
||||
{
|
||||
assertTrue(rabbit.getQueueInfo(queueName).isPresent());
|
||||
assertEquals(0L, rabbit.purgeQueue(queueName));
|
||||
}
|
||||
finally
|
||||
{
|
||||
HttpRequest delete = HttpRequest.newBuilder(URI.create(queueUrl))
|
||||
.header("Authorization", authorization).DELETE().build();
|
||||
assertEquals(204, client.send(delete, HttpResponse.BodyHandlers.discarding()).statusCode());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.authentication.OAuth2AuthenticationMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QAuthenticationType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.messaging.email.EmailMessagingProviderMetaData;
|
||||
import com.kingsrook.qqq.backend.module.mongodb.model.metadata.MongoDBBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.jdbc.ConnectionManager;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
|
||||
import com.kingsrook.qqq.esb.model.EsbInstanceMetaData;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Full profile wiring tests that require no external services. */
|
||||
class FullProfileTest
|
||||
{
|
||||
@TempDir
|
||||
Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void rejectsMissingFullProfileCredentialsBeforeStartup()
|
||||
{
|
||||
assertThrows(IllegalArgumentException.class, () -> FullProfileSettings.from(Map.of("QQQ_ALL_PROFILE", "full")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void wiresEveryFullBackendBrokerMailAndOidcFromEnvironment() throws Exception
|
||||
{
|
||||
FullProfileSettings settings = FullProfileSettings.from(environment());
|
||||
QInstance instance = new FullProfileApplication(dataDirectory, settings).defineQInstance();
|
||||
new QInstanceValidator().validate(instance);
|
||||
|
||||
RDBMSBackendMetaData postgres = (RDBMSBackendMetaData) instance.getBackend("postgres");
|
||||
assertEquals("com.kingsrook.qqq.backend.module.postgres.model.metadata.PostgreSQLBackendMetaData", postgres.getClass().getName());
|
||||
assertEquals("postgres.example.test", postgres.getHostName());
|
||||
assertEquals("jdbc:postgresql://postgres.example.test:5432/qqq", ConnectionManager.getJdbcUrl(postgres));
|
||||
assertEquals("org.postgresql.Driver", ConnectionManager.getJdbcDriverClassName(postgres));
|
||||
assertEquals("\"", postgres.getActionStrategy().getIdentifierQuoteString());
|
||||
assertEquals("DEFAULT VALUES", postgres.getActionStrategy().getInsertDefaultValuesClause());
|
||||
assertEquals("mysql.example.test", ((RDBMSBackendMetaData) instance.getBackend("mysql")).getHostName());
|
||||
assertEquals("replicaSet=rs0", ((MongoDBBackendMetaData) instance.getBackend("mongo")).getUrlSuffix());
|
||||
assertEquals("postgres", instance.getTable("warehouseCustomer").getBackendName());
|
||||
assertEquals("mysql", instance.getTable("supplierOrder").getBackendName());
|
||||
assertEquals("mongo", instance.getTable("shipment").getBackendName());
|
||||
assertEquals("http://minio.example.test:9000",
|
||||
((MinioBackendMetaData) instance.getBackend("s3")).getEndpoint());
|
||||
assertEquals("s3", instance.getTable("document").getBackendName());
|
||||
assertEquals("sftp", instance.getTable("externalImportFile").getBackendName());
|
||||
|
||||
EsbInstanceMetaData esb = EsbInstanceMetaData.of(instance);
|
||||
assertEquals("tcp://artemis.example.test:61616", esb.getProvider("artemis").getUrl());
|
||||
assertEquals("fixture", esb.getProvider("artemis").getUsername());
|
||||
assertEquals("fixture", esb.getProvider("artemis").getPassword());
|
||||
assertEquals("http://artemis.example.test:8161", esb.getProvider("artemis").getManagementUrl());
|
||||
assertEquals("fixture", esb.getProvider("artemis").getManagementUsername());
|
||||
assertEquals("fixture", esb.getProvider("artemis").getManagementPassword());
|
||||
assertEquals("amqp://rabbit.example.test:5672/%2F", esb.getProvider("rabbitmq").getUrl());
|
||||
assertEquals("http://rabbit.example.test:15672", esb.getProvider("rabbitmq").getManagementUrl());
|
||||
assertEquals("fixture", esb.getProvider("rabbitmq").getManagementUsername());
|
||||
assertEquals("fixture", esb.getProvider("rabbitmq").getManagementPassword());
|
||||
assertEquals("artemis", esb.getDestination("orderEvents").getProviderName());
|
||||
assertEquals("rabbitmq", esb.getDestination("orderSyncEvents").getProviderName());
|
||||
|
||||
OAuth2AuthenticationMetaData auth = (OAuth2AuthenticationMetaData) instance.getAuthentication();
|
||||
assertEquals(QAuthenticationType.OAUTH2, auth.getType());
|
||||
assertEquals("https://keycloak.example.test/realms/demo", auth.getBaseUrl());
|
||||
assertNotNull(instance.getTable(auth.getUserSessionTableName()));
|
||||
assertNotNull(instance.getTable(auth.getRedirectStateTableName()));
|
||||
assertEquals("mailpit.example.test", ((EmailMessagingProviderMetaData) instance.getMessagingProvider("mailpit")).getSmtpServer());
|
||||
assertTrue(instance.getQBits().values().stream().anyMatch(qbit -> "user-role-permissions".equals(qbit.getArtifactId())));
|
||||
}
|
||||
|
||||
static Map<String, String> environment()
|
||||
{
|
||||
Map<String, String> values = new HashMap<>();
|
||||
values.put("QQQ_ALL_BIND_HOST", "127.0.0.1");
|
||||
values.put("QQQ_ALL_POSTGRES_HOST", "postgres.example.test");
|
||||
values.put("QQQ_ALL_POSTGRES_DATABASE", "qqq");
|
||||
values.put("QQQ_ALL_POSTGRES_USER", "fixture");
|
||||
values.put("QQQ_ALL_POSTGRES_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_MYSQL_HOST", "mysql.example.test");
|
||||
values.put("QQQ_ALL_MYSQL_DATABASE", "qqq");
|
||||
values.put("QQQ_ALL_MYSQL_USER", "fixture");
|
||||
values.put("QQQ_ALL_MYSQL_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_MONGO_HOST", "mongo.example.test");
|
||||
values.put("QQQ_ALL_MONGO_DATABASE", "qqq");
|
||||
values.put("QQQ_ALL_MONGO_USER", "fixture");
|
||||
values.put("QQQ_ALL_MONGO_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_MONGO_REPLICA_SET", "rs0");
|
||||
values.put("QQQ_ALL_S3_BUCKET", "qqq-demo");
|
||||
values.put("QQQ_ALL_S3_ENDPOINT", "http://minio.example.test:9000");
|
||||
values.put("QQQ_ALL_S3_ACCESS_KEY", "fixture");
|
||||
values.put("QQQ_ALL_S3_SECRET_KEY", "fixture");
|
||||
values.put("QQQ_ALL_SFTP_HOST", "sftp.example.test");
|
||||
values.put("QQQ_ALL_SFTP_USER", "fixture");
|
||||
values.put("QQQ_ALL_SFTP_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_ARTEMIS_URL", "tcp://artemis.example.test:61616");
|
||||
values.put("QQQ_ALL_ARTEMIS_USER", "fixture");
|
||||
values.put("QQQ_ALL_ARTEMIS_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_ARTEMIS_MANAGEMENT_URL", "http://artemis.example.test:8161");
|
||||
values.put("QQQ_ALL_RABBITMQ_URL", "amqp://rabbit.example.test:5672/%2F");
|
||||
values.put("QQQ_ALL_RABBITMQ_MANAGEMENT_URL", "http://rabbit.example.test:15672");
|
||||
values.put("QQQ_ALL_RABBITMQ_USER", "fixture");
|
||||
values.put("QQQ_ALL_RABBITMQ_PASSWORD", "fixture");
|
||||
values.put("QQQ_ALL_SMTP_HOST", "mailpit.example.test");
|
||||
values.put("QQQ_ALL_OIDC_BASE_URL", "https://keycloak.example.test/realms/demo");
|
||||
values.put("QQQ_ALL_OIDC_CLIENT_ID", "qqq-all");
|
||||
values.put("QQQ_ALL_OIDC_CLIENT_SECRET", "fixture");
|
||||
values.put("QQQ_ALL_OPENSEARCH_HOST", "127.0.0.1");
|
||||
values.put("QQQ_ALL_OPENSEARCH_PORT", "1");
|
||||
return values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import com.kingsrook.qbits.quicksearch.QuickSearchQBitConfig;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.PermissionsHelper;
|
||||
import com.kingsrook.qqq.backend.core.actions.permissions.TablePermissionSubType;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QPermissionDeniedException;
|
||||
import com.kingsrook.qqq.backend.core.instances.QInstanceValidator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunProcessInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.QInstance;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.permissions.PermissionLevel;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSession;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class FullQBitsTest
|
||||
{
|
||||
@TempDir Path dataDirectory;
|
||||
|
||||
@Test
|
||||
void fullAddsCustomerSearchAndSftpImportToTheDemo() throws Exception
|
||||
{
|
||||
FullProfileSettings settings = FullProfileSettings.from(FullProfileTest.environment());
|
||||
QInstance instance = new FullProfileApplication(dataDirectory, settings).defineQInstance();
|
||||
new QInstanceValidator().validate(instance);
|
||||
|
||||
Set<String> artifacts = instance.getQBits().values().stream()
|
||||
.map(qbit -> qbit.getArtifactId()).collect(Collectors.toSet());
|
||||
assertTrue(artifacts.containsAll(Set.of("quick-search", "user-role-permissions",
|
||||
"customizable-table-views", "standard-process-trace", "webhooks", "workflows",
|
||||
"qbit-geo-data", "sftp-data-integration")));
|
||||
assertNotNull(instance.getApp("quickSearchAdmin"));
|
||||
assertNotNull(instance.getProcess("quickSearchFullReindex"));
|
||||
assertNotNull(instance.getProcess("quickSearchReconcileIndex"));
|
||||
assertNotNull(instance.getProcess("SFTPImportFileSyncProcess"));
|
||||
assertNotNull(instance.getTable("SFTPImportSourceFileTable"));
|
||||
assertEquals("sftp", instance.getTable("SFTPImportSourceFileTable").getBackendName());
|
||||
assertEquals("scheduled_job", ((RDBMSTableBackendDetails) instance.getTable("scheduledJob")
|
||||
.getBackendDetails()).getTableName());
|
||||
assertEquals("create_date", instance.getTable("scheduledJob").getField("createDate").getBackendName());
|
||||
assertEquals(QFieldType.STRING, instance.getTable("processTrace").getField("userId").getType());
|
||||
assertTrue(DemoQBitData.postgresSchemaStatements(instance).stream()
|
||||
.anyMatch(sql -> sql.startsWith("CREATE TABLE IF NOT EXISTS \"scheduled_job\"")
|
||||
&& sql.contains("\"create_date\" TIMESTAMP")));
|
||||
assertTrue(DemoQBitData.postgresSchemaStatements(instance).stream()
|
||||
.anyMatch(sql -> sql.startsWith("CREATE TABLE IF NOT EXISTS \"webhook_subscription\"")
|
||||
&& sql.contains("\"webhook_event_type_name\" VARCHAR(4000)")));
|
||||
assertFalse(DemoQBitData.postgresSchemaStatements(instance).stream()
|
||||
.anyMatch(sql -> sql.contains("\"user_session\"") || sql.contains("\"warehouse_customer\"")));
|
||||
for(String tableName : Set.of("webhook", "webhookSubscription", "webhookEvent",
|
||||
"webhookEventContent", "webhookEventSendLog", "scheduledJob", "scheduledJobParameter"))
|
||||
{
|
||||
assertEquals(PermissionLevel.READ_INSERT_EDIT_DELETE_PERMISSIONS,
|
||||
instance.getTable(tableName).getPermissionRules().getLevel(), tableName);
|
||||
}
|
||||
for(String processName : Set.of("SendWebhookEvent", "SendTestEventToWebhook", "ManageWebhookHealth"))
|
||||
{
|
||||
assertEquals(PermissionLevel.HAS_ACCESS_PERMISSION,
|
||||
instance.getProcess(processName).getPermissionRules().getLevel(), processName);
|
||||
}
|
||||
QuickSearchQBitConfig search = (QuickSearchQBitConfig) instance.getQBits().values().stream()
|
||||
.filter(qbit -> "quick-search".equals(qbit.getArtifactId())).findFirst().orElseThrow().getConfig();
|
||||
assertEquals("customer", search.getSearchableTables().getFirst().getTableName());
|
||||
assertEquals(Set.of("name", "email"), search.getSearchableTables().getFirst().getFields().stream()
|
||||
.map(field -> field.getFieldName()).collect(Collectors.toSet()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void viewerPermissionsCannotChangeWebhookDestinationOrSendEvent() throws Exception
|
||||
{
|
||||
QInstance instance = new FullProfileApplication(dataDirectory,
|
||||
FullProfileSettings.from(FullProfileTest.environment())).defineQInstance();
|
||||
QSession viewer = new QSession().withPermissions("webhook.read", "webhookSubscription.read");
|
||||
QContext.init(instance, viewer);
|
||||
try
|
||||
{
|
||||
assertFalse(PermissionsHelper.hasTablePermission(new QueryInput("webhook"),
|
||||
"webhook", TablePermissionSubType.EDIT));
|
||||
assertFalse(PermissionsHelper.hasTablePermission(new QueryInput("webhookSubscription"),
|
||||
"webhookSubscription", TablePermissionSubType.EDIT));
|
||||
assertThrows(QPermissionDeniedException.class,
|
||||
() -> PermissionsHelper.checkProcessPermissionThrowing(new RunProcessInput(), "SendWebhookEvent"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void adminPermissionsCanChangeWebhookDestinationAndSendEvent() throws Exception
|
||||
{
|
||||
QInstance instance = new FullProfileApplication(dataDirectory,
|
||||
FullProfileSettings.from(FullProfileTest.environment())).defineQInstance();
|
||||
QSession admin = new QSession().withPermissions("webhook.edit", "webhookSubscription.edit",
|
||||
"SendWebhookEvent.hasAccess");
|
||||
QContext.init(instance, admin);
|
||||
try
|
||||
{
|
||||
assertTrue(PermissionsHelper.hasTablePermission(new QueryInput("webhook"),
|
||||
"webhook", TablePermissionSubType.EDIT));
|
||||
assertTrue(PermissionsHelper.hasTablePermission(new QueryInput("webhookSubscription"),
|
||||
"webhookSubscription", TablePermissionSubType.EDIT));
|
||||
PermissionsHelper.checkProcessPermissionThrowing(new RunProcessInput(), "SendWebhookEvent");
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.kingsrook.qqq.backend.core.modules.backend.QBackendModuleDispatcher;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.actions.AbstractS3Action;
|
||||
import com.kingsrook.qqq.backend.module.filesystem.s3.utils.S3Utils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class MinioBackendTest
|
||||
{
|
||||
@Test
|
||||
void usesConfiguredEndpointForAllFilesystemActions() throws Exception
|
||||
{
|
||||
MinioBackendMetaData backend = new MinioBackendMetaData("http://minio.example.test:9000");
|
||||
backend.setName("s3");
|
||||
backend.setBucketName("qqq-demo");
|
||||
backend.setAccessKey("fixture");
|
||||
backend.setSecretKey("fixture");
|
||||
backend.setRegion("us-east-1");
|
||||
MinioBackendModule module = assertInstanceOf(MinioBackendModule.class,
|
||||
new QBackendModuleDispatcher().getQBackendModule(backend));
|
||||
assertUrl((AbstractS3Action) module.getActionBase(), backend);
|
||||
assertUrl((AbstractS3Action) module.getQueryInterface(), backend);
|
||||
assertUrl((AbstractS3Action) module.getInsertInterface(), backend);
|
||||
assertUrl((AbstractS3Action) module.getCountInterface(), backend);
|
||||
assertUrl((AbstractS3Action) module.getDeleteInterface(), backend);
|
||||
assertUrl((AbstractS3Action) module.getStorageInterface(), backend);
|
||||
}
|
||||
|
||||
private static void assertUrl(AbstractS3Action action, MinioBackendMetaData backend) throws Exception
|
||||
{
|
||||
action.preAction(backend);
|
||||
S3Utils utils = utils(action);
|
||||
assertEquals("http://minio.example.test:9000/qqq-demo/example.json",
|
||||
utils.getAmazonS3().getUrl("qqq-demo", "example.json").toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryAndWriteUseLocalS3Endpoint() throws Exception
|
||||
{
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
AtomicReference<String> written = new AtomicReference<>();
|
||||
server.createContext("/", exchange ->
|
||||
{
|
||||
byte[] response;
|
||||
if("PUT".equals(exchange.getRequestMethod()))
|
||||
{
|
||||
written.set(exchange.getRequestURI().getPath() + ":" +
|
||||
new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
exchange.getResponseHeaders().add("ETag", "\"fixture-etag\"");
|
||||
response = new byte[0];
|
||||
}
|
||||
else
|
||||
{
|
||||
String xml = "<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
|
||||
+ "<Name>qqq-demo</Name><IsTruncated>false</IsTruncated>"
|
||||
+ "<Contents><Key>documents/example.json</Key><Size>2</Size>"
|
||||
+ "<LastModified>2026-01-01T00:00:00.000Z</LastModified></Contents></ListBucketResult>";
|
||||
response = xml.getBytes(StandardCharsets.UTF_8);
|
||||
exchange.getResponseHeaders().add("Content-Type", "application/xml");
|
||||
}
|
||||
exchange.sendResponseHeaders(200, response.length);
|
||||
exchange.getResponseBody().write(response);
|
||||
exchange.close();
|
||||
});
|
||||
server.start();
|
||||
try
|
||||
{
|
||||
MinioBackendMetaData backend = new MinioBackendMetaData("http://127.0.0.1:" + server.getAddress().getPort());
|
||||
backend.setName("s3");
|
||||
backend.setBucketName("qqq-demo");
|
||||
backend.setAccessKey("fixture");
|
||||
backend.setSecretKey("fixture");
|
||||
backend.setRegion("us-east-1");
|
||||
MinioBackendModule module = new MinioBackendModule();
|
||||
|
||||
AbstractS3Action query = (AbstractS3Action) module.getQueryInterface();
|
||||
query.preAction(backend);
|
||||
assertEquals("documents/example.json", utils(query).getAmazonS3()
|
||||
.listObjectsV2("qqq-demo").getObjectSummaries().getFirst().getKey());
|
||||
|
||||
AbstractS3Action insert = (AbstractS3Action) module.getInsertInterface();
|
||||
insert.preAction(backend);
|
||||
utils(insert).writeFile("qqq-demo", "documents/new.json", "{}".getBytes(StandardCharsets.UTF_8), "application/json");
|
||||
assertTrue(written.get().startsWith("/qqq-demo/documents/new.json:"));
|
||||
assertTrue(written.get().contains("\r\n{}\r\n"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
server.stop(0);
|
||||
}
|
||||
}
|
||||
|
||||
private static S3Utils utils(AbstractS3Action action) throws Exception
|
||||
{
|
||||
var accessor = AbstractS3Action.class.getDeclaredMethod("getS3Utils");
|
||||
accessor.setAccessible(true);
|
||||
return (S3Utils) accessor.invoke(action);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.sql.DriverManager;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.InsertAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.insert.InsertInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.fields.QFieldType;
|
||||
import com.kingsrook.qqq.backend.core.model.metadata.tables.QTableMetaData;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.jdbc.ConnectionManager;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSBackendMetaData;
|
||||
import com.kingsrook.qqq.backend.module.rdbms.model.metadata.RDBMSTableBackendDetails;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/** Opt-in native PostgreSQL oracle; owns only its uniquely named table. */
|
||||
@EnabledIfEnvironmentVariable(named = "QQQ_ALL_TEST_POSTGRES_PORT", matches = "[0-9]+")
|
||||
@Timeout(30)
|
||||
class PostgresCompatibilityTest
|
||||
{
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@Test
|
||||
void nativeStrategyPreservesGeneratedIdsNullsAndUtcTimestamps() throws Exception
|
||||
{
|
||||
var environment = FullProfileTest.environment();
|
||||
environment.put("QQQ_ALL_POSTGRES_HOST", "127.0.0.1");
|
||||
environment.put("QQQ_ALL_POSTGRES_PORT", System.getenv("QQQ_ALL_TEST_POSTGRES_PORT"));
|
||||
environment.put("QQQ_ALL_POSTGRES_DATABASE", "qqq");
|
||||
environment.put("QQQ_ALL_POSTGRES_USER", "qqq");
|
||||
environment.put("QQQ_ALL_POSTGRES_PASSWORD", System.getenv("QQQ_ALL_TEST_POSTGRES_PASSWORD"));
|
||||
var instance = new FullProfileApplication(directory, FullProfileSettings.from(environment)).defineQInstance();
|
||||
var backend = (RDBMSBackendMetaData) instance.getBackend("postgres");
|
||||
String table = "compat_" + UUID.randomUUID().toString().replace("-", "");
|
||||
instance.addTable(new QTableMetaData().withName("compatibility").withBackendName("postgres")
|
||||
.withBackendDetails(new RDBMSTableBackendDetails().withTableName(table)).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER))
|
||||
.withField(new QFieldMetaData("value", QFieldType.STRING))
|
||||
.withField(new QFieldMetaData("created", QFieldType.DATE_TIME)));
|
||||
instance.addTable(new QTableMetaData().withName("compatibilityDefault").withBackendName("postgres")
|
||||
.withBackendDetails(new RDBMSTableBackendDetails().withTableName(table)).withPrimaryKeyField("id")
|
||||
.withField(new QFieldMetaData("id", QFieldType.INTEGER)));
|
||||
var previous = QContext.capture();
|
||||
try(var connection = DriverManager.getConnection(ConnectionManager.getJdbcUrl(backend), backend.getUsername(), backend.getPassword());
|
||||
var statement = connection.createStatement())
|
||||
{
|
||||
statement.execute("CREATE TABLE " + table + " (id SERIAL PRIMARY KEY, value TEXT, created TIMESTAMP)");
|
||||
try
|
||||
{
|
||||
QContext.init(instance, new QSystemUserSession());
|
||||
var empty = new InsertAction().execute(new InsertInput("compatibilityDefault").withRecords(List.of(new QRecord()))).getRecords().getFirst();
|
||||
assertNotNull(empty.getValueInteger("id"));
|
||||
Instant timestamp = Instant.parse("2026-09-25T12:34:56Z");
|
||||
var row = new InsertAction().execute(new InsertInput("compatibility").withRecords(List.of(
|
||||
new QRecord().withValue("value", "demo").withValue("created", timestamp)))).getRecords().getFirst();
|
||||
assertTrue(row.getValueInteger("id") > empty.getValueInteger("id"));
|
||||
new UpdateAction().execute(new UpdateInput("compatibility").withRecords(List.of(
|
||||
new QRecord().withValue("id", row.getValueInteger("id")).withValue("value", null))));
|
||||
assertNull(GetAction.execute("compatibility", row.getValueInteger("id")).getValue("value"));
|
||||
try(var result = statement.executeQuery("SELECT value, created FROM " + table + " WHERE id = " + row.getValueInteger("id")))
|
||||
{
|
||||
assertTrue(result.next());
|
||||
assertNull(result.getString(1));
|
||||
assertEquals(timestamp, result.getTimestamp(2, java.util.Calendar.getInstance(java.util.TimeZone.getTimeZone("UTC"))).toInstant());
|
||||
assertFalse(result.next());
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
statement.execute("DROP TABLE " + table);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.init(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** The executable profile selector must choose the right startup path. */
|
||||
class ProfileLauncherTest
|
||||
{
|
||||
@Test
|
||||
void selectsCoreByDefaultAndFullWhenRequested()
|
||||
{
|
||||
assertEquals("core", ProfileLauncher.profile(Map.of()));
|
||||
assertEquals("full", ProfileLauncher.profile(Map.of("QQQ_ALL_PROFILE", "full")));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> ProfileLauncher.profile(Map.of("QQQ_ALL_PROFILE", "typo")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullFailsForMissingConfigurationBeforeOpeningServices()
|
||||
{
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> ProfileLauncher.launch(Map.of("QQQ_ALL_PROFILE", "full")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullRequiresAnExplicitHttpBindAddress()
|
||||
{
|
||||
Map<String, String> environment = new HashMap<>(FullProfileTest.environment());
|
||||
environment.remove("QQQ_ALL_BIND_HOST");
|
||||
assertEquals("Missing required environment variable QQQ_ALL_BIND_HOST",
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> FullProfileSettings.from(environment)).getMessage());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import javax.script.ScriptEngineManager;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/** The reference application must ship its advertised backend and language. */
|
||||
class RuntimeAssemblyTest
|
||||
{
|
||||
@Test
|
||||
void includesApiBackendAndJavaScriptEngine()
|
||||
{
|
||||
assertDoesNotThrow(() -> Class.forName("com.kingsrook.qqq.backend.module.api.APIBackendModule"));
|
||||
assertDoesNotThrow(() -> Class.forName("com.kingsrook.qqq.languages.javascript.QJavaScriptExecutor"));
|
||||
assertNotNull(new ScriptEngineManager().getEngineByName("JavaScript"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* Copyright 2026 Kingsrook, LLC
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0
|
||||
*/
|
||||
package com.kingsrook.qqq.all;
|
||||
|
||||
import java.net.ServerSocket;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.CountAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.GetAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.QueryAction;
|
||||
import com.kingsrook.qqq.backend.core.actions.tables.UpdateAction;
|
||||
import com.kingsrook.qqq.backend.core.context.QContext;
|
||||
import com.kingsrook.qqq.backend.core.exceptions.QException;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.processes.RunBackendStepOutput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.count.CountInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QCriteriaOperator;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QFilterCriteria;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QQueryFilter;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.query.QueryInput;
|
||||
import com.kingsrook.qqq.backend.core.model.actions.tables.update.UpdateInput;
|
||||
import com.kingsrook.qqq.backend.core.model.data.QRecord;
|
||||
import com.kingsrook.qqq.backend.core.model.session.QSystemUserSession;
|
||||
import com.kingsrook.qqq.esb.connection.EsbConnectionManager;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
/** Exercise the assembled demo against its real local HTTP backend. */
|
||||
@Timeout(45)
|
||||
class RuntimeFeaturesTest
|
||||
{
|
||||
@TempDir
|
||||
Path directory;
|
||||
|
||||
@AfterEach
|
||||
void closeOwnedBrokerConnections()
|
||||
{
|
||||
EsbConnectionManager.getInstance().closeAll();
|
||||
}
|
||||
|
||||
@Test
|
||||
void apiCatalogQueriesGetsAndPaginates() throws Exception
|
||||
{
|
||||
try(CoreRuntime runtime = CoreRuntime.launch(directory, freePort()))
|
||||
{
|
||||
assertNotNull(runtime.getLauncher().getQInstance().getTable("apiCatalog"));
|
||||
QContext.init(runtime.getLauncher().getQInstance(), new QSystemUserSession());
|
||||
try
|
||||
{
|
||||
assertEquals(List.of(101, 102, 103), new QueryAction().execute(new QueryInput("apiCatalog")).getRecords()
|
||||
.stream().map(record -> record.getValueInteger("id")).toList());
|
||||
assertEquals(102, new QueryAction().execute(new QueryInput("apiCatalog")
|
||||
.withFilter(new QQueryFilter().withSkip(1).withLimit(1))).getRecords().getFirst().getValueInteger("id"));
|
||||
assertEquals("Shipping Box", GetAction.execute("apiCatalog", 103).getValueString("name"));
|
||||
assertNull(GetAction.execute("apiCatalog", 999));
|
||||
assertEquals(3, new CountAction().execute(new CountInput("apiCatalog")).getCount());
|
||||
var exactId = new QQueryFilter(new QFilterCriteria("id", QCriteriaOperator.EQUALS, 103));
|
||||
assertEquals(1, new CountAction().execute(new CountInput("apiCatalog").withFilter(exactId)).getCount());
|
||||
assertEquals(List.of(103), new QueryAction().execute(new QueryInput("apiCatalog").withFilter(exactId)).getRecords()
|
||||
.stream().map(record -> record.getValueInteger("id")).toList());
|
||||
assertThrows(QException.class, () -> new QueryAction().execute(new QueryInput("apiCatalog")
|
||||
.withFilter(new QQueryFilter(new QFilterCriteria("name", QCriteriaOperator.EQUALS, "Starter Kit")))));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculationUsesRealJavaScriptAndRequiresPermission() throws Exception
|
||||
{
|
||||
int port = freePort();
|
||||
try(CoreRuntime runtime = CoreRuntime.launch(directory, port); HttpClient client = HttpClient.newHttpClient())
|
||||
{
|
||||
assertNotNull(runtime.getLauncher().getQInstance().getProcess("calculateOrderTotal"));
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port
|
||||
+ "/processes/calculateOrderTotal/run?quantity=3&unitPriceCents=1250"))
|
||||
.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString("{}"));
|
||||
assertEquals(403, client.send(request.header("Cookie", "sessionId=" + DemoUsers.DEMO_SESSION).build(), HttpResponse.BodyHandlers.ofString()).statusCode());
|
||||
var allowed = client.send(request.setHeader("Cookie", "sessionId=" + DemoUsers.ADMIN_SESSION).build(), HttpResponse.BodyHandlers.ofString());
|
||||
assertEquals(200, allowed.statusCode(), allowed.body());
|
||||
assertEquals(3750, new org.json.JSONObject(allowed.body()).getJSONObject("values").getInt("totalCents"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void calculationRejectsMissingNegativeAndExcessiveInputs()
|
||||
{
|
||||
for(Integer quantity : java.util.Arrays.asList(null, 0, -1, 1001))
|
||||
{
|
||||
var input = new RunBackendStepInput().addValue("quantity", quantity).addValue("unitPriceCents", 1250);
|
||||
assertThrows(QException.class, () -> new CalculateOrderTotalStep().run(input, new RunBackendStepOutput()));
|
||||
}
|
||||
for(Integer price : java.util.Arrays.asList(null, -1, 1_000_001))
|
||||
{
|
||||
var input = new RunBackendStepInput().addValue("quantity", 3).addValue("unitPriceCents", price);
|
||||
assertThrows(QException.class, () -> new CalculateOrderTotalStep().run(input, new RunBackendStepOutput()));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void memoryNotesResetAcrossRuntimeRestart() throws Exception
|
||||
{
|
||||
try(CoreRuntime runtime = CoreRuntime.launch(directory, freePort()))
|
||||
{
|
||||
assertNotNull(runtime.getLauncher().getQInstance().getTable("demoNote"));
|
||||
QContext.init(runtime.getLauncher().getQInstance(), new QSystemUserSession());
|
||||
try
|
||||
{
|
||||
assertEquals("Transient demo note", GetAction.execute("demoNote", 1).getValueString("text"));
|
||||
new UpdateAction().execute(new UpdateInput("demoNote").withRecords(List.of(new QRecord().withValue("id", 1).withValue("text", "Only this run"))));
|
||||
assertEquals("Only this run", GetAction.execute("demoNote", 1).getValueString("text"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
closeOwnedBrokerConnections();
|
||||
try(CoreRuntime runtime = CoreRuntime.launch(directory, freePort()))
|
||||
{
|
||||
QContext.init(runtime.getLauncher().getQInstance(), new QSystemUserSession());
|
||||
try
|
||||
{
|
||||
assertEquals("Transient demo note", GetAction.execute("demoNote", 1).getValueString("text"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
QContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static int freePort() throws Exception
|
||||
{
|
||||
try(ServerSocket socket = new ServerSocket(0))
|
||||
{
|
||||
return socket.getLocalPort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright 2026 QRunIO, LLC
|
||||
~
|
||||
~ Licensed under the Apache License, Version 2.0 (the "License");
|
||||
~ you may not use this file except in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing, software
|
||||
~ distributed under the License is distributed on an "AS IS" BASIS,
|
||||
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
~ See the License for the specific language governing permissions and
|
||||
~ limitations under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qqq-all-bom-test</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>QQQ All - Stack BOM Test</name>
|
||||
<description>Resolves every artifact the stack BOM manages. Build-time check only; not published.</description>
|
||||
|
||||
<properties>
|
||||
<maven.deploy.skip>true</maven.deploy.skip>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-bom</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<!-- One versionless dependency per artifact the BOM manages, so resolving this -->
|
||||
<!-- module's test classpath resolves each of them. StackBomTest fails if one is missing. -->
|
||||
<dependencies>
|
||||
<!-- QQQ modules, qqq-esb, and qqq-frontend-next (from qqq-bom-pom) -->
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-core</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-rdbms</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-mongodb</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-filesystem</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-sqlite</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-backend-module-postgres</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-javalin</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-slack</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-api</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-openapi</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-picocli</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-lambda</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-middleware-health</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-language-support-javascript</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-utility-lambdas</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-esb</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-frontend-next</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- qBits -->
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-quick-search</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-user-role-permissions</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-customizable-table-views</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-standard-process-trace</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-webhooks</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-workflows</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-geo-data</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-sftp-data-integration</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- JDBC drivers -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.xerial</groupId>
|
||||
<artifactId>sqlite-jdbc</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Broker clients -->
|
||||
<dependency>
|
||||
<groupId>org.apache.artemis</groupId>
|
||||
<artifactId>artemis-jakarta-client</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.rabbitmq.jms</groupId>
|
||||
<artifactId>rabbitmq-jms</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Test framework (not part of the stack) -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>6.0.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- Writes the effective POM (BOM imports expanded) for StackBomTest to read. -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-help-plugin</artifactId>
|
||||
<version>3.5.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>effective-pom</id>
|
||||
<phase>generate-test-resources</phase>
|
||||
<goals>
|
||||
<goal>effective-pom</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<output>${project.build.directory}/effective-pom.xml</output>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,225 @@
|
||||
/*
|
||||
* Copyright 2026 QRunIO, LLC
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package com.kingsrook.qqq.all.bom;
|
||||
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import java.util.stream.Collectors;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Checks qqq-all-bom through this module's effective POM, which Maven writes
|
||||
** with the BOM imports expanded: the BOM manages the whole stack, and this
|
||||
** module depends on every stack artifact the BOM manages, so the build
|
||||
** resolves each one.
|
||||
*******************************************************************************/
|
||||
class StackBomTest
|
||||
{
|
||||
private static final Path EFFECTIVE_POM = Path.of("target", "effective-pom.xml");
|
||||
private static final Path BOM_POM = Path.of("..", "qqq-all-bom", "pom.xml");
|
||||
|
||||
private static List<Coordinate> managed;
|
||||
private static List<Coordinate> dependencies;
|
||||
private static List<Coordinate> bomDeclared;
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read the managed and declared dependencies from the effective POM.
|
||||
*******************************************************************************/
|
||||
@BeforeAll
|
||||
static void beforeAll() throws Exception
|
||||
{
|
||||
Element effectivePom = parse(EFFECTIVE_POM);
|
||||
managed = readDependencies(child(effectivePom, "dependencyManagement"));
|
||||
dependencies = readDependencies(effectivePom);
|
||||
|
||||
bomDeclared = readDependencies(child(parse(BOM_POM), "dependencyManagement")).stream()
|
||||
.filter(coordinate -> !"import".equals(coordinate.scope()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The BOM manages every artifact the qqq-all stack is built from.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testManagesTheStack()
|
||||
{
|
||||
Map<String, String> managedVersions = managed.stream().collect(Collectors.toMap(Coordinate::key, Coordinate::version));
|
||||
|
||||
List<String> required = List.of(
|
||||
"com.kingsrook.qqq:qqq-backend-core",
|
||||
"com.kingsrook.qqq:qqq-esb",
|
||||
"com.kingsrook.qqq:qqq-frontend-next",
|
||||
"com.kingsrook.qbits:qbit-quick-search",
|
||||
"com.kingsrook.qbits:qbit-user-role-permissions",
|
||||
"com.kingsrook.qbits:qbit-customizable-table-views",
|
||||
"com.kingsrook.qbits:qbit-standard-process-trace",
|
||||
"com.kingsrook.qbits:qbit-webhooks",
|
||||
"com.kingsrook.qbits:qbit-workflows",
|
||||
"com.kingsrook.qbits:qbit-geo-data",
|
||||
"com.kingsrook.qbits:qbit-sftp-data-integration",
|
||||
"org.postgresql:postgresql",
|
||||
"com.mysql:mysql-connector-j",
|
||||
"org.xerial:sqlite-jdbc",
|
||||
"com.h2database:h2",
|
||||
"org.apache.artemis:artemis-jakarta-client",
|
||||
"com.rabbitmq.jms:rabbitmq-jms");
|
||||
|
||||
List<String> missing = required.stream().filter(key -> !managedVersions.containsKey(key)).toList();
|
||||
assertEquals(List.of(), missing, "Artifacts the stack BOM does not manage");
|
||||
assertEquals("3.9.0", managedVersions.get("com.rabbitmq.jms:rabbitmq-jms"));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** This module depends on every stack artifact the BOM manages, so resolving
|
||||
** its test classpath resolves each one from the configured repositories.
|
||||
**
|
||||
** Stack artifacts are the managed com.kingsrook artifacts (qqq modules,
|
||||
** qqq-esb, qqq-frontend-next, qBits) plus everything qqq-all-bom declares
|
||||
** itself. The third-party entries qqq-bom-pom inherits from its parent
|
||||
** (Jackson, Netty, Jetty, and others) only align versions, so they are
|
||||
** resolved when something depends on them rather than here.
|
||||
*******************************************************************************/
|
||||
@Test
|
||||
void testDependsOnEveryStackArtifact()
|
||||
{
|
||||
Set<String> stack = managed.stream()
|
||||
.filter(coordinate -> coordinate.groupId().startsWith("com.kingsrook."))
|
||||
.map(Coordinate::key)
|
||||
.collect(Collectors.toCollection(TreeSet::new));
|
||||
bomDeclared.forEach(coordinate -> stack.add(coordinate.key()));
|
||||
|
||||
Set<String> declared = dependencies.stream().map(Coordinate::key).collect(Collectors.toSet());
|
||||
|
||||
List<String> notResolved = stack.stream().filter(key -> !declared.contains(key)).toList();
|
||||
assertEquals(List.of(), notResolved, "Stack artifacts missing from qqq-all-bom-test's dependencies, so the build does not resolve them");
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Parse a POM file and return its project element.
|
||||
*******************************************************************************/
|
||||
private static Element parse(Path pom) throws Exception
|
||||
{
|
||||
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(pom.toFile());
|
||||
return (document.getDocumentElement());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Read the dependency elements directly under parent's dependencies element.
|
||||
*******************************************************************************/
|
||||
private static List<Coordinate> readDependencies(Element parent)
|
||||
{
|
||||
List<Coordinate> coordinates = new ArrayList<>();
|
||||
for(Element dependency : children(child(parent, "dependencies"), "dependency"))
|
||||
{
|
||||
coordinates.add(new Coordinate(
|
||||
text(dependency, "groupId", null),
|
||||
text(dependency, "artifactId", null),
|
||||
text(dependency, "version", null),
|
||||
text(dependency, "type", "jar"),
|
||||
text(dependency, "classifier", ""),
|
||||
text(dependency, "scope", "compile")));
|
||||
}
|
||||
return (coordinates);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The single child element with the given name.
|
||||
*******************************************************************************/
|
||||
private static Element child(Element parent, String name)
|
||||
{
|
||||
List<Element> matches = children(parent, name);
|
||||
assertEquals(1, matches.size(), "Expected one <" + name + "> under <" + parent.getTagName() + ">");
|
||||
return (matches.get(0));
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** The child elements with the given name (direct children only, so plugin
|
||||
** dependencies are not mistaken for project dependencies).
|
||||
*******************************************************************************/
|
||||
private static List<Element> children(Element parent, String name)
|
||||
{
|
||||
List<Element> matches = new ArrayList<>();
|
||||
for(Node node = parent.getFirstChild(); node != null; node = node.getNextSibling())
|
||||
{
|
||||
if(node instanceof Element element && element.getTagName().equals(name))
|
||||
{
|
||||
matches.add(element);
|
||||
}
|
||||
}
|
||||
return (matches);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** Text of the named child element, or defaultValue when it is absent.
|
||||
*******************************************************************************/
|
||||
private static String text(Element parent, String name, String defaultValue)
|
||||
{
|
||||
List<Element> matches = children(parent, name);
|
||||
return (matches.isEmpty() ? defaultValue : matches.get(0).getTextContent().trim());
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*******************************************************************************
|
||||
** A dependency coordinate; key() is how Maven matches a dependency to its
|
||||
** managed entry.
|
||||
*******************************************************************************/
|
||||
private record Coordinate(String groupId, String artifactId, String version, String type, String classifier, String scope)
|
||||
{
|
||||
/***************************************************************************
|
||||
**
|
||||
***************************************************************************/
|
||||
String key()
|
||||
{
|
||||
String key = groupId + ":" + artifactId;
|
||||
if(!type.equals("jar") || !classifier.isEmpty())
|
||||
{
|
||||
key += ":" + type + (classifier.isEmpty() ? "" : ":" + classifier);
|
||||
}
|
||||
return (key);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-all-parent</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>qqq-all-bom</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>QQQ All - Stack BOM</name>
|
||||
<description>One tested version set for QQQ, the ESB, the Next dashboard, the included qBits, JDBC drivers, and broker clients.</description>
|
||||
|
||||
<properties>
|
||||
<qqq.version>4.1.0-SNAPSHOT</qqq.version>
|
||||
|
||||
<!-- qBits: develop builds on qbit-build-parent 2.0.0; none has a release on that parent yet. -->
|
||||
<qbit-quick-search.version>0.2.1-SNAPSHOT</qbit-quick-search.version>
|
||||
<qbit-user-role-permissions.version>0.33.0-SNAPSHOT</qbit-user-role-permissions.version>
|
||||
<qbit-customizable-table-views.version>0.5.0-SNAPSHOT</qbit-customizable-table-views.version>
|
||||
<qbit-standard-process-trace.version>0.3.0-SNAPSHOT</qbit-standard-process-trace.version>
|
||||
<qbit-webhooks.version>0.4.0-SNAPSHOT</qbit-webhooks.version>
|
||||
<qbit-workflows.version>0.114.0-SNAPSHOT</qbit-workflows.version>
|
||||
<qbit-geo-data.version>0.2.0-SNAPSHOT</qbit-geo-data.version>
|
||||
<qbit-sftp-data-integration.version>0.4.0-SNAPSHOT</qbit-sftp-data-integration.version>
|
||||
|
||||
<!-- The versions qqq 4.1 builds and tests its backend modules and qqq-esb with. -->
|
||||
<postgresql.version>42.7.12</postgresql.version>
|
||||
<mysql-connector-j.version>9.5.0</mysql-connector-j.version>
|
||||
<sqlite-jdbc.version>3.51.1.0</sqlite-jdbc.version>
|
||||
<h2.version>2.4.240</h2.version>
|
||||
<artemis.version>2.57.0</artemis.version>
|
||||
<rabbitmq-jms.version>3.9.0</rabbitmq-jms.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<!-- QQQ modules, qqq-esb, and qqq-frontend-next. -->
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qqq</groupId>
|
||||
<artifactId>qqq-bom-pom</artifactId>
|
||||
<version>${qqq.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- qBits -->
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-quick-search</artifactId>
|
||||
<version>${qbit-quick-search.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-user-role-permissions</artifactId>
|
||||
<version>${qbit-user-role-permissions.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-customizable-table-views</artifactId>
|
||||
<version>${qbit-customizable-table-views.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-standard-process-trace</artifactId>
|
||||
<version>${qbit-standard-process-trace.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-webhooks</artifactId>
|
||||
<version>${qbit-webhooks.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-workflows</artifactId>
|
||||
<version>${qbit-workflows.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-geo-data</artifactId>
|
||||
<version>${qbit-geo-data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.kingsrook.qbits</groupId>
|
||||
<artifactId>qbit-sftp-data-integration</artifactId>
|
||||
<version>${qbit-sftp-data-integration.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- JDBC drivers -->
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${postgresql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>${mysql-connector-j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.xerial</groupId>
|
||||
<artifactId>sqlite-jdbc</artifactId>
|
||||
<version>${sqlite-jdbc.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Broker clients for qqq-esb -->
|
||||
<dependency>
|
||||
<groupId>org.apache.artemis</groupId>
|
||||
<artifactId>artemis-jakarta-client</artifactId>
|
||||
<version>${artemis.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.rabbitmq.jms</groupId>
|
||||
<artifactId>rabbitmq-jms</artifactId>
|
||||
<version>${rabbitmq-jms.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,16 @@
|
||||
services:
|
||||
app-full:
|
||||
environment:
|
||||
QQQ_ALL_OPENSEARCH_HOST: opensearch
|
||||
rabbitmq:
|
||||
ports: !override
|
||||
- "127.0.0.1::15672"
|
||||
artemis:
|
||||
ports: !override
|
||||
- "127.0.0.1::8161"
|
||||
mailpit:
|
||||
ports: !override
|
||||
- "127.0.0.1::8025"
|
||||
minio:
|
||||
ports: !override
|
||||
- "127.0.0.1::9001"
|
||||
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Start the packaged core jar, smoke its HTTP API, and always stop it."""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from smoke import CORE_ADMIN_SESSION, SmokeClient, check_core
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", 0))
|
||||
return listener.getsockname()[1]
|
||||
|
||||
|
||||
def await_health(client, process, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise AssertionError("packaged app exited before becoming healthy")
|
||||
try:
|
||||
if client.json("/health").get("status") == "UP":
|
||||
return
|
||||
except (AssertionError, OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise AssertionError("timed out waiting for packaged app health")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("jar", type=Path)
|
||||
parser.add_argument("--timeout", type=int, default=90)
|
||||
args = parser.parse_args()
|
||||
if not args.jar.is_file():
|
||||
raise AssertionError("packaged jar was not found")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="qqq-all-core-smoke-") as directory:
|
||||
port = free_port()
|
||||
environment = os.environ.copy()
|
||||
environment.update({
|
||||
"QQQ_ALL_PROFILE": "core",
|
||||
"QQQ_ALL_PORT": str(port),
|
||||
"QQQ_ALL_DATA_DIR": str(Path(directory) / "data"),
|
||||
})
|
||||
with (Path(directory) / "app.log").open("wb") as output:
|
||||
process = subprocess.Popen(
|
||||
["java", "-jar", str(args.jar.resolve())],
|
||||
env=environment, stdout=output, stderr=subprocess.STDOUT,
|
||||
)
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{port}", CORE_ADMIN_SESSION)
|
||||
await_health(client, process, args.timeout)
|
||||
check_core(client, args.timeout)
|
||||
if process.poll() is not None:
|
||||
raise AssertionError("packaged app exited during smoke checks")
|
||||
finally:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait(timeout=10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ValueError) as error:
|
||||
print(f"core smoke failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Boot a private full Compose stack, run HTTP smoke checks, and remove it."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
from smoke import check_full
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def free_port(exclude=()):
|
||||
for _ in range(30):
|
||||
port = 20000 + secrets.randbelow(10000)
|
||||
if port in exclude:
|
||||
continue
|
||||
try:
|
||||
with socket.socket() as listener:
|
||||
listener.bind(("127.0.0.1", port))
|
||||
return port
|
||||
except OSError:
|
||||
continue
|
||||
raise AssertionError("could not reserve a full smoke host port")
|
||||
|
||||
|
||||
def demo_environment():
|
||||
values = {}
|
||||
for line in (ROOT / ".env.example").read_text().splitlines():
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
if "PASSWORD" in key or "SECRET" in key or key == "MONGO_KEYFILE":
|
||||
value = secrets.token_urlsafe(24)
|
||||
values[key] = value
|
||||
app_port = free_port()
|
||||
values["QQQ_ALL_PORT"] = str(app_port)
|
||||
values["KEYCLOAK_PORT"] = str(free_port((app_port,)))
|
||||
return values
|
||||
|
||||
|
||||
def published_port(command, service, target, environment):
|
||||
result = subprocess.run(command + ["port", service, str(target)],
|
||||
cwd=ROOT, env=environment, capture_output=True, text=True,
|
||||
timeout=15, check=False)
|
||||
if result.returncode:
|
||||
raise AssertionError(f"could not discover {service} host port")
|
||||
address = result.stdout.strip()
|
||||
if not address.startswith("127.0.0.1:") or not address.rsplit(":", 1)[1].isdigit():
|
||||
raise AssertionError(f"unexpected {service} host port")
|
||||
return int(address.rsplit(":", 1)[1])
|
||||
|
||||
|
||||
def query_opensearch(command, environment, index_name, query):
|
||||
url = ("http://127.0.0.1:9200/" + urllib.parse.quote(index_name, safe="")
|
||||
+ "/_search")
|
||||
result = subprocess.run(
|
||||
command + ["exec", "-T", "opensearch", "curl", "--fail", "--silent",
|
||||
"--show-error", "--max-time", "5", "-H", "Content-Type: application/json",
|
||||
"--data-binary", json.dumps(query), url],
|
||||
cwd=ROOT, env=environment, capture_output=True, text=True, timeout=15, check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError("OpenSearch query failed inside Compose")
|
||||
try:
|
||||
return json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise AssertionError("OpenSearch returned invalid JSON") from None
|
||||
|
||||
|
||||
def prepare_sftp_import_directory(command, environment, username):
|
||||
path = f"/home/{username}/upload/imports"
|
||||
for args in (["mkdir", "-p", path], ["chown", "1001:1001", path]):
|
||||
result = subprocess.run(
|
||||
command + ["exec", "-T", "sftp"] + args,
|
||||
cwd=ROOT, env=environment, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
timeout=15, check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise AssertionError("could not prepare SFTP import directory")
|
||||
|
||||
|
||||
def main():
|
||||
if not (ROOT / "compose.yaml").is_file():
|
||||
raise AssertionError("C6 Compose is not integrated into this branch")
|
||||
values = demo_environment()
|
||||
project = "qqqallsmoke" + secrets.token_hex(4)
|
||||
environment = os.environ.copy()
|
||||
environment.update(values)
|
||||
os.environ.update(values)
|
||||
with tempfile.TemporaryDirectory(prefix="qqq-all-full-smoke-") as directory:
|
||||
env_file = Path(directory) / "compose.env"
|
||||
env_file.write_text("".join(f"{key}={value}\n" for key, value in values.items()))
|
||||
env_file.chmod(0o600)
|
||||
command = ["docker", "compose", "-p", project, "--env-file", str(env_file),
|
||||
"-f", str(ROOT / "compose.yaml"), "-f", str(ROOT / "scripts/compose.smoke.yaml"),
|
||||
"--profile", "full"]
|
||||
try:
|
||||
started = subprocess.run(command + ["up", "-d", "--build", "--wait", "--wait-timeout", "360"],
|
||||
cwd=ROOT, env=environment, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=480, check=False)
|
||||
if started.returncode:
|
||||
raise AssertionError("full Compose stack did not become healthy")
|
||||
prepare_sftp_import_directory(command, environment, values.get("SFTP_USER", "qqq"))
|
||||
check_full(
|
||||
f"http://127.0.0.1:{values['QQQ_ALL_PORT']}",
|
||||
f"http://keycloak.localhost:{values['KEYCLOAK_PORT']}/realms/qqq-all",
|
||||
lambda index, query: query_opensearch(command, environment, index, query),
|
||||
120,
|
||||
)
|
||||
finally:
|
||||
subprocess.run(command + ["down", "--volumes", "--remove-orphans"],
|
||||
cwd=ROOT, env=environment, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=120, check=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ValueError, subprocess.TimeoutExpired) as error:
|
||||
print(f"full smoke failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,375 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box HTTP smoke checks for the qqq-all reference application."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import html.parser
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
CORE_TABLES = ("customer", "order", "orderLine", "product")
|
||||
CORE_SEEDS = (
|
||||
("customer", "name", "Ada Lovelace"),
|
||||
("order", "orderNo", "ORD-1001"),
|
||||
("orderLine", "quantity", 2),
|
||||
("product", "name", "QRun Starter Kit"),
|
||||
)
|
||||
FULL_TABLES = CORE_TABLES + (
|
||||
"warehouseCustomer", "supplierOrder", "shipment", "document", "externalImportFile",
|
||||
"SFTPImportSourceFileTable",
|
||||
)
|
||||
CORE_ADMIN_SESSION = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
|
||||
|
||||
|
||||
class LoginForm(html.parser.HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.action = None
|
||||
self.values = {}
|
||||
self.inside = False
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
values = dict(attrs)
|
||||
if tag == "form" and values.get("id") == "kc-form-login":
|
||||
self.action = values.get("action")
|
||||
self.inside = True
|
||||
elif tag == "input" and self.inside and values.get("name"):
|
||||
self.values[values["name"]] = values.get("value", "")
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
if tag == "form":
|
||||
self.inside = False
|
||||
|
||||
|
||||
class StopAtCallback(urllib.request.HTTPRedirectHandler):
|
||||
def __init__(self, callback):
|
||||
self.callback = callback
|
||||
|
||||
def redirect_request(self, request, fp, code, msg, headers, url):
|
||||
if url.startswith(self.callback + "?"):
|
||||
return None
|
||||
return super().redirect_request(request, fp, code, msg, headers, url)
|
||||
|
||||
|
||||
def wait_for(label, predicate, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if predicate():
|
||||
return
|
||||
except (OSError, TimeoutError, AssertionError, ValueError):
|
||||
pass
|
||||
time.sleep(0.25)
|
||||
raise AssertionError(f"timed out waiting for {label}")
|
||||
|
||||
|
||||
class SmokeClient:
|
||||
def __init__(self, base_url, session_id=None):
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.session_id = session_id
|
||||
self.cookies = http.cookiejar.CookieJar()
|
||||
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies))
|
||||
|
||||
def request(self, path, body=None, method=None, expected_status=200):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
headers = {"Content-Type": "application/json"} if data is not None else {}
|
||||
if self.session_id:
|
||||
headers["Cookie"] = "sessionId=" + self.session_id
|
||||
request = urllib.request.Request(
|
||||
self.base_url + path, data=data, method=method,
|
||||
headers=headers,
|
||||
)
|
||||
try:
|
||||
with self.opener.open(request, timeout=5) as response:
|
||||
if response.status != expected_status:
|
||||
raise AssertionError(f"{path}: HTTP {response.status}")
|
||||
return response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
status = error.code
|
||||
try:
|
||||
if status == expected_status:
|
||||
return error.read()
|
||||
finally:
|
||||
error.close()
|
||||
raise AssertionError(f"{path}: HTTP {status}") from None
|
||||
|
||||
def json(self, path, body=None):
|
||||
return json.loads(self.request(path, body))
|
||||
|
||||
def records(self, table):
|
||||
result = self.json(f"/qqq/v1/table/{table}/query", {})
|
||||
records = result.get("records")
|
||||
if not isinstance(records, list):
|
||||
raise AssertionError(f"{table}: query did not return records")
|
||||
return records
|
||||
|
||||
def require_record(self, table, field, value):
|
||||
if not any(record.get("values", {}).get(field) == value for record in self.records(table)):
|
||||
raise AssertionError(f"missing expected {table} {field}")
|
||||
|
||||
|
||||
def allow_loopback_http_session(client):
|
||||
parsed = urllib.parse.urlsplit(client.base_url)
|
||||
if parsed.scheme != "http" or parsed.hostname not in ("127.0.0.1", "localhost"):
|
||||
raise AssertionError("OIDC HTTP cookie adjustment requires a loopback app")
|
||||
cookies = [cookie for cookie in client.cookies if cookie.name == "sessionUUID"]
|
||||
if len(cookies) != 1:
|
||||
raise AssertionError("OIDC did not set exactly one session cookie")
|
||||
if cookies[0].secure:
|
||||
cookies[0].secure = False
|
||||
|
||||
|
||||
def allow_loopback_http_cookies(cookies, url):
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
host = parsed.hostname or ""
|
||||
if parsed.scheme != "http" or not (host in ("127.0.0.1", "localhost")
|
||||
or host.endswith(".localhost")):
|
||||
raise AssertionError("OIDC HTTP cookie adjustment requires a loopback host")
|
||||
for cookie in cookies:
|
||||
if cookie.secure and cookie.domain.lstrip(".") == host:
|
||||
cookie.secure = False
|
||||
|
||||
|
||||
def check_health_and_dashboard(client, timeout):
|
||||
wait_for("health", lambda: client.json("/health").get("status") == "UP", timeout)
|
||||
html = client.request("/").decode()
|
||||
match = re.search(r'["\'](/_next/static/[^"\']+\.(?:js|css))["\']', html)
|
||||
if not match:
|
||||
raise AssertionError("dashboard did not reference a Next asset")
|
||||
if not client.request(match.group(1)):
|
||||
raise AssertionError("Next asset was empty")
|
||||
print("health and Next asset: OK")
|
||||
|
||||
|
||||
def check_tables(client, tables, require_seed=True):
|
||||
for table in tables:
|
||||
records = client.records(table)
|
||||
if require_seed and not records:
|
||||
raise AssertionError(f"{table}: no seeded records")
|
||||
if require_seed:
|
||||
for table, field, value in CORE_SEEDS:
|
||||
client.require_record(table, field, value)
|
||||
else:
|
||||
client.require_record("customer", "name", "Ada Lovelace")
|
||||
print("backend table queries: OK")
|
||||
|
||||
|
||||
def trigger_order(client):
|
||||
before = {record.get("values", {}).get("id") for record in client.records("processTrace")}
|
||||
marker = "SMOKE-" + uuid.uuid4().hex[:12]
|
||||
response = client.json("/data/order/", {
|
||||
"orderNo": marker, "customerId": 1, "status": "NEW"
|
||||
})
|
||||
inserted = response.get("records", [])
|
||||
order_id = inserted[0].get("values", {}).get("id") if inserted else None
|
||||
if not order_id:
|
||||
raise AssertionError("order insert did not return an ID")
|
||||
return before, order_id, marker
|
||||
|
||||
|
||||
def check_artemis_round_trip(client, timeout):
|
||||
before, order_id, marker = trigger_order(client)
|
||||
process_uuid = None
|
||||
|
||||
def new_sync_trace():
|
||||
nonlocal process_uuid
|
||||
for record in client.records("processTrace"):
|
||||
values = record.get("values", {})
|
||||
if (values.get("id") not in before
|
||||
and record.get("recordLabel", "").startswith("Sync Order -")
|
||||
and values.get("keyRecordId") == order_id
|
||||
and values.get("processUUID")):
|
||||
process_uuid = values["processUUID"]
|
||||
return True
|
||||
return False
|
||||
|
||||
wait_for("Artemis syncOrder trace",
|
||||
new_sync_trace, timeout)
|
||||
client.require_record("order", "orderNo", marker)
|
||||
print("Artemis order event round trip: OK")
|
||||
return process_uuid
|
||||
|
||||
|
||||
def check_runtime_features(client, can_calculate=True):
|
||||
records = client.records("apiCatalog")
|
||||
if [record.get("values", {}).get("id") for record in records] != [101, 102, 103]:
|
||||
raise AssertionError("API catalog did not traverse all pages")
|
||||
record = client.json("/data/apiCatalog/103")
|
||||
if record.get("values", {}).get("name") != "Shipping Box":
|
||||
raise AssertionError("API catalog get returned incorrect record")
|
||||
client.require_record("demoNote", "text", "Transient demo note")
|
||||
path = "/processes/calculateOrderTotal/run?quantity=3&unitPriceCents=1250"
|
||||
if can_calculate:
|
||||
result = client.json(path, {})
|
||||
if result.get("values", {}).get("totalCents") != 3750:
|
||||
raise AssertionError("JavaScript calculation returned incorrect total")
|
||||
else:
|
||||
client.request(path, {}, expected_status=403)
|
||||
client.request("/data/demoNote/1", {"text": "forbidden"}, method="PATCH", expected_status=403)
|
||||
client.request("/data/apiCatalog/", {"id": 999, "name": "forbidden"}, expected_status=403)
|
||||
print("API catalog, transient memory, JavaScript permissions: OK")
|
||||
|
||||
|
||||
def check_core(client, timeout):
|
||||
check_health_and_dashboard(client, timeout)
|
||||
check_tables(client, CORE_TABLES)
|
||||
check_runtime_features(client)
|
||||
check_runtime_features(SmokeClient(client.base_url, "dddddddd-dddd-4ddd-8ddd-dddddddddddd"), False)
|
||||
check_artemis_round_trip(client, timeout)
|
||||
|
||||
|
||||
def oidc_login(client, keycloak_url, username, password):
|
||||
"""Complete the browser authorization-code flow and establish a QQQ cookie."""
|
||||
try:
|
||||
discovery_url = keycloak_url.rstrip("/") + "/.well-known/openid-configuration"
|
||||
with urllib.request.urlopen(discovery_url, timeout=5) as response:
|
||||
authorization_endpoint = json.load(response)["authorization_endpoint"]
|
||||
verifier = secrets.token_urlsafe(48)
|
||||
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
|
||||
state = secrets.token_urlsafe(24)
|
||||
callback = client.base_url + "/"
|
||||
query = urllib.parse.urlencode({
|
||||
"client_id": "qqq-all", "response_type": "code", "scope": "openid email profile",
|
||||
"redirect_uri": callback, "state": state, "code_challenge": challenge,
|
||||
"code_challenge_method": "S256",
|
||||
})
|
||||
browser_cookies = http.cookiejar.CookieJar()
|
||||
browser = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(browser_cookies), StopAtCallback(callback)
|
||||
)
|
||||
with browser.open(authorization_endpoint + "?" + query, timeout=10) as response:
|
||||
form = LoginForm()
|
||||
form.feed(response.read().decode())
|
||||
if not form.action:
|
||||
raise AssertionError("Keycloak login form missing")
|
||||
if urllib.parse.urlsplit(authorization_endpoint).scheme == "http":
|
||||
allow_loopback_http_cookies(browser_cookies, authorization_endpoint)
|
||||
form.values.update({"username": username, "password": password})
|
||||
request = urllib.request.Request(form.action, data=urllib.parse.urlencode(form.values).encode())
|
||||
try:
|
||||
with browser.open(request, timeout=10) as response:
|
||||
raise AssertionError(f"Keycloak did not redirect after login (HTTP {response.status})")
|
||||
except urllib.error.HTTPError as response:
|
||||
if response.code not in (302, 303):
|
||||
status = response.code
|
||||
response.close()
|
||||
raise AssertionError(f"Keycloak rejected the login (HTTP {status})") from None
|
||||
location = response.headers.get("Location", "")
|
||||
response.close()
|
||||
parameters = urllib.parse.parse_qs(urllib.parse.urlsplit(location).query)
|
||||
if parameters.get("state") != [state] or not parameters.get("code"):
|
||||
raise AssertionError("OIDC callback did not contain a valid code and state")
|
||||
result = client.json("/manageSession", {
|
||||
"code": parameters["code"][0], "redirectUri": callback, "codeVerifier": verifier
|
||||
})
|
||||
if not result.get("uuid") or not any(cookie.name == "sessionUUID" for cookie in client.cookies):
|
||||
raise AssertionError("QQQ did not establish an OIDC session")
|
||||
if urllib.parse.urlsplit(client.base_url).scheme == "http":
|
||||
allow_loopback_http_session(client)
|
||||
except (OSError, KeyError, ValueError, urllib.error.HTTPError) as error:
|
||||
raise AssertionError("OIDC login did not complete") from None
|
||||
print(f"OIDC {username} login: OK")
|
||||
|
||||
|
||||
def http_query_index(search_url, index_name, query):
|
||||
request = urllib.request.Request(
|
||||
search_url.rstrip("/") + "/" + urllib.parse.quote(index_name, safe="") + "/_search",
|
||||
data=json.dumps(query).encode(), headers={"Content-Type": "application/json"},
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=5) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def check_quick_search(client, query_index, index_name, timeout):
|
||||
result = client.json("/processes/quickSearchFullReindex/run", {})
|
||||
if result.get("exception"):
|
||||
raise AssertionError("quick-search reindex failed")
|
||||
|
||||
def finds_customer():
|
||||
query = {"query": {"bool": {"must": {"match": {"searchableText": "Ada"}},
|
||||
"filter": {"term": {"sourceTable": "customer"}}}}}
|
||||
hits = query_index(index_name, query)["hits"]["hits"]
|
||||
return any("Ada Lovelace" in json.dumps(hit.get("_source", {})) for hit in hits)
|
||||
|
||||
wait_for("quick search seeded customer", finds_customer, timeout)
|
||||
print("OpenSearch customer quick search: OK")
|
||||
|
||||
|
||||
def check_rabbitmq(client, timeout, process_uuid):
|
||||
def message_arrived():
|
||||
offset = 0
|
||||
while True:
|
||||
suffix = "" if offset == 0 else f"?offset={offset}"
|
||||
page = client.json("/qqq/v1/esb/messages/orderSyncEvents" + suffix)
|
||||
messages = page.get("messages", [])
|
||||
for message in messages:
|
||||
event = message.get("event")
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
data = event.get("data")
|
||||
if (event.get("type") == "qqq.process.syncOrder.completed"
|
||||
and isinstance(data, dict)
|
||||
and data.get("processName") == "syncOrder"
|
||||
and data.get("processUUID") == process_uuid):
|
||||
return True
|
||||
if not page.get("hasMore"):
|
||||
return False
|
||||
if not messages:
|
||||
raise ValueError("ESB browse returned an empty page with more messages")
|
||||
offset += len(messages)
|
||||
|
||||
wait_for("RabbitMQ syncOrder completion", message_arrived, timeout)
|
||||
print("RabbitMQ completion publication: OK")
|
||||
|
||||
|
||||
def check_full(base_url, keycloak_url, query_index, timeout):
|
||||
viewer = SmokeClient(base_url)
|
||||
check_health_and_dashboard(viewer, timeout)
|
||||
oidc_login(viewer, keycloak_url, "demo-user", os.environ["DEMO_USER_PASSWORD"])
|
||||
viewer.require_record("customer", "name", "Ada Lovelace")
|
||||
check_runtime_features(viewer, False)
|
||||
admin = SmokeClient(base_url)
|
||||
oidc_login(admin, keycloak_url, "demo-admin", os.environ["DEMO_ADMIN_PASSWORD"])
|
||||
check_tables(admin, FULL_TABLES, require_seed=False)
|
||||
check_runtime_features(admin)
|
||||
check_quick_search(admin, query_index, os.environ.get("QQQ_ALL_OPENSEARCH_INDEX", "qqq-all-customers"), timeout)
|
||||
process_uuid = check_artemis_round_trip(admin, timeout)
|
||||
check_rabbitmq(admin, timeout, process_uuid)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("profile", choices=("core", "full"))
|
||||
parser.add_argument("--base-url", default="http://127.0.0.1:8080")
|
||||
parser.add_argument("--timeout", type=int, default=90)
|
||||
parser.add_argument("--keycloak-url", default="http://keycloak.localhost:8081/realms/qqq-all")
|
||||
parser.add_argument("--opensearch-url")
|
||||
args = parser.parse_args()
|
||||
client = SmokeClient(args.base_url, CORE_ADMIN_SESSION if args.profile == "core" else None)
|
||||
if args.profile == "core":
|
||||
check_core(client, args.timeout)
|
||||
else:
|
||||
if not args.opensearch_url:
|
||||
raise AssertionError("full profile needs --opensearch-url; use run_full_smoke.py for private Compose")
|
||||
check_full(args.base_url, args.keycloak_url,
|
||||
lambda index, query: http_query_index(args.opensearch_url, index, query),
|
||||
args.timeout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ValueError, KeyError) as error:
|
||||
print(f"smoke failed: {error}", file=sys.stderr)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,522 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Contract tests for the HTTP smoke checks, without starting the application."""
|
||||
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import socketserver
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import xml.etree.ElementTree as ET
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from smoke import SmokeClient, check_artemis_round_trip, check_core, check_rabbitmq, check_tables, check_runtime_features, CORE_TABLES
|
||||
import run_full_smoke
|
||||
from run_full_smoke import ROOT
|
||||
|
||||
|
||||
class SmokeServer(ThreadingHTTPServer):
|
||||
def server_bind(self):
|
||||
socketserver.TCPServer.server_bind(self)
|
||||
self.server_name = "localhost"
|
||||
self.server_port = self.server_address[1]
|
||||
|
||||
|
||||
class DemoHandler(BaseHTTPRequestHandler):
|
||||
orders = 0
|
||||
product_name = "QRun Starter Kit"
|
||||
trace_label = "Sync Order - demo"
|
||||
trace_order_id = None
|
||||
inserted_marker = None
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.path == "/data/apiCatalog/103":
|
||||
return self.send_json({"values": {"id": 103, "name": "Shipping Box"}})
|
||||
if self.path == "/health":
|
||||
return self.send_json({"status": "UP"})
|
||||
if self.path == "/":
|
||||
body = b'<html><script src="/_next/static/chunks/demo.js"></script></html>'
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
if self.path == "/_next/static/chunks/demo.js":
|
||||
body = b"console.log('demo');"
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
return
|
||||
self.send_error(404)
|
||||
|
||||
def do_POST(self):
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
if self.path == "/data/apiCatalog/":
|
||||
return self.send_error(403)
|
||||
if self.path.startswith("/processes/calculateOrderTotal/run"):
|
||||
if "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa" not in self.headers.get("Cookie", ""):
|
||||
return self.send_error(403)
|
||||
return self.send_json({"values": {"totalCents": 3750}})
|
||||
if self.path == "/data/order/":
|
||||
assert body["orderNo"].startswith("SMOKE-")
|
||||
type(self).orders += 1
|
||||
type(self).trace_order_id = 100 + self.orders
|
||||
type(self).inserted_marker = body["orderNo"]
|
||||
return self.send_json({"records": [{"values": {"id": 100 + self.orders}}]})
|
||||
if self.path.startswith("/qqq/v1/table/") and self.path.endswith("/query"):
|
||||
table = self.path.split("/")[4]
|
||||
if table == "apiCatalog":
|
||||
return self.send_json({"records": [{"values": {"id": i}} for i in (101, 102, 103)]})
|
||||
if table == "processTrace":
|
||||
records = [{"recordLabel": self.trace_label,
|
||||
"values": {"id": i, "processUUID": f"trace-{i}",
|
||||
"keyRecordId": self.trace_order_id}}
|
||||
for i in range(self.orders)]
|
||||
else:
|
||||
values = {
|
||||
"demoNote": {"id": 1, "text": "Transient demo note"},
|
||||
"customer": {"id": 1, "name": "Ada Lovelace"},
|
||||
"order": {"id": 1, "orderNo": "ORD-1001"},
|
||||
"orderLine": {"id": 1, "quantity": 2},
|
||||
"product": {"id": 1, "name": self.product_name},
|
||||
}
|
||||
records = [{"values": values.get(table, {"id": 1})}]
|
||||
if table == "order" and self.inserted_marker:
|
||||
records.append({"values": {"id": 100 + self.orders,
|
||||
"orderNo": self.inserted_marker}})
|
||||
return self.send_json({"records": records})
|
||||
self.send_error(404)
|
||||
|
||||
def do_PATCH(self):
|
||||
if self.path == "/data/demoNote/1":
|
||||
return self.send_error(403)
|
||||
self.send_error(404)
|
||||
|
||||
def send_json(self, value):
|
||||
data = json.dumps(value).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
class SmokeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
DemoHandler.orders = 0
|
||||
DemoHandler.trace_order_id = None
|
||||
DemoHandler.inserted_marker = None
|
||||
|
||||
def test_catalog_missing_final_page_fails(self):
|
||||
client = mock.Mock()
|
||||
client.records.return_value = [{"values": {"id": value}} for value in (101, 102)]
|
||||
with self.assertRaisesRegex(AssertionError, "all pages"):
|
||||
check_runtime_features(client)
|
||||
|
||||
def test_wrong_javascript_result_fails(self):
|
||||
client = mock.Mock()
|
||||
client.records.return_value = [{"values": {"id": value}} for value in (101, 102, 103)]
|
||||
client.json.side_effect = [{"values": {"name": "Shipping Box"}}, {"values": {"totalCents": 3749}}]
|
||||
with self.assertRaisesRegex(AssertionError, "incorrect total"):
|
||||
check_runtime_features(client)
|
||||
|
||||
def test_core_runner_fails_promptly_when_jar_exits(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
jar = Path(directory) / "broken.jar"
|
||||
jar.write_bytes(b"not a jar")
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).with_name("run_core_smoke.py")),
|
||||
str(jar), "--timeout", "1"], capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn("packaged app exited", result.stderr)
|
||||
|
||||
def test_ci_core_smokes_maven_final_artifact(self):
|
||||
pom = ET.parse(ROOT / "qqq-all-app" / "pom.xml")
|
||||
final_name = pom.findtext(".//{http://maven.apache.org/POM/4.0.0}build/"
|
||||
"{http://maven.apache.org/POM/4.0.0}finalName")
|
||||
workflow = (ROOT / ".github" / "workflows" / "smoke.yml").read_text()
|
||||
command = re.search(r"run: python3 scripts/run_core_smoke.py (\S+)", workflow)
|
||||
self.assertIsNotNone(command)
|
||||
self.assertEqual(f"qqq-all-app/target/{final_name}.jar", command.group(1))
|
||||
|
||||
def test_standalone_full_smoke_requires_explicit_search_endpoint(self):
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(Path(__file__).with_name("smoke.py")), "full",
|
||||
"--base-url", "http://127.0.0.1:1"],
|
||||
capture_output=True, text=True, timeout=5,
|
||||
)
|
||||
self.assertEqual(1, result.returncode)
|
||||
self.assertIn("run_full_smoke.py", result.stderr)
|
||||
|
||||
def test_full_runner_reserves_distinct_non_ephemeral_app_ports(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / ".env.example").write_text(
|
||||
"QQQ_ALL_PORT=8080\nKEYCLOAK_PORT=8081\nPOSTGRES_PASSWORD=example\n")
|
||||
with mock.patch.object(run_full_smoke, "ROOT", root):
|
||||
values = run_full_smoke.demo_environment()
|
||||
app_port = int(values["QQQ_ALL_PORT"])
|
||||
keycloak_port = int(values["KEYCLOAK_PORT"])
|
||||
self.assertTrue(20000 <= app_port < 30000)
|
||||
self.assertTrue(20000 <= keycloak_port < 30000)
|
||||
self.assertNotEqual(app_port, keycloak_port)
|
||||
self.assertNotEqual("example", values["POSTGRES_PASSWORD"])
|
||||
|
||||
def test_full_runner_supplies_generated_credentials_to_http_checks(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "compose.yaml").write_text("services: {}\n")
|
||||
values = {"QQQ_ALL_PORT": "20001", "KEYCLOAK_PORT": "20002",
|
||||
"DEMO_USER_PASSWORD": "generated-user",
|
||||
"DEMO_ADMIN_PASSWORD": "generated-admin",
|
||||
"RABBITMQ_PASSWORD": "generated-rabbit"}
|
||||
|
||||
def verify_credentials(*_args):
|
||||
for key in ("DEMO_USER_PASSWORD", "DEMO_ADMIN_PASSWORD", "RABBITMQ_PASSWORD"):
|
||||
self.assertEqual(values[key], os.environ[key])
|
||||
|
||||
with (mock.patch.object(run_full_smoke, "ROOT", root),
|
||||
mock.patch.object(run_full_smoke, "demo_environment", return_value=values),
|
||||
mock.patch.object(run_full_smoke, "published_port", return_value=20003),
|
||||
mock.patch.object(run_full_smoke.subprocess, "run",
|
||||
return_value=subprocess.CompletedProcess([], 0)),
|
||||
mock.patch.object(run_full_smoke, "check_full", side_effect=verify_credentials) as check,
|
||||
mock.patch.dict(os.environ, {}, clear=False)):
|
||||
run_full_smoke.main()
|
||||
check.assert_called_once()
|
||||
|
||||
def test_full_runner_queries_private_opensearch_service(self):
|
||||
command = ["docker", "compose", "-p", "smoke"]
|
||||
with mock.patch.object(run_full_smoke.subprocess, "run",
|
||||
return_value=subprocess.CompletedProcess([], 0,
|
||||
stdout='{"hits":{"hits":[]}}')) as invoke:
|
||||
result = run_full_smoke.query_opensearch(command, {}, "customers", {"query": {}})
|
||||
self.assertEqual([], result["hits"]["hits"])
|
||||
args = invoke.call_args.args[0]
|
||||
self.assertEqual(["exec", "-T", "opensearch", "curl"], args[len(command):len(command) + 4])
|
||||
self.assertIn("http://127.0.0.1:9200/customers/_search", args)
|
||||
|
||||
def test_full_runner_fails_when_private_opensearch_query_fails(self):
|
||||
with mock.patch.object(run_full_smoke.subprocess, "run",
|
||||
return_value=subprocess.CompletedProcess([], 22, stdout="")):
|
||||
with self.assertRaisesRegex(AssertionError, "OpenSearch query failed"):
|
||||
run_full_smoke.query_opensearch(["docker", "compose"], {}, "customers", {"query": {}})
|
||||
|
||||
def test_full_runner_prepares_sftp_import_directory(self):
|
||||
command = ["docker", "compose", "-p", "smoke"]
|
||||
with mock.patch.object(run_full_smoke.subprocess, "run",
|
||||
return_value=subprocess.CompletedProcess([], 0)) as invoke:
|
||||
run_full_smoke.prepare_sftp_import_directory(command, {}, "qqq")
|
||||
self.assertEqual([
|
||||
command + ["exec", "-T", "sftp", "mkdir", "-p", "/home/qqq/upload/imports"],
|
||||
command + ["exec", "-T", "sftp", "chown", "1001:1001", "/home/qqq/upload/imports"],
|
||||
], [call.args[0] for call in invoke.call_args_list])
|
||||
|
||||
def test_full_runner_fails_when_sftp_fixture_cannot_be_prepared(self):
|
||||
with mock.patch.object(run_full_smoke.subprocess, "run", side_effect=[
|
||||
subprocess.CompletedProcess([], 0), subprocess.CompletedProcess([], 1)]):
|
||||
with self.assertRaisesRegex(AssertionError, "SFTP import directory"):
|
||||
run_full_smoke.prepare_sftp_import_directory(["docker", "compose"], {}, "qqq")
|
||||
|
||||
def test_oidc_cookie_is_sent_only_to_loopback_http_app(self):
|
||||
from smoke import allow_loopback_http_session
|
||||
|
||||
class SecureSession(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path in ("/login", "/login-plain"):
|
||||
data = b"ok"
|
||||
self.send_response(200)
|
||||
secure = "; Secure" if self.path == "/login" else ""
|
||||
self.send_header("Set-Cookie", "sessionUUID=test-session; Path=/; HttpOnly" + secure)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
if self.path == "/protected":
|
||||
if "sessionUUID=test-session" not in self.headers.get("Cookie", ""):
|
||||
return self.send_error(403)
|
||||
return self.send_json({"ok": True})
|
||||
return super().do_GET()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), SecureSession)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
client.request("/login")
|
||||
with self.assertRaisesRegex(AssertionError, "HTTP 403"):
|
||||
client.request("/protected")
|
||||
allow_loopback_http_session(client)
|
||||
self.assertTrue(client.json("/protected")["ok"])
|
||||
plain = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
plain.request("/login-plain")
|
||||
allow_loopback_http_session(plain)
|
||||
self.assertTrue(plain.json("/protected")["ok"])
|
||||
remote = SmokeClient("http://example.com")
|
||||
with self.assertRaisesRegex(AssertionError, "loopback"):
|
||||
allow_loopback_http_session(remote)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_keycloak_secure_auth_cookie_is_sent_on_loopback_http(self):
|
||||
from smoke import allow_loopback_http_cookies
|
||||
|
||||
class SecureKeycloak(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/auth":
|
||||
data = b"login"
|
||||
self.send_response(200)
|
||||
self.send_header("Set-Cookie", "AUTH_SESSION_ID=test-auth; Path=/; Secure; HttpOnly")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
return super().do_GET()
|
||||
|
||||
def do_POST(self):
|
||||
if self.path == "/login":
|
||||
if "AUTH_SESSION_ID=test-auth" not in self.headers.get("Cookie", ""):
|
||||
return self.send_error(400)
|
||||
return self.send_json({"ok": True})
|
||||
return super().do_POST()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), SecureKeycloak)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
base = f"http://127.0.0.1:{server.server_port}"
|
||||
cookies = http.cookiejar.CookieJar()
|
||||
browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))
|
||||
browser.open(base + "/auth", timeout=2).close()
|
||||
with self.assertRaises(urllib.error.HTTPError) as denied:
|
||||
browser.open(urllib.request.Request(base + "/login", data=b"x"), timeout=2)
|
||||
denied.exception.close()
|
||||
allow_loopback_http_cookies(cookies, base)
|
||||
with browser.open(urllib.request.Request(base + "/login", data=b"x"), timeout=2) as response:
|
||||
self.assertEqual({"ok": True}, json.load(response))
|
||||
with self.assertRaisesRegex(AssertionError, "loopback"):
|
||||
allow_loopback_http_cookies(cookies, "http://example.com")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_core_checks_public_http_behavior(self):
|
||||
server = SmokeServer(("127.0.0.1", 0), DemoHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
client.session_id = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
|
||||
check_core(client, timeout=2)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_missing_backend_records_fail(self):
|
||||
server = SmokeServer(("127.0.0.1", 0), DemoHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "missing expected customer"):
|
||||
client.require_record("customer", "name", "Grace Hopper")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_core_rejects_wrong_filesystem_seed(self):
|
||||
class WrongProduct(DemoHandler):
|
||||
product_name = "Unrelated Product"
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), WrongProduct)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "missing expected product"):
|
||||
check_tables(client, CORE_TABLES)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_artemis_rejects_unrelated_trace(self):
|
||||
class WrongTrace(DemoHandler):
|
||||
trace_label = "Unrelated Process - demo"
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), WrongTrace)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "Artemis.*syncOrder"):
|
||||
check_artemis_round_trip(client, timeout=0.3)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_artemis_returns_the_new_trace_uuid(self):
|
||||
server = SmokeServer(("127.0.0.1", 0), DemoHandler)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
self.assertEqual("trace-0", check_artemis_round_trip(client, timeout=2))
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_artemis_rejects_trace_for_another_order(self):
|
||||
class WrongOrderTrace(DemoHandler):
|
||||
trace_order_id = 999
|
||||
|
||||
def do_POST(self):
|
||||
if self.path == "/data/order/":
|
||||
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
||||
assert body["orderNo"].startswith("SMOKE-")
|
||||
type(self).orders += 1
|
||||
return self.send_json({"records": [{"values": {"id": 101}}]})
|
||||
return super().do_POST()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), WrongOrderTrace)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "Artemis.*syncOrder"):
|
||||
check_artemis_round_trip(client, timeout=0.3)
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_rabbitmq_rejects_unrelated_completion(self):
|
||||
class WrongCompletion(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/qqq/v1/esb/messages/orderSyncEvents":
|
||||
event = {"type": "qqq.process.other.completed",
|
||||
"data": {"processName": "other", "processUUID": "trace-1"}}
|
||||
return self.send_json({"messages": [{"event": event}], "hasMore": False})
|
||||
return super().do_GET()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), WrongCompletion)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "RabbitMQ syncOrder completion"):
|
||||
check_rabbitmq(client, 0.3, "trace-1")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_rabbitmq_rejects_wrong_process_uuid(self):
|
||||
class WrongRun(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/qqq/v1/esb/messages/orderSyncEvents":
|
||||
event = {"type": "qqq.process.syncOrder.completed",
|
||||
"data": {"processName": "syncOrder", "processUUID": "other-run"}}
|
||||
return self.send_json({"messages": [{"event": event}], "hasMore": False})
|
||||
return super().do_GET()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), WrongRun)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
with self.assertRaisesRegex(AssertionError, "RabbitMQ syncOrder completion"):
|
||||
check_rabbitmq(client, 0.3, "trace-0")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_rabbitmq_accepts_matching_process_uuid(self):
|
||||
class MatchingRun(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/qqq/v1/esb/messages/orderSyncEvents":
|
||||
event = {"type": "qqq.process.syncOrder.completed",
|
||||
"data": {"processName": "syncOrder", "processUUID": "trace-0"}}
|
||||
return self.send_json({"messages": [{"event": event}], "hasMore": False})
|
||||
return super().do_GET()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), MatchingRun)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
check_rabbitmq(client, 2, "trace-0")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
def test_rabbitmq_finds_completion_after_first_browse_page(self):
|
||||
class LaterPage(DemoHandler):
|
||||
def do_GET(self):
|
||||
if self.path == "/qqq/v1/esb/messages/orderSyncEvents":
|
||||
old = {"type": "qqq.process.syncOrder.completed",
|
||||
"data": {"processName": "syncOrder", "processUUID": "old-run"}}
|
||||
return self.send_json({"messages": [{"event": old}] * 50, "hasMore": True})
|
||||
if self.path == "/qqq/v1/esb/messages/orderSyncEvents?offset=50":
|
||||
event = {"type": "qqq.process.syncOrder.completed",
|
||||
"data": {"processName": "syncOrder", "processUUID": "trace-0"}}
|
||||
return self.send_json({"messages": [{"event": event}], "hasMore": False})
|
||||
return super().do_GET()
|
||||
|
||||
server = SmokeServer(("127.0.0.1", 0), LaterPage)
|
||||
thread = threading.Thread(target=server.serve_forever, daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
client = SmokeClient(f"http://127.0.0.1:{server.server_port}")
|
||||
check_rabbitmq(client, 2, "trace-0")
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
thread.join()
|
||||
|
||||
@unittest.skipUnless((ROOT / "compose.yaml").is_file() and shutil.which("docker"),
|
||||
"C6 Compose integration is not available")
|
||||
def test_full_smoke_keeps_opensearch_private_and_uses_ephemeral_service_ports(self):
|
||||
command = ["docker", "compose", "--env-file", str(ROOT / ".env.example"),
|
||||
"-f", str(ROOT / "compose.yaml"),
|
||||
"-f", str(ROOT / "scripts/compose.smoke.yaml"),
|
||||
"--profile", "full", "config", "--format", "json"]
|
||||
result = subprocess.run(command, capture_output=True, text=True, timeout=15)
|
||||
self.assertEqual(0, result.returncode, "full smoke Compose config failed")
|
||||
services = json.loads(result.stdout)["services"]
|
||||
self.assertNotIn("ports", services["opensearch"])
|
||||
for service, target in (("rabbitmq", 15672),
|
||||
("artemis", 8161), ("mailpit", 8025), ("minio", 9001)):
|
||||
with self.subTest(service=service):
|
||||
ports = services[service]["ports"]
|
||||
self.assertEqual(1, len(ports))
|
||||
self.assertEqual(target, ports[0]["target"])
|
||||
self.assertEqual("127.0.0.1", ports[0]["host_ip"])
|
||||
self.assertFalse(ports[0].get("published"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user