Compare commits
105 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a68259a0f4 | |||
| 136e4d44c9 | |||
| 660d536618 | |||
| e1d3ec480d | |||
| 0180f36a62 | |||
| 4500c89904 | |||
| 3df4642c90 | |||
| e67ed7165b | |||
| 4ae6ef39d5 | |||
| f2b63c00a3 | |||
| 6a151301b8 | |||
| d1be283318 | |||
| bf717dc38f | |||
| 73ee4c4479 | |||
| 38f9cfd48e | |||
| e14fc266bb | |||
| 917a79c536 | |||
| 2c951fd834 | |||
| 3983102caa | |||
| fba2039efc | |||
| b22381cb7f | |||
| eb0db67358 | |||
| 1f41d13667 | |||
| 222e408a16 | |||
| 67c27d3056 | |||
| 001caffba6 | |||
| 006d99a9e7 | |||
| 6bd0d195bf | |||
| 68e00e7c85 | |||
| 4aefd3ff06 | |||
| bbc900cd05 | |||
| 21f53f257c | |||
| 8ca6a450a3 | |||
| 58d8d52194 | |||
| 7d617bbb30 | |||
| cd6dfa345b | |||
| 1967cc2c22 | |||
| 60ebac7150 | |||
| a066b5e5ab | |||
| cd8e2433a5 | |||
| b538a379d1 | |||
| 8cab7a51ad | |||
| ece74226d4 | |||
| d26aa2f18a | |||
| ce2f73dfe3 | |||
| 30fb539289 | |||
| 66fd6db3c2 | |||
| 93a91cd76e | |||
| 1d1444234b | |||
| 49ac63210e | |||
| 702491cb39 | |||
| d55dbe0471 | |||
| 55969b03b5 | |||
| 70a036e158 | |||
| 6ade7d295b | |||
| e6ae133449 | |||
| d3706a8778 | |||
| a271e7c35d | |||
| a46a50b429 | |||
| dc8c359bfc | |||
| dfb6b10caf | |||
| 3fa30b3a32 | |||
| 80ed6033d1 | |||
| 4640522d5d | |||
| 848232cc11 | |||
| 98dedc4494 | |||
| e6f64ea026 | |||
| ea71d3825e | |||
| afa9b33568 | |||
| a93189411b | |||
| 98f103f5cf | |||
| 6fc48dae83 | |||
| d039add340 | |||
| 0214d6f46d | |||
| 37e14ec2f8 | |||
| a85d5a8c73 | |||
| 80cebe3357 | |||
| 451a5fbf0f | |||
| aeb6d1164b | |||
| 2f14cd82dd | |||
| faedd0bc7a | |||
| 1d207fae64 | |||
| a71f345f66 | |||
| 7cc6c1197f | |||
| 115bbf7366 | |||
| 36a06ac670 | |||
| 772897cb27 | |||
| 1f42798d12 | |||
| 08302e4457 | |||
| cd9a44fcc9 | |||
| 6532ff466e | |||
| 8cbed80fd0 | |||
| 0758bf4cee | |||
| f5c296bee3 | |||
| 8f33375b5f | |||
| cebbd48237 | |||
| 88d81ecfe3 | |||
| 3050c2b100 | |||
| a2aa586dae | |||
| ebc9c6852e | |||
| a1b67b8553 | |||
| dbc81796d6 | |||
| 2f796dbdab | |||
| ff06e10b8f | |||
| 050fd6f1e3 |
+4
-1
@@ -1,6 +1,9 @@
|
|||||||
.git
|
.git
|
||||||
/bin/
|
/bin/
|
||||||
/.shards/
|
/.shards/
|
||||||
/bruno/
|
|
||||||
/spec/
|
/spec/
|
||||||
/sqlite/
|
/sqlite/
|
||||||
|
|
||||||
|
/docs/
|
||||||
|
benchmark.cr
|
||||||
|
.env*
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
name: Publish Docker image
|
name: Publish Docker images
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
@@ -8,43 +8,77 @@ on:
|
|||||||
types: [published]
|
types: [published]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
push_to_registry:
|
build-platforms:
|
||||||
name: Push Docker image to Docker Hub
|
name: Build Platforms
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
platform: [linux/amd64, linux/arm64]
|
||||||
permissions:
|
permissions:
|
||||||
packages: write
|
|
||||||
contents: read
|
contents: read
|
||||||
attestations: write
|
packages: write
|
||||||
id-token: write
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v2
|
|
||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@v2
|
uses: docker/setup-buildx-action@v2
|
||||||
|
|
||||||
- name: Login to Docker Hub
|
- name: Login to Docker Hub
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
- name: Extract version tag
|
|
||||||
id: extract_tag
|
- name: Determine version
|
||||||
if: github.event_name == 'release'
|
id: version
|
||||||
run: echo "RELEASE_TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
|
run: |
|
||||||
- name: Build and push image
|
if [ "${{ github.event_name }}" = "release" ]; then
|
||||||
id: push
|
echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
|
||||||
uses: docker/build-push-action@v5.0.0
|
else
|
||||||
|
echo "version=latest" >> $GITHUB_OUTPUT
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Build and push platform image
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
env:
|
||||||
|
CRYSTAL_WORKERS: ${{ matrix.platform == 'linux/amd64' && 4 || 2 }}
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
|
platforms: ${{ matrix.platform }}
|
||||||
push: true
|
push: true
|
||||||
platforms: linux/amd64,linux/arm64
|
|
||||||
tags: |
|
tags: |
|
||||||
sjdonado/url-shortener:latest
|
sjdonado/bit:${{ steps.version.outputs.version }}-${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
|
||||||
${{ github.event_name == 'release' && 'sjdonado/url-shortener:${{ env.RELEASE_TAG }}' || '' }}
|
build-args: |
|
||||||
- name: Attest
|
TARGETARCH=${{ matrix.platform == 'linux/amd64' && 'amd64' || 'arm64' }}
|
||||||
uses: actions/attest-build-provenance@v1
|
cache-from: type=gha
|
||||||
id: attest
|
cache-to: type=gha,mode=max
|
||||||
|
|
||||||
|
create-manifest:
|
||||||
|
name: Create Manifest
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build-platforms
|
||||||
|
permissions:
|
||||||
|
packages: write
|
||||||
|
steps:
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
subject-name: sjdonado/url-shortener
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
subject-digest: ${{ steps.push.outputs.digest }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Determine version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
if [ "${{ github.event_name }}" = "release" ]; then
|
||||||
|
echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
|
||||||
|
else
|
||||||
|
echo "version=latest" >> $GITHUB_OUTPUT
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Create manifest
|
||||||
|
run: |
|
||||||
|
docker buildx imagetools create \
|
||||||
|
-t sjdonado/bit:${{ steps.version.outputs.version }} \
|
||||||
|
sjdonado/bit:${{ steps.version.outputs.version }}-{amd64,arm64}
|
||||||
|
|||||||
+2
-1
@@ -1,4 +1,3 @@
|
|||||||
/docs/
|
|
||||||
/lib/
|
/lib/
|
||||||
/bin/
|
/bin/
|
||||||
/.shards/
|
/.shards/
|
||||||
@@ -7,3 +6,5 @@
|
|||||||
|
|
||||||
/sqlite/
|
/sqlite/
|
||||||
.env.production
|
.env.production
|
||||||
|
|
||||||
|
resource_usage.*
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
# Contributor Covenant 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,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but 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.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official email address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
[INSERT CONTACT METHOD].
|
||||||
|
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][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
[https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0].
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by
|
||||||
|
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available
|
||||||
|
at [https://www.contributor-covenant.org/translations][translations].
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
[v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html
|
||||||
|
[Mozilla CoC]: https://github.com/mozilla/diversity
|
||||||
|
[FAQ]: https://www.contributor-covenant.org/faq
|
||||||
|
[translations]: https://www.contributor-covenant.org/translations
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# Contributing Guidelines
|
||||||
|
|
||||||
|
We welcome contributions from the community! Please follow these guidelines to help maintain consistency and quality in the project.
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
This project adheres to the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md). By participating, you agree to uphold its terms.
|
||||||
|
|
||||||
|
## How to Contribute
|
||||||
|
|
||||||
|
### 1. Fork the Repository
|
||||||
|
Click the "Fork" button at the top-right of the [repository page](https://github.com/sjdonado/bit).
|
||||||
|
|
||||||
|
### 2. Clone Your Fork
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/YOUR_USERNAME/bit.git
|
||||||
|
cd bit
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Create a Feature Branch
|
||||||
|
```bash
|
||||||
|
git checkout -b feat/your-feature-name
|
||||||
|
```
|
||||||
|
|
||||||
|
### or for bug fixes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout -b fix/issue-description
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Develop Your Changes
|
||||||
|
- Check [Local Development](docs/SETUP.md#local-development) guidelines
|
||||||
|
- Ensure changes match the project scope
|
||||||
|
- Write clear commit messages
|
||||||
|
- Include tests for new functionality
|
||||||
|
- Update documentation when applicable
|
||||||
|
|
||||||
|
### 5. Commit Changes
|
||||||
|
```bash
|
||||||
|
git commit -am 'Add descriptive commit message'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. Push to GitHub
|
||||||
|
```bash
|
||||||
|
git push origin your-branch-name
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. Create a Pull Request
|
||||||
|
1. Go to the [original repository](https://github.com/sjdonado/bit)
|
||||||
|
2. Click "New Pull Request"
|
||||||
|
3. Select your fork and branch
|
||||||
|
4. Add a clear description including:
|
||||||
|
- Purpose of changes
|
||||||
|
- Related issues (if applicable)
|
||||||
|
- Testing performed
|
||||||
|
|
||||||
|
## Pull Request Guidelines
|
||||||
|
- Keep PRs focused on a single feature/bugfix
|
||||||
|
- Ensure all tests pass
|
||||||
|
- Update documentation in the same PR
|
||||||
|
- Use descriptive titles (e.g., "Add URL validation" not "Update code")
|
||||||
|
- Reference related issues using #issue-number
|
||||||
|
|
||||||
|
## Reporting Issues
|
||||||
|
When opening an issue, please include:
|
||||||
|
1. Description of the problem
|
||||||
|
2. Steps to reproduce
|
||||||
|
3. Expected vs actual behavior
|
||||||
|
4. Environment details (OS, Crystal version, etc)
|
||||||
|
|
||||||
|
For feature requests:
|
||||||
|
- Explain the problem you're trying to solve
|
||||||
|
- Suggest potential implementations
|
||||||
|
|
||||||
|
## License
|
||||||
|
By contributing, you agree that your contributions will be licensed under the [license](LICENSE).
|
||||||
+37
-9
@@ -1,19 +1,47 @@
|
|||||||
FROM alpine:edge as base
|
FROM debian:bookworm-slim AS build
|
||||||
|
|
||||||
|
ARG TARGETARCH
|
||||||
|
ENV ENV=production
|
||||||
WORKDIR /usr/src/app
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
RUN apk add crystal shards sqlite-dev openssl-dev
|
RUN apt-get update && apt-get install -y \
|
||||||
|
curl \
|
||||||
|
gnupg \
|
||||||
|
ca-certificates \
|
||||||
|
&& mkdir -p /etc/apt/keyrings \
|
||||||
|
&& curl -fsSL https://packagecloud.io/84codes/crystal/gpgkey | gpg --dearmor > /etc/apt/trusted.gpg.d/84codes_crystal.gpg \
|
||||||
|
&& echo "deb [signed-by=/etc/apt/trusted.gpg.d/84codes_crystal.gpg] https://packagecloud.io/84codes/crystal/debian/ bookworm main" > /etc/apt/sources.list.d/84codes_crystal.list
|
||||||
|
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
crystal \
|
||||||
|
libssl-dev \
|
||||||
|
libyaml-dev \
|
||||||
|
libsqlite3-dev \
|
||||||
|
libevent-dev \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
RUN shards install --production
|
||||||
|
RUN shards build --release --no-debug --progress --stats
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim AS runtime
|
||||||
|
|
||||||
FROM base AS build
|
|
||||||
ENV ENV=production
|
ENV ENV=production
|
||||||
COPY . .
|
WORKDIR /usr/src/app
|
||||||
|
|
||||||
RUN shards install
|
RUN apt-get update && apt-get install -y \
|
||||||
RUN shards build --progress
|
libssl3 \
|
||||||
|
libyaml-0-2 \
|
||||||
|
sqlite3 \
|
||||||
|
libevent-2.1-7 \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
RUN mkdir -p sqlite
|
||||||
|
|
||||||
FROM base AS release
|
|
||||||
RUN mkdir -p /usr/src/app/sqlite
|
|
||||||
COPY --from=build /usr/src/app/db db
|
COPY --from=build /usr/src/app/db db
|
||||||
|
COPY --from=build /usr/src/app/data data
|
||||||
COPY --from=build /usr/src/app/bin /usr/local/bin
|
COPY --from=build /usr/src/app/bin /usr/local/bin
|
||||||
|
|
||||||
EXPOSE 4000/tcp
|
EXPOSE 4000/tcp
|
||||||
CMD ["url-shortener"]
|
CMD ["bit"]
|
||||||
|
|||||||
@@ -1,138 +1,30 @@
|
|||||||
# url-shortener
|
[](https://hub.docker.com/r/sjdonado/bit)
|
||||||
> Lightning fast, lightweight and minimal self-hosted url shortener
|
[](https://hub.docker.com/r/sjdonado/bit)
|
||||||
|
[](https://hub.docker.com/r/sjdonado/bit)
|
||||||
|
|
||||||
## Benchmark
|
Lightweight URL shortener (API-only) with minimal resource requirements. Avg memory consumption under pressure is around **60MiB**, CPU single core consumption 60%.
|
||||||
```shell
|
|
||||||
./benchmark.sh
|
|
||||||
Semaphore initialized with 2666 slots.
|
|
||||||
Setup...
|
|
||||||
[+] Running 1/0
|
|
||||||
✔ Container url-shortener-app-1 Running 0.0s
|
|
||||||
2024-05-20T16:39:53.818306Z INFO - micrate: No migrations to run. current version: 20240513130054
|
|
||||||
Captured API Key: 4y2mblZDneZLcI-YywHGFA
|
|
||||||
Waiting for database to be ready...
|
|
||||||
Creating 1000 short links...
|
|
||||||
Created short link 100/1000
|
|
||||||
Created short link 200/1000
|
|
||||||
Created short link 300/1000
|
|
||||||
Created short link 400/1000
|
|
||||||
Created short link 500/1000
|
|
||||||
Created short link 600/1000
|
|
||||||
Created short link 700/1000
|
|
||||||
Created short link 800/1000
|
|
||||||
Created short link 900/1000
|
|
||||||
Created short link 1000/1000
|
|
||||||
Accessing each link 10 times concurrently...
|
|
||||||
****Results****
|
|
||||||
Average Memory Usage: 11.00 MiB
|
|
||||||
Average Response Time: 5.28 µs
|
|
||||||
[+] Running 2/2
|
|
||||||
✔ Container url-shortener-app-1 Removed 10.2s
|
|
||||||
✔ Network url-shortener_default Removed
|
|
||||||
```
|
|
||||||
|
|
||||||
## Self-hosted
|
Highly performant: 6K+ reqs/sec, latency 20ms (100000 requests using 125 connections, [benchmark](docs/SETUP.md#benchmark)).
|
||||||
|
|
||||||
- Run via docker-compose
|
Self-hosted: [Dokku](docs/SETUP.md#dokku), [Docker Compose](docs/SETUP.md#docker-compose).
|
||||||
```bash
|
|
||||||
docker-compose up
|
|
||||||
|
|
||||||
docker-compose exec -it app migrate
|
Images available on [Docker Hub](https://hub.docker.com/r/sjdonado/bit/tags).
|
||||||
docker-compose exec -it app cli --create-user=Admin
|
|
||||||
```
|
|
||||||
|
|
||||||
- Run via docker cli
|
## Why bit?
|
||||||
```bash
|
It is feature-complete by design: simple and reliable without unnecessary bloat. Bug fixes will continue, but new features aren't planned.
|
||||||
docker run \
|
|
||||||
--name url-shortener \
|
|
||||||
-p 4000:4000 \
|
|
||||||
-e ENV="production" \
|
|
||||||
-e DATABASE_URL="sqlite3://./sqlite/data.db?journal_mode=wal&synchronous=normal&foreign_keys=true" \
|
|
||||||
-e APP_URL="http://localhost:4000" \
|
|
||||||
sjdonado/url-shortener
|
|
||||||
|
|
||||||
docker exec -it url-shortener migrate
|
- Minimal tracking setup: Country, browser, OS, referer. No cookies or persistent tracking mechanisms are used beyond what's available from a basic client's request.
|
||||||
docker exec -it url-shortener cli --create-user=Admin
|
- Provides standard `X-Forwarded-For` header support to enable extended capabilities.
|
||||||
```
|
- Multiple users are supported via API key authentication. Users can create, list and delete keys via the [CLI](docs/SETUP.md#cli).
|
||||||
|
|
||||||
- Dokku
|
## Minimum Requirements
|
||||||
```dockerfile
|
- 100MB disk space
|
||||||
FROM sjdonado/url-shortener
|
- 70MiB RAM
|
||||||
```
|
- x86_64 or ARM64
|
||||||
|
|
||||||
```bash
|
## Documentation
|
||||||
dokku apps:create url-shortener
|
- [API Reference](docs/API.md)
|
||||||
|
- [Setup](docs/SETUP.md)
|
||||||
dokku domains:set url-shortener bit.donado.co
|
|
||||||
dokku letsencrypt:enable url-shortener
|
|
||||||
|
|
||||||
dokku storage:ensure-directory url-shortener-sqlite
|
|
||||||
dokku storage:mount url-shortener /var/lib/dokku/data/storage/url-shortener-sqlite:/usr/src/app/sqlite/
|
|
||||||
|
|
||||||
dokku config:set url-shortener DATABASE_URL="sqlite3://./sqlite/data.db?journal_mode=wal&synchronous=normal&foreign_keys=true" APP_URL=https://bit.donado.co
|
|
||||||
|
|
||||||
dokku ports:add url-shortener http:80:4000
|
|
||||||
dokku ports:add url-shortener https:443:4000
|
|
||||||
|
|
||||||
dokku run url-shortener migrate
|
|
||||||
dokku run url-shortener cli --create-user=Admin
|
|
||||||
```
|
|
||||||
|
|
||||||
## Usage
|
|
||||||
|
|
||||||
**REST API**
|
|
||||||
|
|
||||||
| Endpoint | HTTP Method | Description | Payload |
|
|
||||||
|----------|-------------|-------------|---------|
|
|
||||||
| `/api/ping` | GET | Ping the API to check if it's running | - |
|
|
||||||
| `/:slug` | GET | Retrieve a link by its slug | - |
|
|
||||||
| `/api/links` | GET | Retrieve all links | - |
|
|
||||||
| `/api/links` | POST | Create a new link | `{"url": "https://example.com"}` |
|
|
||||||
| `/api/links/:id` | PUT | Update an existing link by its ID | `{"url": "https://newexample.com"}` |
|
|
||||||
| `/api/links/:id` | DELETE | Delete a link by its ID | - |
|
|
||||||
|
|
||||||
**CLI**
|
|
||||||
```
|
|
||||||
Usage: ./cli [options]
|
|
||||||
Options:
|
|
||||||
--create-user=NAME Create a new user with the given name
|
|
||||||
--list-users List all users
|
|
||||||
--delete-user=USER_ID Delete a user by ID
|
|
||||||
```
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
**Installation**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
brew tap amberframework/micrate
|
|
||||||
brew install micrate
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
shards run migrate
|
|
||||||
shards run url-shortener
|
|
||||||
```
|
|
||||||
|
|
||||||
**Generate the `X-Api-Key`**
|
|
||||||
|
|
||||||
```bash
|
|
||||||
shards run cli -- --create-user=Admin
|
|
||||||
```
|
|
||||||
|
|
||||||
## Run tests
|
|
||||||
```bash
|
|
||||||
ENV=test crystal spec
|
|
||||||
```
|
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
Found an issue or have a suggestion? Please follow our [contribution guidelines](CONTRIBUTING.md).
|
||||||
1. Fork it (<https://github.com/sjdonado/url-shortener/fork>)
|
|
||||||
2. Create your feature branch (`git checkout -b my-new-feature`)
|
|
||||||
3. Commit your changes (`git commit -am 'Add some feature'`)
|
|
||||||
4. Push to the branch (`git push origin my-new-feature`)
|
|
||||||
5. Create a new Pull Request
|
|
||||||
|
|
||||||
## Contributors
|
|
||||||
|
|
||||||
- [sjdonado](https://github.com/sjdonado) - creator and maintainer
|
|
||||||
|
|||||||
@@ -1,6 +1,15 @@
|
|||||||
|
require "log"
|
||||||
|
|
||||||
ENV["ENV"] ||= "development"
|
ENV["ENV"] ||= "development"
|
||||||
|
ENV["APP_URL"] ||= "http://localhost:4000"
|
||||||
|
ENV["DATABASE_URL"] ||= "sqlite3://./sqlite/data.db?journal_mode=wal&synchronous=normal&foreign_keys=true
|
||||||
|
"
|
||||||
|
|
||||||
{% if env("ENV") != "production" %}
|
{% if env("ENV") != "production" %}
|
||||||
require "dotenv"
|
require "dotenv"
|
||||||
Dotenv.load ".env.#{ENV["ENV"]}" # File must exist in non-production!
|
Dotenv.load ".env.#{ENV["ENV"]}" # File must exist in non-production!
|
||||||
{% end %}
|
{% end %}
|
||||||
|
|
||||||
|
{% if env("ENV") == "production" %}
|
||||||
|
Log.setup(:error)
|
||||||
|
{% end %}
|
||||||
|
|||||||
@@ -3,3 +3,5 @@ require "kemal"
|
|||||||
Kemal.config.env = ENV["ENV"]? || "development"
|
Kemal.config.env = ENV["ENV"]? || "development"
|
||||||
Kemal.config.port = ENV["PORT"]?.try(&.to_i) || 4000
|
Kemal.config.port = ENV["PORT"]?.try(&.to_i) || 4000
|
||||||
Kemal.config.host_binding = ENV["HOST"]? || "0.0.0.0"
|
Kemal.config.host_binding = ENV["HOST"]? || "0.0.0.0"
|
||||||
|
|
||||||
|
Kemal.config.powered_by_header = false
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
module App::Controllers
|
||||||
|
struct ClickController
|
||||||
|
include App::Models
|
||||||
|
include App::Lib
|
||||||
|
include App::Services
|
||||||
|
|
||||||
|
# Buffered channel to hold click data
|
||||||
|
@@click_channel = Channel(NamedTuple(
|
||||||
|
link_id: Int64,
|
||||||
|
remote_address: String,
|
||||||
|
user_agent: String?,
|
||||||
|
referer: String
|
||||||
|
)).new(1024)
|
||||||
|
|
||||||
|
@@processor_started = begin
|
||||||
|
spawn do
|
||||||
|
batch_size = 64
|
||||||
|
batch = [] of NamedTuple(
|
||||||
|
link_id: Int64,
|
||||||
|
remote_address: String,
|
||||||
|
user_agent: String?,
|
||||||
|
referer: String
|
||||||
|
)
|
||||||
|
|
||||||
|
loop do
|
||||||
|
select
|
||||||
|
when click_data = @@click_channel.receive
|
||||||
|
batch << click_data
|
||||||
|
|
||||||
|
# Collect clicks until we have a batch or a timeout
|
||||||
|
if batch.size >= batch_size
|
||||||
|
process_click_batch(batch)
|
||||||
|
batch.clear
|
||||||
|
end
|
||||||
|
when timeout(0.5.seconds)
|
||||||
|
# Process whatever we have after timeout
|
||||||
|
unless batch.empty?
|
||||||
|
process_click_batch(batch)
|
||||||
|
batch.clear
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
true
|
||||||
|
end
|
||||||
|
|
||||||
|
private def self.process_click_batch(batch)
|
||||||
|
clicks = [] of App::Models::Click
|
||||||
|
|
||||||
|
batch.each do |click_data|
|
||||||
|
begin
|
||||||
|
client_ip = IpLookup.ip_from_address(click_data[:remote_address])
|
||||||
|
family, _, _, os = UserAgent.parse(click_data[:user_agent] || "")
|
||||||
|
|
||||||
|
click = App::Models::Click.new
|
||||||
|
click.link_id = click_data[:link_id]
|
||||||
|
click.country = client_ip ? IpLookup.country(client_ip) : nil
|
||||||
|
click.user_agent = click_data[:user_agent]
|
||||||
|
click.browser = family
|
||||||
|
click.os = os.try &.[0] # OS family
|
||||||
|
click.referer = click_data[:referer]
|
||||||
|
|
||||||
|
clicks << click
|
||||||
|
rescue ex
|
||||||
|
Log.error { "Click data processing error: #{ex.message}" }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
# Batch insert clicks if any were successfully processed
|
||||||
|
unless clicks.empty?
|
||||||
|
begin
|
||||||
|
multi = Crecto::Multi.new
|
||||||
|
clicks.each do |click|
|
||||||
|
multi.insert(click)
|
||||||
|
end
|
||||||
|
Database.transaction(multi)
|
||||||
|
rescue ex
|
||||||
|
Log.error { "Batch click insertion error: #{ex.message}" }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.redirect_handler
|
||||||
|
->(env : HTTP::Server::Context) {
|
||||||
|
link_id, url = Database.raw_query("SELECT id, url FROM links WHERE slug = (?) LIMIT 1", env.params.url["slug"]) do |result|
|
||||||
|
result.move_next ? {result.read(Int64), result.read(String)} : nil
|
||||||
|
end || raise App::NotFoundException.new(env)
|
||||||
|
|
||||||
|
remote_address = env.request.headers["Cf-Connecting-Ip"]? || env.request.remote_address.to_s
|
||||||
|
|
||||||
|
env.response.status_code = 301
|
||||||
|
env.response.headers.add("Location", url)
|
||||||
|
env.response.headers.add("X-Forwarded-For", remote_address)
|
||||||
|
|
||||||
|
begin
|
||||||
|
@@click_channel.send({
|
||||||
|
link_id: link_id,
|
||||||
|
remote_address: remote_address,
|
||||||
|
user_agent: env.request.headers["User-Agent"]?,
|
||||||
|
referer: env.request.headers["Referer"]?.try { |r| URI.parse(r).host rescue r } || env.params.query["utm_source"]? || "Direct"
|
||||||
|
})
|
||||||
|
rescue Channel::ClosedError
|
||||||
|
Log.error { "Click channel closed" }
|
||||||
|
rescue ex
|
||||||
|
Log.error { "Error queuing click: #{ex.message}" }
|
||||||
|
end
|
||||||
|
}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
+114
-84
@@ -1,123 +1,153 @@
|
|||||||
require "uuid"
|
module App::Controllers
|
||||||
|
class LinkController < App::Lib::BaseController
|
||||||
require "../lib/controller.cr"
|
|
||||||
|
|
||||||
module App::Controllers::Link
|
|
||||||
class Create < App::Lib::BaseController
|
|
||||||
include App::Models
|
include App::Models
|
||||||
include App::Lib
|
include App::Lib
|
||||||
|
include App::Services
|
||||||
|
|
||||||
def call(env)
|
def initialize(@env : HTTP::Server::Context)
|
||||||
user = env.get("user").as(User)
|
super(@env)
|
||||||
body = parse_body(env, ["url"])
|
end
|
||||||
|
|
||||||
|
def create
|
||||||
|
body = parse_body(["url"])
|
||||||
|
url = body["url"].to_s
|
||||||
|
|
||||||
|
query = Database::Query.where(url: url, user_id: current_user_id).limit(1)
|
||||||
|
existing_link = Database.all(Link, query, preload: [:clicks]).first?
|
||||||
|
if existing_link
|
||||||
|
return render_json({"data" => App::Serializers::Link.new(existing_link)})
|
||||||
|
end
|
||||||
|
|
||||||
link = Link.new
|
link = Link.new
|
||||||
link.id = UUID.v4.to_s
|
link.url = url
|
||||||
link.url = body["url"].to_s
|
link.user_id = current_user_id
|
||||||
link.slug = Random::Secure.urlsafe_base64(4)
|
link.slug = SlugService.shorten_url(url, current_user_id)
|
||||||
link.user = user
|
|
||||||
|
|
||||||
changeset = Database.insert(link)
|
changeset = Database.insert(link)
|
||||||
if !changeset.valid?
|
if !changeset.valid?
|
||||||
raise App::UnprocessableEntityException.new(env, map_changeset_errors(changeset.errors))
|
raise App::UnprocessableEntityException.new(@env, map_changeset_errors(changeset.errors))
|
||||||
end
|
end
|
||||||
|
|
||||||
response = {"data" => App::Serializers::Link.new(link)}
|
inserted_link = Database.get!(Link, changeset.instance.id)
|
||||||
response.to_json
|
|
||||||
|
render_json({"data" => App::Serializers::Link.new(inserted_link)}, 201)
|
||||||
end
|
end
|
||||||
end
|
|
||||||
|
|
||||||
class Index < App::Lib::BaseController
|
def list_all
|
||||||
include App::Models
|
limit, cursor = pagination_params
|
||||||
include App::Lib
|
|
||||||
|
|
||||||
def call(env)
|
query = Database::Query.where(user_id: current_user_id)
|
||||||
slug = env.params.url["slug"]
|
query = query.where("id < ?", cursor) if cursor
|
||||||
|
query = query.order_by("id DESC").limit(limit + 1)
|
||||||
|
|
||||||
link = Database.get_by(Link, slug: slug)
|
|
||||||
raise App::NotFoundException.new(env) if !link
|
|
||||||
|
|
||||||
spawn do
|
|
||||||
link.click_counter = link.click_counter! + 1
|
|
||||||
|
|
||||||
changeset = Database.update(link)
|
|
||||||
if changeset.errors.any?
|
|
||||||
Log.error { "Increase click counter failed: #{changeset.errors}" }
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
env.response.status_code = 301
|
|
||||||
env.response.headers["Location"] = link.url!
|
|
||||||
env.response.headers["Content-Type"] = "text/html"
|
|
||||||
env.response.print("Redirecting...")
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
class All < App::Lib::BaseController
|
|
||||||
include App::Models
|
|
||||||
include App::Lib
|
|
||||||
|
|
||||||
def call(env)
|
|
||||||
user = env.get("user").as(User)
|
|
||||||
|
|
||||||
query = Database::Query.where(user_id: user.id.as(String))
|
|
||||||
links = Database.all(Link, query)
|
links = Database.all(Link, query)
|
||||||
|
|
||||||
response = {"data" => links.map { |link| App::Serializers::Link.new(link) }}
|
paginated_response(links, limit) { |link| App::Serializers::Link.new(link) }
|
||||||
response.to_json
|
|
||||||
end
|
end
|
||||||
end
|
|
||||||
|
|
||||||
class Update < App::Lib::BaseController
|
def get
|
||||||
include App::Models
|
link_id = @env.params.url["id"].to_i64
|
||||||
include App::Lib
|
|
||||||
|
|
||||||
def call(env)
|
query = Database::Query.where(id: link_id, user_id: current_user_id).limit(1)
|
||||||
user = env.get("user").as(User)
|
link = Database.all(Link, query).first?
|
||||||
id = env.params.url["id"]
|
raise App::NotFoundException.new(@env) if link.nil?
|
||||||
body = parse_body(env, ["url"])
|
|
||||||
|
|
||||||
link = Database.get(Link, id)
|
clicks_query = Database::Query.where(link_id: link_id)
|
||||||
raise App::NotFoundException.new(env) if !link
|
.order_by("id DESC")
|
||||||
|
.limit(100)
|
||||||
|
link.clicks = Database.all(Click, clicks_query)
|
||||||
|
|
||||||
if link.user_id != user.id
|
render_json({"data" => App::Serializers::Link.new(link)})
|
||||||
raise App::ForbiddenException.new(env)
|
end
|
||||||
|
|
||||||
|
def list_clicks
|
||||||
|
link_id = @env.params.url["id"].to_i64
|
||||||
|
|
||||||
|
# Verify link exists and belongs to user
|
||||||
|
link_query = Database::Query.where(id: link_id, user_id: current_user_id).limit(1)
|
||||||
|
link = Database.all(Link, link_query).first?
|
||||||
|
raise App::NotFoundException.new(@env) if link.nil?
|
||||||
|
|
||||||
|
limit, cursor = pagination_params
|
||||||
|
|
||||||
|
query = Database::Query.where(link_id: link_id)
|
||||||
|
query = query.where("id < ?", cursor) if cursor
|
||||||
|
query = query.order_by("id DESC").limit(limit + 1)
|
||||||
|
|
||||||
|
clicks = Database.all(Click, query)
|
||||||
|
|
||||||
|
paginated_response(clicks, limit) { |click| App::Serializers::Click.new(click) }
|
||||||
|
end
|
||||||
|
|
||||||
|
def update
|
||||||
|
id = @env.params.url["id"].to_i64
|
||||||
|
body = parse_body(["url"])
|
||||||
|
new_url = body["url"].to_s
|
||||||
|
|
||||||
|
query = Database::Query.where(id: id).limit(1)
|
||||||
|
link = Database.all(Link, query, preload: [:clicks]).first?
|
||||||
|
|
||||||
|
raise App::NotFoundException.new(@env) if link.nil?
|
||||||
|
raise App::ForbiddenException.new(@env) if link.user_id != current_user_id
|
||||||
|
|
||||||
|
# Check for existing URL
|
||||||
|
existing_query = Database::Query.where(url: new_url, user_id: current_user_id).limit(1)
|
||||||
|
if Database.all(Link, existing_query).first?
|
||||||
|
raise App::UnprocessableEntityException.new(@env, { "url" => ["URL already exists"] })
|
||||||
end
|
end
|
||||||
|
|
||||||
link.url = body["url"].to_s
|
link.url = new_url
|
||||||
link.click_counter = 0
|
link.slug = SlugService.shorten_url(new_url, current_user_id)
|
||||||
|
|
||||||
changeset = Database.update(link)
|
changeset = Database.update(link)
|
||||||
if !changeset.valid?
|
if !changeset.valid?
|
||||||
raise App::UnprocessableEntityException.new(env, map_changeset_errors(changeset.errors))
|
raise App::UnprocessableEntityException.new(@env, map_changeset_errors(changeset.errors))
|
||||||
end
|
end
|
||||||
|
|
||||||
response = {"data" => App::Serializers::Link.new(link)}
|
render_json({"data" => App::Serializers::Link.new(link)})
|
||||||
response.to_json
|
|
||||||
end
|
end
|
||||||
end
|
|
||||||
|
|
||||||
class Delete < App::Lib::BaseController
|
def delete
|
||||||
include App::Models
|
id = @env.params.url["id"].to_i64
|
||||||
include App::Lib
|
|
||||||
|
|
||||||
def call(env)
|
|
||||||
user = env.get("user").as(User)
|
|
||||||
id = env.params.url["id"]
|
|
||||||
|
|
||||||
link = Database.get(Link, id)
|
link = Database.get(Link, id)
|
||||||
raise App::NotFoundException.new(env) if !link
|
raise App::NotFoundException.new(@env) if !link
|
||||||
|
raise App::ForbiddenException.new(@env) if link.user_id != current_user_id
|
||||||
|
|
||||||
if link.user_id != user.id
|
result = Database.raw_exec("DELETE FROM links WHERE id = (?)", link.id)
|
||||||
raise App::ForbiddenException.new(env)
|
|
||||||
end
|
|
||||||
|
|
||||||
result = Database.raw_exec("DELETE FROM links WHERE id = (?)", link.id) # tempfix: Database.delete does not work
|
|
||||||
if result.rows_affected == 0
|
if result.rows_affected == 0
|
||||||
raise App::UnprocessableEntityException.new(env, { "id" => ["Row delete failed"] })
|
raise App::UnprocessableEntityException.new(@env, { "id" => ["Row delete failed"] })
|
||||||
end
|
end
|
||||||
|
|
||||||
env.response.status_code = 204
|
@env.response.status_code = 204
|
||||||
|
end
|
||||||
|
|
||||||
|
private def current_user : User
|
||||||
|
@env.get("user").as(User)
|
||||||
|
end
|
||||||
|
|
||||||
|
private def current_user_id : Int64
|
||||||
|
current_user.id.as(Int64)
|
||||||
|
end
|
||||||
|
|
||||||
|
private def pagination_params
|
||||||
|
limit = (@env.params.query["limit"]? || "100").to_i32
|
||||||
|
cursor = @env.params.query["cursor"]?
|
||||||
|
{limit, cursor}
|
||||||
|
end
|
||||||
|
|
||||||
|
private def paginated_response(items, limit)
|
||||||
|
has_more = items.size > limit
|
||||||
|
items = items[0...limit] if has_more
|
||||||
|
next_cursor = has_more ? items.last.id : nil
|
||||||
|
|
||||||
|
render_json({
|
||||||
|
"data" => items.map { |item| yield item },
|
||||||
|
"pagination" => {
|
||||||
|
"has_more" => has_more,
|
||||||
|
"next_cursor" => next_cursor
|
||||||
|
}
|
||||||
|
})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,10 +1,13 @@
|
|||||||
require "../lib/controller.cr"
|
require "../lib/controller.cr"
|
||||||
|
|
||||||
module App::Controllers::Ping
|
module App::Controllers
|
||||||
class Get < App::Lib::BaseController
|
class PingController < App::Lib::BaseController
|
||||||
def call(env)
|
def initialize(@env : HTTP::Server::Context)
|
||||||
response = {"pong" => "ok"}
|
super(@env)
|
||||||
response.to_json
|
end
|
||||||
|
|
||||||
|
def ping
|
||||||
|
render_json({data: "pong"})
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+29
-13
@@ -1,29 +1,45 @@
|
|||||||
module App::Lib
|
module App::Lib
|
||||||
abstract class BaseController
|
abstract class BaseController
|
||||||
def map_changeset_errors(errors)
|
protected getter env : HTTP::Server::Context
|
||||||
|
|
||||||
|
def initialize(@env : HTTP::Server::Context); end
|
||||||
|
|
||||||
|
# Convert changeset errors to API-friendly format
|
||||||
|
protected def map_changeset_errors(errors)
|
||||||
errors.reduce({} of String => Array(String)) do |memo, error|
|
errors.reduce({} of String => Array(String)) do |memo, error|
|
||||||
memo[error[:field]] = memo[error[:field]]? || [] of String
|
field = error[:field].to_s
|
||||||
memo[error[:field]] << error[:message]
|
message = error[:message].to_s
|
||||||
|
|
||||||
|
memo[field] ||= [] of String
|
||||||
|
memo[field] << message
|
||||||
memo
|
memo
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def parse_body(env, fields)
|
protected def parse_body(required_fields : Array(String) = [] of String)
|
||||||
json_params = env.params.json.to_h
|
json_params = @env.params.json.try(&.to_h) || {} of String => JSON::Any
|
||||||
missing_fields = [] of String
|
json_params = json_params.transform_values(&.to_s) # Convert JSON::Any to String
|
||||||
|
|
||||||
fields.each do |field|
|
missing_fields = required_fields.reject { |field| json_params.has_key?(field) }
|
||||||
unless json_params.has_key?(field)
|
|
||||||
missing_fields << field
|
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
unless missing_fields.empty?
|
unless missing_fields.empty?
|
||||||
error_message = missing_fields.map { |field| "#{field}: Required field" }.join(", ")
|
error_message = missing_fields.join(", ") + " required"
|
||||||
raise App::BadRequestException.new(env, error_message)
|
raise App::BadRequestException.new(@env, error_message)
|
||||||
end
|
end
|
||||||
|
|
||||||
json_params
|
json_params
|
||||||
end
|
end
|
||||||
|
|
||||||
|
protected def render_json(data, status_code : Int32 = 200)
|
||||||
|
@env.response.status_code = status_code
|
||||||
|
@env.response.content_type = "application/json"
|
||||||
|
data.to_json
|
||||||
|
end
|
||||||
|
|
||||||
|
protected def param(key : String) : String
|
||||||
|
@env.params.url[key]
|
||||||
|
rescue KeyError
|
||||||
|
raise App::BadRequestException.new(@env, "Missing required parameter: #{key}")
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+17
-1
@@ -1,5 +1,6 @@
|
|||||||
require "sqlite3"
|
require "sqlite3"
|
||||||
require "crecto"
|
require "crecto"
|
||||||
|
require "micrate"
|
||||||
|
|
||||||
module App::Lib
|
module App::Lib
|
||||||
class Database
|
class Database
|
||||||
@@ -8,11 +9,26 @@ module App::Lib
|
|||||||
Query = Crecto::Repo::Query
|
Query = Crecto::Repo::Query
|
||||||
|
|
||||||
config do |conf|
|
config do |conf|
|
||||||
conf.uri = ENV["DATABASE_URL"]
|
base_url = ENV["DATABASE_URL"]
|
||||||
|
separator = base_url.includes?("?") ? "&" : "?"
|
||||||
|
|
||||||
|
db_url = base_url + separator +
|
||||||
|
"&journal_mode=WAL" +
|
||||||
|
"&synchronous=NORMAL" + # Better performance with reasonable safety
|
||||||
|
"&foreign_keys=true"
|
||||||
|
|
||||||
|
conf.uri = db_url
|
||||||
end
|
end
|
||||||
|
|
||||||
if ENV["ENV"] == "development"
|
if ENV["ENV"] == "development"
|
||||||
Crecto::DbLogger.set_handler(STDOUT)
|
Crecto::DbLogger.set_handler(STDOUT)
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.run_migrations
|
||||||
|
Micrate::DB.connection_url = ENV["DATABASE_URL"]
|
||||||
|
Micrate::Cli.run_up
|
||||||
|
end
|
||||||
|
|
||||||
|
run_migrations
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,8 +1,18 @@
|
|||||||
require "kemal"
|
require "kemal"
|
||||||
|
|
||||||
module App
|
module App
|
||||||
|
class InternalServerErrorException < Kemal::Exceptions::CustomException
|
||||||
|
def initialize(context)
|
||||||
|
context.response.content_type = "application/json"
|
||||||
|
context.response.status_code = 500
|
||||||
|
context.response.print({ "error" => "Internal Server Error" }.to_json)
|
||||||
|
super(context)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
class BadRequestException < Kemal::Exceptions::CustomException
|
class BadRequestException < Kemal::Exceptions::CustomException
|
||||||
def initialize(context, message : String)
|
def initialize(context, message : String)
|
||||||
|
context.response.content_type = "application/json"
|
||||||
context.response.status_code = 400
|
context.response.status_code = 400
|
||||||
context.response.print({ "error" => message }.to_json)
|
context.response.print({ "error" => message }.to_json)
|
||||||
super(context)
|
super(context)
|
||||||
@@ -11,13 +21,16 @@ module App
|
|||||||
|
|
||||||
class UnauthorizedException < Kemal::Exceptions::CustomException
|
class UnauthorizedException < Kemal::Exceptions::CustomException
|
||||||
def initialize(context)
|
def initialize(context)
|
||||||
|
context.response.content_type = "application/json"
|
||||||
context.response.status_code = 401
|
context.response.status_code = 401
|
||||||
|
context.response.print({ "error" => "Unauthorized access" }.to_json)
|
||||||
super(context)
|
super(context)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class ForbiddenException < Kemal::Exceptions::CustomException
|
class ForbiddenException < Kemal::Exceptions::CustomException
|
||||||
def initialize(context)
|
def initialize(context)
|
||||||
|
context.response.content_type = "application/json"
|
||||||
context.response.status_code = 403
|
context.response.status_code = 403
|
||||||
context.response.print({ "error" => "Access not allowed" }.to_json)
|
context.response.print({ "error" => "Access not allowed" }.to_json)
|
||||||
super(context)
|
super(context)
|
||||||
@@ -26,13 +39,16 @@ module App
|
|||||||
|
|
||||||
class NotFoundException < Kemal::Exceptions::CustomException
|
class NotFoundException < Kemal::Exceptions::CustomException
|
||||||
def initialize(context)
|
def initialize(context)
|
||||||
|
context.response.content_type = "application/json"
|
||||||
context.response.status_code = 404
|
context.response.status_code = 404
|
||||||
|
context.response.print({ "error" => "Resource not found" }.to_json)
|
||||||
super(context)
|
super(context)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
class UnprocessableEntityException < Kemal::Exceptions::CustomException
|
class UnprocessableEntityException < Kemal::Exceptions::CustomException
|
||||||
def initialize(context, message : Hash(String, Array(String)))
|
def initialize(context, message : Hash(String, Array(String)))
|
||||||
|
context.response.content_type = "application/json"
|
||||||
context.response.status_code = 422
|
context.response.status_code = 422
|
||||||
context.response.print({ "errors" => message }.to_json)
|
context.response.print({ "errors" => message }.to_json)
|
||||||
super(context)
|
super(context)
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
require "maxminddb"
|
||||||
|
require "log"
|
||||||
|
|
||||||
|
module App::Lib
|
||||||
|
struct IpLookup
|
||||||
|
MMDB_PATH = "data/GeoLite2-Country.mmdb"
|
||||||
|
|
||||||
|
@@reader : MaxMindDB::Reader? = nil
|
||||||
|
@@reader_mutex = Mutex.new
|
||||||
|
|
||||||
|
private def self.get_reader : MaxMindDB::Reader
|
||||||
|
@@reader_mutex.synchronize do
|
||||||
|
@@reader ||= MaxMindDB.open(MMDB_PATH)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.country(ip_address : String) : String?
|
||||||
|
return nil if ip_address == "Unknown" || ip_address.empty?
|
||||||
|
|
||||||
|
begin
|
||||||
|
lookup = get_reader.get(ip_address)
|
||||||
|
lookup["country"]?.try &.["iso_code"]?.try &.as_s
|
||||||
|
rescue ex
|
||||||
|
Log.error { "IP lookup failed: #{ex.message}" }
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.ip_from_address(address_string : String?) : String?
|
||||||
|
return nil if address_string.nil?
|
||||||
|
|
||||||
|
if address_string.includes?('[') # IPv6 with port: [2001:db8::1]:8080
|
||||||
|
address_string.split(']').first.sub('[', '\'')
|
||||||
|
elsif address_string.includes?(':')
|
||||||
|
if address_string.count(':') > 1 # IPv6 without port
|
||||||
|
address_string
|
||||||
|
else # IPv4 with port: 192.168.1.1:8080
|
||||||
|
address_string.split(':').first
|
||||||
|
end
|
||||||
|
else # Address without port
|
||||||
|
address_string
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
require "yaml"
|
||||||
|
require "semantic_version"
|
||||||
|
|
||||||
|
module App::Lib
|
||||||
|
struct UserAgent
|
||||||
|
REGEXES_PATH = "data/uap_core_regexes.yaml"
|
||||||
|
|
||||||
|
@@regexes_cache : YAML::Any? = nil
|
||||||
|
@@compiled_regexes = {} of String => Array(Tuple(Regex, YAML::Any))
|
||||||
|
@@mutex = Mutex.new
|
||||||
|
|
||||||
|
private def self.load_regexes
|
||||||
|
@@mutex.synchronize do
|
||||||
|
if @@regexes_cache.nil?
|
||||||
|
begin
|
||||||
|
regexes_yaml = File.read(REGEXES_PATH)
|
||||||
|
@@regexes_cache = YAML.parse(regexes_yaml)
|
||||||
|
|
||||||
|
# Pre-compile all regexes for better performance
|
||||||
|
["user_agent_parsers", "os_parsers", "device_parsers"].each do |parser_type|
|
||||||
|
@@compiled_regexes[parser_type] = [] of Tuple(Regex, YAML::Any)
|
||||||
|
|
||||||
|
@@regexes_cache.not_nil![parser_type].as_a.each do |parser|
|
||||||
|
regex_str = parser["regex"].as_s
|
||||||
|
options = parser["regex_flag"]?.try(&.as_s) == "i" ?
|
||||||
|
Regex::Options::IGNORE_CASE : Regex::Options::None
|
||||||
|
|
||||||
|
begin
|
||||||
|
compiled_regex = Regex.new(regex_str, options)
|
||||||
|
@@compiled_regexes[parser_type] << {compiled_regex, parser}
|
||||||
|
rescue
|
||||||
|
# Skip invalid regexes
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
rescue ex
|
||||||
|
# If loading fails, set an empty cache to prevent repeated failures
|
||||||
|
@@regexes_cache = YAML.parse("{}")
|
||||||
|
@@compiled_regexes = {} of String => Array(Tuple(Regex, YAML::Any))
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.parse(user_agent_string : String)
|
||||||
|
return {nil, nil, nil, nil} if user_agent_string.empty?
|
||||||
|
|
||||||
|
# Load regexes only once and cache them
|
||||||
|
load_regexes
|
||||||
|
|
||||||
|
family = nil
|
||||||
|
version = nil
|
||||||
|
device = nil
|
||||||
|
os = nil
|
||||||
|
|
||||||
|
@@compiled_regexes["user_agent_parsers"]?.try &.each do |regex_tuple|
|
||||||
|
regex, parser = regex_tuple
|
||||||
|
match = regex.match(user_agent_string)
|
||||||
|
next unless match
|
||||||
|
|
||||||
|
family = match[1]? || nil
|
||||||
|
v1 = (match[2]? || "0").to_i
|
||||||
|
v2 = (match[3]? || "0").to_i
|
||||||
|
v3 = (match[4]? || "0").to_i
|
||||||
|
|
||||||
|
# Apply replacements if defined
|
||||||
|
if replacement = parser["family_replacement"]?
|
||||||
|
family = replacement.as_s.gsub("$1", family.to_s)
|
||||||
|
end
|
||||||
|
|
||||||
|
version = SemanticVersion.new(v1, v2, v3)
|
||||||
|
break
|
||||||
|
end
|
||||||
|
|
||||||
|
@@compiled_regexes["os_parsers"]?.try &.each do |regex_tuple|
|
||||||
|
regex, parser = regex_tuple
|
||||||
|
match = regex.match(user_agent_string)
|
||||||
|
next unless match
|
||||||
|
|
||||||
|
os_family = match[1]? || nil
|
||||||
|
os_v1 = (match[2]? || "0").to_i
|
||||||
|
os_v2 = (match[3]? || "0").to_i
|
||||||
|
os_v3 = (match[4]? || "0").to_i
|
||||||
|
|
||||||
|
# Apply replacements if defined
|
||||||
|
if replacement = parser["os_replacement"]?
|
||||||
|
os_family = replacement.as_s.gsub("$1", os_family.to_s)
|
||||||
|
end
|
||||||
|
|
||||||
|
os = {os_family, SemanticVersion.new(os_v1, os_v2, os_v3)}
|
||||||
|
break
|
||||||
|
end
|
||||||
|
|
||||||
|
@@compiled_regexes["device_parsers"]?.try &.each do |regex_tuple|
|
||||||
|
regex, parser = regex_tuple
|
||||||
|
match = regex.match(user_agent_string)
|
||||||
|
next unless match
|
||||||
|
|
||||||
|
model = match[1]? || nil
|
||||||
|
device_name = model
|
||||||
|
brand = nil
|
||||||
|
|
||||||
|
# Apply replacements if defined
|
||||||
|
if device_replacement = parser["device_replacement"]?
|
||||||
|
device_name = device_replacement.as_s.gsub("$1", device_name.to_s)
|
||||||
|
end
|
||||||
|
|
||||||
|
if model_replacement = parser["model_replacement"]?
|
||||||
|
model = model_replacement.as_s.gsub("$1", model.to_s)
|
||||||
|
end
|
||||||
|
|
||||||
|
if brand_replacement = parser["brand_replacement"]?
|
||||||
|
brand = brand_replacement.as_s
|
||||||
|
end
|
||||||
|
|
||||||
|
device = {model, brand, device_name}
|
||||||
|
break
|
||||||
|
end
|
||||||
|
|
||||||
|
{family, version, device, os}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
module App::Middlewares
|
||||||
|
class CORSHandler < Kemal::Handler
|
||||||
|
exclude ["/api/ping", "/:slug"]
|
||||||
|
|
||||||
|
def initialize(
|
||||||
|
@allow_origin = "*",
|
||||||
|
@allow_methods = "GET, POST, PUT, DELETE, OPTIONS",
|
||||||
|
@allow_headers = "Content-Type, Accept, Origin, X-Api-Key"
|
||||||
|
)
|
||||||
|
end
|
||||||
|
|
||||||
|
def call(env)
|
||||||
|
return call_next(env) if exclude_match?(env)
|
||||||
|
|
||||||
|
env.response.headers["Access-Control-Allow-Origin"] = @allow_origin
|
||||||
|
env.response.headers["Access-Control-Allow-Methods"] = @allow_methods
|
||||||
|
env.response.headers["Access-Control-Allow-Headers"] = @allow_headers
|
||||||
|
|
||||||
|
if env.request.method == "OPTIONS"
|
||||||
|
env.response.status_code = 200
|
||||||
|
env.response.content_type = "text/plain"
|
||||||
|
env.response.print("")
|
||||||
|
return env
|
||||||
|
end
|
||||||
|
|
||||||
|
call_next(env)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
require "crecto"
|
||||||
|
|
||||||
|
module App::Models
|
||||||
|
class Click < Crecto::Model
|
||||||
|
schema :clicks do
|
||||||
|
field :id, Int64, primary_key: true
|
||||||
|
field :user_agent, String
|
||||||
|
field :country, String
|
||||||
|
field :browser, String
|
||||||
|
field :os, String
|
||||||
|
field :referer, String
|
||||||
|
|
||||||
|
belongs_to :link, Link
|
||||||
|
end
|
||||||
|
|
||||||
|
validate_required [:user_agent, :referer]
|
||||||
|
end
|
||||||
|
end
|
||||||
+3
-3
@@ -6,17 +6,17 @@ require "./user.cr"
|
|||||||
module App::Models
|
module App::Models
|
||||||
class Link < Crecto::Model
|
class Link < Crecto::Model
|
||||||
schema :links do
|
schema :links do
|
||||||
field :id, String, primary_key: true
|
field :id, Int64, primary_key: true
|
||||||
field :slug, String
|
field :slug, String
|
||||||
field :url, String
|
field :url, String
|
||||||
field :click_counter, Int64, default: 0
|
|
||||||
|
|
||||||
belongs_to :user, User
|
belongs_to :user, User
|
||||||
|
has_many :clicks, Click
|
||||||
end
|
end
|
||||||
|
|
||||||
unique_constraint :slug
|
unique_constraint :slug
|
||||||
|
|
||||||
validate_required [:slug, :url]
|
validate_required [:slug, :url]
|
||||||
validate_format :url, /\A(?:https?:\/\/)?(?:[\w-]+\.)+[\w-]+(?:\/\S*)?/
|
validate_format :url, /\A(?:(https?:\/\/)?(?:[\w-]+\.)+[a-z]{2,})(?::\d+)?(?:[\/?#]\S*)?\z/i
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ require "crecto"
|
|||||||
module App::Models
|
module App::Models
|
||||||
class User < Crecto::Model
|
class User < Crecto::Model
|
||||||
schema :users do
|
schema :users do
|
||||||
field :id, String, primary_key: true
|
field :id, Int64, primary_key: true
|
||||||
field :name, String
|
field :name, String
|
||||||
field :api_key, String
|
field :api_key, String
|
||||||
end
|
end
|
||||||
|
|||||||
+25
-18
@@ -1,37 +1,44 @@
|
|||||||
require "./controllers/**"
|
require "./controllers/**"
|
||||||
|
|
||||||
|
require "kemal"
|
||||||
|
|
||||||
|
add_handler App::Middlewares::CORSHandler.new
|
||||||
|
add_handler App::Middlewares::Auth.new
|
||||||
|
|
||||||
module App
|
module App
|
||||||
before_all do |env|
|
get "/:slug", &App::Controllers::ClickController.redirect_handler
|
||||||
env.response.headers["Access-Control-Allow-Origin"] = "*"
|
|
||||||
env.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
|
|
||||||
env.response.headers["Access-Control-Allow-Headers"] = "Content-Type, Accept, X-Api-Key"
|
|
||||||
end
|
|
||||||
|
|
||||||
after_all do |env|
|
|
||||||
env.response.content_type = "application/json"
|
|
||||||
end
|
|
||||||
|
|
||||||
|
# Namespace /api
|
||||||
get "/api/ping" do |env|
|
get "/api/ping" do |env|
|
||||||
Controllers::Ping::Get.new.call(env)
|
Controllers::PingController.new(env).ping
|
||||||
end
|
|
||||||
|
|
||||||
get "/:slug" do |env|
|
|
||||||
Controllers::Link::Index.new.call(env)
|
|
||||||
end
|
end
|
||||||
|
|
||||||
get "/api/links" do |env|
|
get "/api/links" do |env|
|
||||||
Controllers::Link::All.new.call(env)
|
Controllers::LinkController.new(env).list_all
|
||||||
|
end
|
||||||
|
|
||||||
|
get "/api/links/:id" do |env|
|
||||||
|
Controllers::LinkController.new(env).get
|
||||||
|
end
|
||||||
|
|
||||||
|
get "/api/links/:id/clicks" do |env|
|
||||||
|
Controllers::LinkController.new(env).list_clicks
|
||||||
end
|
end
|
||||||
|
|
||||||
post "/api/links" do |env|
|
post "/api/links" do |env|
|
||||||
Controllers::Link::Create.new.call(env)
|
Controllers::LinkController.new(env).create
|
||||||
end
|
end
|
||||||
|
|
||||||
put "/api/links/:id" do |env|
|
put "/api/links/:id" do |env|
|
||||||
Controllers::Link::Update.new.call(env)
|
Controllers::LinkController.new(env).update
|
||||||
end
|
end
|
||||||
|
|
||||||
delete "/api/links/:id" do |env|
|
delete "/api/links/:id" do |env|
|
||||||
Controllers::Link::Delete.new.call(env)
|
Controllers::LinkController.new(env).delete
|
||||||
|
end
|
||||||
|
|
||||||
|
error 500 do |env|
|
||||||
|
App::InternalServerErrorException.new(env)
|
||||||
|
""
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
require "json"
|
||||||
|
|
||||||
|
require "../models/click"
|
||||||
|
|
||||||
|
module App::Serializers
|
||||||
|
class Click
|
||||||
|
def initialize(@click : App::Models::Click)
|
||||||
|
end
|
||||||
|
|
||||||
|
def to_json(builder : JSON::Builder)
|
||||||
|
builder.object do
|
||||||
|
builder.field("id", @click.id)
|
||||||
|
builder.field("user_agent", @click.user_agent)
|
||||||
|
builder.field("country", @click.country)
|
||||||
|
builder.field("browser", @click.browser)
|
||||||
|
builder.field("os", @click.os)
|
||||||
|
builder.field("referer", @click.referer)
|
||||||
|
builder.field("created_at", @click.created_at)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
+10
-1
@@ -1,6 +1,7 @@
|
|||||||
require "json"
|
require "json"
|
||||||
|
|
||||||
require "../models/link"
|
require "../models/link"
|
||||||
|
require "./click"
|
||||||
|
|
||||||
module App::Serializers
|
module App::Serializers
|
||||||
class Link
|
class Link
|
||||||
@@ -15,7 +16,15 @@ module App::Serializers
|
|||||||
builder.field("id", @link.id)
|
builder.field("id", @link.id)
|
||||||
builder.field("refer", @refer)
|
builder.field("refer", @refer)
|
||||||
builder.field("origin", @link.url)
|
builder.field("origin", @link.url)
|
||||||
builder.field("clicks", @link.click_counter)
|
|
||||||
|
begin
|
||||||
|
clicks = @link.clicks
|
||||||
|
unless clicks.empty?
|
||||||
|
builder.field("clicks", clicks.map { |click| App::Serializers::Click.new(click) })
|
||||||
|
end
|
||||||
|
rescue Crecto::AssociationNotLoaded
|
||||||
|
# Association not loaded, skip this field silently
|
||||||
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+106
-4
@@ -1,16 +1,18 @@
|
|||||||
|
require "file_utils"
|
||||||
|
require "http/client"
|
||||||
|
|
||||||
require "../config/*"
|
require "../config/*"
|
||||||
require "../lib/*"
|
require "../lib/*"
|
||||||
require "../models/*"
|
require "../models/*"
|
||||||
|
|
||||||
module App::Services::Cli
|
module App::Services::Cli
|
||||||
def self.create_user(name)
|
def self.create_user(name, api_key = nil)
|
||||||
user = App::Models::User.new
|
user = App::Models::User.new
|
||||||
user.id = UUID.v4.to_s
|
|
||||||
user.name = name
|
user.name = name
|
||||||
user.api_key = Random::Secure.urlsafe_base64()
|
user.api_key = api_key || Random::Secure.urlsafe_base64()
|
||||||
|
|
||||||
changeset = App::Lib::Database.insert(user)
|
changeset = App::Lib::Database.insert(user)
|
||||||
return changeset.errors if !changeset.valid?
|
return changeset.errors unless changeset.valid?
|
||||||
|
|
||||||
"New user created: Name: #{user.name}, X-Api-Key: #{user.api_key}"
|
"New user created: Name: #{user.name}, X-Api-Key: #{user.api_key}"
|
||||||
end
|
end
|
||||||
@@ -35,4 +37,104 @@ module App::Services::Cli
|
|||||||
|
|
||||||
"User with ID #{user_id} deleted successfully"
|
"User with ID #{user_id} deleted successfully"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def self.setup_admin_user
|
||||||
|
admin_name = ENV["ADMIN_NAME"]?
|
||||||
|
admin_api_key = ENV["ADMIN_API_KEY"]?
|
||||||
|
|
||||||
|
if admin_name && admin_api_key
|
||||||
|
query = App::Lib::Database::Query.where(name: admin_name, api_key: admin_api_key).limit(1)
|
||||||
|
existing_user = App::Lib::Database.all(App::Models::User, query).first?
|
||||||
|
|
||||||
|
return if existing_user
|
||||||
|
|
||||||
|
puts "Admin user setup detected. Creating admin user..."
|
||||||
|
result = create_user(admin_name, admin_api_key)
|
||||||
|
puts result
|
||||||
|
else
|
||||||
|
puts "Admin setup skipped: Missing ADMIN_NAME or ADMIN_API_KEY environment variables."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.update_uap_regexes
|
||||||
|
puts "Downloading User-Agent Parser core regexes..."
|
||||||
|
|
||||||
|
FileUtils.mkdir_p("data")
|
||||||
|
url = "https://raw.githubusercontent.com/ua-parser/uap-core/master/regexes.yaml"
|
||||||
|
output_file = "data/uap_core_regexes.yaml"
|
||||||
|
|
||||||
|
begin
|
||||||
|
http_get_with_redirect(url) do |response|
|
||||||
|
File.write(output_file, response.body_io.gets_to_end)
|
||||||
|
end
|
||||||
|
puts "User-Agent regexes downloaded to #{output_file}"
|
||||||
|
rescue e
|
||||||
|
puts "Error: Failed to download UAP core regexes: #{e.message}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def self.download_geolite_db
|
||||||
|
puts "Downloading GeoLite2 Country database..."
|
||||||
|
|
||||||
|
FileUtils.mkdir_p("data")
|
||||||
|
url = "https://github.com/P3TERX/GeoLite.mmdb/raw/download/GeoLite2-Country.mmdb"
|
||||||
|
output_file = "data/GeoLite2-Country.mmdb"
|
||||||
|
|
||||||
|
begin
|
||||||
|
File.open(output_file, "wb") do |file|
|
||||||
|
http_get_with_redirect(url) do |response|
|
||||||
|
IO.copy(response.body_io, file)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
puts "GeoLite2 database downloaded to #{output_file}"
|
||||||
|
rescue e
|
||||||
|
puts "Error: Failed to download GeoLite2 database: #{e.message}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private def self.http_get_with_redirect(url : String, max_redirects = 5)
|
||||||
|
redirects = 0
|
||||||
|
|
||||||
|
while redirects < max_redirects
|
||||||
|
uri = URI.parse(url)
|
||||||
|
client = HTTP::Client.new(uri)
|
||||||
|
|
||||||
|
success = false
|
||||||
|
follow_redirect = false
|
||||||
|
redirect_url = nil
|
||||||
|
|
||||||
|
begin
|
||||||
|
client.get(uri.request_target) do |response|
|
||||||
|
case response.status_code
|
||||||
|
when 200
|
||||||
|
yield response
|
||||||
|
success = true
|
||||||
|
when 301, 302
|
||||||
|
if new_location = response.headers["Location"]?
|
||||||
|
puts "Following redirect to: #{new_location}"
|
||||||
|
redirect_url = new_location
|
||||||
|
follow_redirect = true
|
||||||
|
else
|
||||||
|
raise "Received redirect status but no Location header"
|
||||||
|
end
|
||||||
|
else
|
||||||
|
raise "Failed request with status code: #{response.status_code}"
|
||||||
|
end
|
||||||
|
end
|
||||||
|
ensure
|
||||||
|
client.close
|
||||||
|
end
|
||||||
|
|
||||||
|
return if success
|
||||||
|
|
||||||
|
if follow_redirect && redirect_url
|
||||||
|
url = redirect_url
|
||||||
|
redirects += 1
|
||||||
|
else
|
||||||
|
break
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
raise "Too many redirects (#{max_redirects})"
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
require "digest"
|
||||||
|
require "base64"
|
||||||
|
|
||||||
|
module App::Services::SlugService
|
||||||
|
def self.shorten_url(url : String, user_id : Int64) : String
|
||||||
|
combined = "#{user_id}-#{url}"
|
||||||
|
crc32_hash = Digest::CRC32.digest(combined)
|
||||||
|
base62_encoded = Base64.urlsafe_encode(crc32_hash).strip.tr("-_=", "")
|
||||||
|
|
||||||
|
base62_encoded
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
module App
|
|
||||||
VERSION = "0.1.0"
|
|
||||||
end
|
|
||||||
Executable
+258
@@ -0,0 +1,258 @@
|
|||||||
|
#!/usr/bin/env crystal
|
||||||
|
|
||||||
|
require "http/client"
|
||||||
|
require "json"
|
||||||
|
require "file_utils"
|
||||||
|
|
||||||
|
# Configuration variables
|
||||||
|
SERVER_URL = "http://localhost:4000"
|
||||||
|
API_URL = "#{SERVER_URL}/api/links"
|
||||||
|
API_KEY = "secure_api_key_1"
|
||||||
|
NUMBER_OF_REQUESTS = 100000
|
||||||
|
|
||||||
|
CONTAINER_NAME = "bit"
|
||||||
|
STATS_FILE = "resource_usage.txt"
|
||||||
|
|
||||||
|
class ResourceMonitor
|
||||||
|
def initialize(@container_name : String)
|
||||||
|
@running = false
|
||||||
|
@stats = [] of {timestamp: Time, cpu: Float64, memory: Float64}
|
||||||
|
end
|
||||||
|
|
||||||
|
def start
|
||||||
|
@running = true
|
||||||
|
@stats.clear
|
||||||
|
|
||||||
|
# Initialize stats file with header
|
||||||
|
File.write(STATS_FILE, "Timestamp\tCPU(%)\tMemory(MiB)\n")
|
||||||
|
|
||||||
|
spawn do
|
||||||
|
while @running
|
||||||
|
if stat = capture_stats
|
||||||
|
# Append each measurement directly to the file
|
||||||
|
File.open(STATS_FILE, "a") do |file|
|
||||||
|
file.puts "#{stat[:timestamp].to_unix}\t#{stat[:cpu]}\t#{stat[:memory]}"
|
||||||
|
end
|
||||||
|
@stats << stat
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def stop
|
||||||
|
@running = false
|
||||||
|
end
|
||||||
|
|
||||||
|
def avg_stats
|
||||||
|
return {cpu: 0.0, memory: 0.0} if @stats.empty?
|
||||||
|
|
||||||
|
total_cpu = 0.0
|
||||||
|
total_memory = 0.0
|
||||||
|
@stats.each do |stat|
|
||||||
|
total_cpu += stat[:cpu]
|
||||||
|
total_memory += stat[:memory]
|
||||||
|
end
|
||||||
|
|
||||||
|
{
|
||||||
|
cpu: total_cpu / @stats.size,
|
||||||
|
memory: total_memory / @stats.size
|
||||||
|
}
|
||||||
|
end
|
||||||
|
|
||||||
|
private def capture_stats
|
||||||
|
output = IO::Memory.new
|
||||||
|
process = Process.run(
|
||||||
|
"docker", ["stats", "--no-stream", "--format", "{{.CPUPerc}},{{.MemUsage}}", @container_name],
|
||||||
|
output: output
|
||||||
|
)
|
||||||
|
|
||||||
|
if process.success?
|
||||||
|
line = output.to_s.strip
|
||||||
|
parts = line.split(",")
|
||||||
|
if parts.size == 2
|
||||||
|
cpu_part = parts[0].gsub("%", "").to_f
|
||||||
|
|
||||||
|
# Extract the memory value properly by removing the "MiB" suffix
|
||||||
|
mem_string = parts[1].split.first
|
||||||
|
mem_part = mem_string.gsub(/[A-Za-z]+$/, "").to_f
|
||||||
|
|
||||||
|
return {timestamp: Time.utc, cpu: cpu_part, memory: mem_part}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
nil
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def check_dependencies
|
||||||
|
{"docker", "jq", "bombardier"}.each do |cmd|
|
||||||
|
process = Process.run("which", [cmd], output: Process::Redirect::Close)
|
||||||
|
unless process.success?
|
||||||
|
puts "Error: #{cmd} is not installed. Please install it to proceed."
|
||||||
|
exit(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def setup_containers
|
||||||
|
puts "Setting up..."
|
||||||
|
|
||||||
|
process = Process.run("docker", ["compose", "up", "-d"])
|
||||||
|
unless process.success?
|
||||||
|
puts "Failed to start Docker containers."
|
||||||
|
exit(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
puts "Waiting for the application to be ready..."
|
||||||
|
until begin
|
||||||
|
HTTP::Client.get("#{SERVER_URL}/api/ping").success?
|
||||||
|
rescue
|
||||||
|
false
|
||||||
|
end
|
||||||
|
sleep 1.seconds
|
||||||
|
end
|
||||||
|
|
||||||
|
puts "Seeding the database..."
|
||||||
|
process = Process.run("docker", ["compose", "exec", "app", "sh", "-c", "sqlite3 ./sqlite/data.db < ./db/seed.sql"])
|
||||||
|
|
||||||
|
unless process.success?
|
||||||
|
puts "Error on seeding database"
|
||||||
|
exit(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
puts "Checking seed results..."
|
||||||
|
until begin
|
||||||
|
HTTP::Client.get(
|
||||||
|
"#{API_URL}?limit=1",
|
||||||
|
headers: HTTP::Headers{"X-Api-Key" => API_KEY}
|
||||||
|
).success?
|
||||||
|
rescue
|
||||||
|
false
|
||||||
|
end
|
||||||
|
sleep 2.seconds
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def run_benchmark
|
||||||
|
puts "Fetching all created links from /api/links..."
|
||||||
|
|
||||||
|
response = HTTP::Client.get(
|
||||||
|
"#{API_URL}?limit=10000",
|
||||||
|
headers: HTTP::Headers{"X-Api-Key" => API_KEY}
|
||||||
|
)
|
||||||
|
|
||||||
|
sleep 2.seconds
|
||||||
|
unless response.success?
|
||||||
|
puts "Failed to fetch links. Status: #{response.status_code}"
|
||||||
|
exit(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
data = JSON.parse(response.body)
|
||||||
|
links = data["data"].as_a.map { |link| link["refer"].as_s }
|
||||||
|
|
||||||
|
random_link = links.sample
|
||||||
|
puts "Selected link for benchmarking: #{random_link}"
|
||||||
|
|
||||||
|
puts "Starting benchmark with Bombardier..."
|
||||||
|
|
||||||
|
sleep 2.seconds
|
||||||
|
process = Process.new(
|
||||||
|
"bombardier",
|
||||||
|
["-n", NUMBER_OF_REQUESTS.to_s, "-l", "--disableKeepAlives", random_link],
|
||||||
|
output: Process::Redirect::Inherit,
|
||||||
|
error: Process::Redirect::Inherit
|
||||||
|
)
|
||||||
|
|
||||||
|
status = process.wait
|
||||||
|
|
||||||
|
if status.success?
|
||||||
|
puts "Benchmark completed successfully."
|
||||||
|
else
|
||||||
|
puts "Bombardier failed with error code: #{status.exit_code}"
|
||||||
|
exit(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def analyze_resource_usage
|
||||||
|
puts "Analyzing resource usage..."
|
||||||
|
|
||||||
|
sleep 2.seconds
|
||||||
|
# Read stats directly from file for more accurate results
|
||||||
|
if File.exists?(STATS_FILE)
|
||||||
|
lines = File.read_lines(STATS_FILE)
|
||||||
|
# Skip header
|
||||||
|
lines = lines[1..-1] if lines.size > 0
|
||||||
|
|
||||||
|
if lines.size > 0
|
||||||
|
total_cpu = 0.0
|
||||||
|
total_memory = 0.0
|
||||||
|
peak_cpu = 0.0
|
||||||
|
peak_memory = 0.0
|
||||||
|
|
||||||
|
lines.each do |line|
|
||||||
|
fields = line.split("\t")
|
||||||
|
if fields.size >= 3
|
||||||
|
begin
|
||||||
|
cpu = fields[1].to_f
|
||||||
|
memory = fields[2].to_f
|
||||||
|
|
||||||
|
total_cpu += cpu
|
||||||
|
total_memory += memory
|
||||||
|
|
||||||
|
# Track peaks in a single pass
|
||||||
|
peak_cpu = cpu if cpu > peak_cpu
|
||||||
|
peak_memory = memory if memory > peak_memory
|
||||||
|
rescue
|
||||||
|
# Skip invalid lines
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
avg_cpu = total_cpu / lines.size
|
||||||
|
avg_memory = total_memory / lines.size
|
||||||
|
|
||||||
|
stats_summary = <<-STATS
|
||||||
|
**** Resource Usage Statistics ****
|
||||||
|
Measurements: #{lines.size}
|
||||||
|
Average CPU Usage: #{avg_cpu.round(2)}%
|
||||||
|
Average Memory Usage: #{avg_memory.round(2)} MiB
|
||||||
|
Peak CPU Usage: #{peak_cpu.round(2)}%
|
||||||
|
Peak Memory Usage: #{peak_memory.round(2)} MiB
|
||||||
|
|
||||||
|
STATS
|
||||||
|
|
||||||
|
File.open(STATS_FILE, "a") do |file|
|
||||||
|
file.puts "\n" + stats_summary
|
||||||
|
end
|
||||||
|
|
||||||
|
puts File.read(STATS_FILE)
|
||||||
|
else
|
||||||
|
puts "No resource usage data collected."
|
||||||
|
end
|
||||||
|
else
|
||||||
|
puts "Resource usage file not found."
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def cleanup
|
||||||
|
Process.run("docker", ["compose", "down"])
|
||||||
|
puts "Cleanup completed. Resource usage data saved in #{STATS_FILE}"
|
||||||
|
end
|
||||||
|
|
||||||
|
def main
|
||||||
|
check_dependencies
|
||||||
|
setup_containers
|
||||||
|
|
||||||
|
monitor = ResourceMonitor.new(CONTAINER_NAME)
|
||||||
|
monitor.start
|
||||||
|
|
||||||
|
begin
|
||||||
|
run_benchmark
|
||||||
|
|
||||||
|
monitor.stop
|
||||||
|
analyze_resource_usage
|
||||||
|
ensure
|
||||||
|
cleanup
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
main
|
||||||
-145
@@ -1,145 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
api_url="http://localhost:4001/api/links"
|
|
||||||
num_links=1000
|
|
||||||
num_requests=10
|
|
||||||
resource_usage_interval=1 # Interval in seconds for resource usage logging
|
|
||||||
|
|
||||||
semaphore="/tmp/semaphore"
|
|
||||||
max_concurrent_processes=$(ulimit -u) # Adjust this number based on your system's capability
|
|
||||||
|
|
||||||
# Initialize semaphore
|
|
||||||
mkfifo $semaphore
|
|
||||||
exec 3<> $semaphore
|
|
||||||
rm $semaphore
|
|
||||||
|
|
||||||
for ((i=0; i<max_concurrent_processes; i++)); do
|
|
||||||
echo >&3
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "Semaphore initialized with $max_concurrent_processes slots."
|
|
||||||
|
|
||||||
function get_resource_usage {
|
|
||||||
while true; do
|
|
||||||
docker stats --no-stream --format "{{.MemUsage}} {{.CPUPerc}}" url-shortener >> resource_usage.txt
|
|
||||||
sleep $resource_usage_interval
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
function calculate_average_usage {
|
|
||||||
total_mem=0
|
|
||||||
count=0
|
|
||||||
|
|
||||||
while read -r line; do
|
|
||||||
mem=$(echo $line | awk '{print $1}')
|
|
||||||
|
|
||||||
# Convert memory to MiB if necessary
|
|
||||||
if [[ $mem == *MiB ]]; then
|
|
||||||
mem=$(echo $mem | sed 's/MiB//')
|
|
||||||
elif [[ $mem == *GiB ]]; then
|
|
||||||
mem=$(echo $mem | sed 's/GiB//')
|
|
||||||
mem=$(echo "$mem * 1024" | bc)
|
|
||||||
fi
|
|
||||||
|
|
||||||
total_mem=$(echo "$total_mem + $mem" | bc)
|
|
||||||
((count++))
|
|
||||||
done < resource_usage.txt
|
|
||||||
|
|
||||||
avg_mem=$(echo "scale=2; $total_mem / $count" | bc)
|
|
||||||
rm resource_usage.txt
|
|
||||||
|
|
||||||
echo "Average Memory Usage: $avg_mem MiB"
|
|
||||||
}
|
|
||||||
|
|
||||||
function measure {
|
|
||||||
total_time=0
|
|
||||||
declare -a refer_links
|
|
||||||
|
|
||||||
# Start resource usage logging in the background
|
|
||||||
nohup bash -c "$(declare -f get_resource_usage); get_resource_usage" &> /dev/null &
|
|
||||||
resource_usage_pid=$!
|
|
||||||
disown
|
|
||||||
|
|
||||||
echo "Creating $num_links short links..."
|
|
||||||
for ((i=1; i<=num_links; i++)); do
|
|
||||||
response=$(curl --silent --request POST \
|
|
||||||
--url $api_url \
|
|
||||||
--header "X-Api-Key: $api_key" \
|
|
||||||
--header "Content-Type: application/json" \
|
|
||||||
--data "{ \"url\": \"https://kagi.com\" }")
|
|
||||||
|
|
||||||
refer=$(echo $response | awk -F'"' '/"refer":/{print $(NF-1)}')
|
|
||||||
if [[ -n $refer ]]; then
|
|
||||||
refer_links+=("$refer")
|
|
||||||
if (( i % 100 == 0 )); then
|
|
||||||
echo "Created short link $i/$num_links"
|
|
||||||
fi
|
|
||||||
else
|
|
||||||
echo "Failed to create short link $i"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
|
|
||||||
echo "Accessing each link $num_requests times concurrently..."
|
|
||||||
> times.txt # Ensure times.txt is created and empty
|
|
||||||
|
|
||||||
total_accesses=$((num_links * num_requests))
|
|
||||||
accesses_done=0
|
|
||||||
|
|
||||||
for refer in "${refer_links[@]}"; do
|
|
||||||
for ((i=1; i<=num_requests; i++)); do
|
|
||||||
# Wait for a slot
|
|
||||||
read -u 3
|
|
||||||
{
|
|
||||||
start_time=$(date +%s%6N)
|
|
||||||
curl -s "$refer" >> /dev/null
|
|
||||||
end_time=$(date +%s%6N)
|
|
||||||
elapsed_time=$(echo "$end_time - $start_time" | bc)
|
|
||||||
echo $elapsed_time >> times.txt
|
|
||||||
# Release the slot
|
|
||||||
echo >&3
|
|
||||||
|
|
||||||
((accesses_done++))
|
|
||||||
if (( accesses_done % 10 == 0 )); then
|
|
||||||
echo "Accessed $accesses_done/$total_accesses"
|
|
||||||
fi
|
|
||||||
} &
|
|
||||||
done
|
|
||||||
done
|
|
||||||
|
|
||||||
wait
|
|
||||||
|
|
||||||
# Stop resource usage logging
|
|
||||||
if kill -0 $resource_usage_pid 2>/dev/null; then
|
|
||||||
kill $resource_usage_pid
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Read all elapsed times and calculate total
|
|
||||||
while read -r time; do
|
|
||||||
total_time=$(echo "$total_time + $time" | bc)
|
|
||||||
done < times.txt
|
|
||||||
rm times.txt
|
|
||||||
|
|
||||||
echo "****Results****"
|
|
||||||
|
|
||||||
calculate_average_usage
|
|
||||||
echo "Average Response Time: $(echo "scale=2; $total_time / ($num_links * $num_requests)" | bc) µs"
|
|
||||||
}
|
|
||||||
|
|
||||||
echo "Setup..."
|
|
||||||
|
|
||||||
docker-compose up -d
|
|
||||||
# Ensure migrations are done
|
|
||||||
docker-compose exec -T app migrate
|
|
||||||
|
|
||||||
# Create a new user and capture the API key
|
|
||||||
output=$(docker-compose exec -T app cli --create-user=Admin)
|
|
||||||
api_key=$(echo "$output" | awk -F' ' '/X-Api-Key:/{print $NF}')
|
|
||||||
echo "Captured API Key: $api_key"
|
|
||||||
|
|
||||||
echo "Waiting for database to be ready..."
|
|
||||||
sleep 5
|
|
||||||
|
|
||||||
measure
|
|
||||||
|
|
||||||
# Clean up
|
|
||||||
docker-compose down
|
|
||||||
@@ -5,14 +5,11 @@ require "./app/lib/*"
|
|||||||
require "./app/models/*"
|
require "./app/models/*"
|
||||||
require "./app/serializers/*"
|
require "./app/serializers/*"
|
||||||
require "./app/middlewares/*"
|
require "./app/middlewares/*"
|
||||||
|
require "./app/services/*"
|
||||||
|
|
||||||
require "./app/routes"
|
require "./app/routes"
|
||||||
|
|
||||||
add_context_storage_type(App::Models::User)
|
add_context_storage_type(App::Models::User)
|
||||||
add_handler(App::Middlewares::Auth.new)
|
App::Services::Cli.setup_admin_user
|
||||||
|
|
||||||
error 500 { |env| {"error" => "Internal Server Error" }.to_json}
|
|
||||||
error 401 { |env| {"error" => "Unauthorized" }.to_json}
|
|
||||||
error 404 { |env| {"error" => "Not Found" }.to_json}
|
|
||||||
|
|
||||||
Kemal.run
|
Kemal.run
|
||||||
Binary file not shown.
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,6 @@ CREATE TABLE links (
|
|||||||
user_id TEXT NOT NULL,
|
user_id TEXT NOT NULL,
|
||||||
slug VARCHAR(4) UNIQUE NOT NULL,
|
slug VARCHAR(4) UNIQUE NOT NULL,
|
||||||
url TEXT NOT NULL,
|
url TEXT NOT NULL,
|
||||||
click_counter INTEGER NOT NULL DEFAULT 0,
|
|
||||||
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
CREATE TABLE clicks (
|
||||||
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
link_id TEXT NOT NULL,
|
||||||
|
user_agent TEXT,
|
||||||
|
browser TEXT,
|
||||||
|
os TEXT,
|
||||||
|
source TEXT,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
|
||||||
|
FOREIGN KEY (link_id) REFERENCES links(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL section 'Down' is executed when this migration is rolled back
|
||||||
|
DROP TABLE clicks;
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
|
||||||
|
-- Step 1: Create a new table with the desired column type
|
||||||
|
CREATE TABLE links_new (
|
||||||
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
slug VARCHAR(8) UNIQUE NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 2: Copy data from the old table to the new table
|
||||||
|
INSERT INTO links_new (id, user_id, slug, url, created_at, updated_at)
|
||||||
|
SELECT id, user_id, slug, url, created_at, updated_at FROM links;
|
||||||
|
|
||||||
|
-- Step 3: Drop the old table
|
||||||
|
DROP TABLE links;
|
||||||
|
|
||||||
|
-- Step 4: Rename the new table to the old table's name
|
||||||
|
ALTER TABLE links_new RENAME TO links;
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL section 'Down' is executed when this migration is rolled back
|
||||||
|
|
||||||
|
-- Step 1: Create a new table with the original column type
|
||||||
|
CREATE TABLE links_old (
|
||||||
|
id TEXT PRIMARY KEY NOT NULL,
|
||||||
|
user_id TEXT NOT NULL,
|
||||||
|
slug VARCHAR(4) UNIQUE NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 2: Copy data from the current table to the old table
|
||||||
|
INSERT INTO links_old (id, user_id, slug, url, created_at, updated_at)
|
||||||
|
SELECT id, user_id, substr(slug, 1, 4), url, created_at, updated_at FROM links;
|
||||||
|
|
||||||
|
-- Step 3: Drop the current table
|
||||||
|
DROP TABLE links;
|
||||||
|
|
||||||
|
-- Step 4: Rename the old table to the current table's name
|
||||||
|
ALTER TABLE links_old RENAME TO links;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
ALTER TABLE clicks ADD COLUMN country TEXT;
|
||||||
|
ALTER TABLE clicks RENAME COLUMN source TO referer;
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL section 'Down' is executed when this migration is rolled back
|
||||||
|
ALTER TABLE clicks RENAME COLUMN referer TO source;
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
UPDATE clicks SET user_agent = NULL WHERE user_agent = 'Unknown';
|
||||||
|
UPDATE clicks SET browser = NULL WHERE browser = 'Unknown';
|
||||||
|
UPDATE clicks SET os = NULL WHERE os = 'Unknown';
|
||||||
|
UPDATE clicks SET referer = NULL WHERE referer = 'Unknown';
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL section 'Down' is executed when this migration is rolled back
|
||||||
|
UPDATE clicks SET user_agent = 'Unknown' WHERE user_agent IS NULL;
|
||||||
|
UPDATE clicks SET browser = 'Unknown' WHERE browser IS NULL;
|
||||||
|
UPDATE clicks SET os = 'Unknown' WHERE os IS NULL;
|
||||||
|
UPDATE clicks SET referer = 'Unknown' WHERE referer IS NULL;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
DROP INDEX IF EXISTS idx_links_slug; -- Remove old composite index
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_links_slug_optimized ON links (slug, url);
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL in section 'Down' is executed when this migration is rolled back
|
||||||
|
DROP INDEX IF EXISTS idx_links_slug_optimized;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_links_slug ON links (id, slug, url);
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
-- +micrate Up
|
||||||
|
-- SQL in section 'Up' is executed when this migration is applied
|
||||||
|
-- 1. Create new users table with INTEGER PK
|
||||||
|
CREATE TABLE users_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
name VARCHAR(100) NOT NULL,
|
||||||
|
api_key VARCHAR(64) UNIQUE NOT NULL,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Create a mapping table to track old and new user IDs
|
||||||
|
CREATE TEMPORARY TABLE user_id_map (
|
||||||
|
old_id TEXT,
|
||||||
|
new_id INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Insert users data and capture the mappings
|
||||||
|
INSERT INTO users_new (name, api_key, created_at, updated_at)
|
||||||
|
SELECT name, api_key, created_at, updated_at FROM users;
|
||||||
|
|
||||||
|
INSERT INTO user_id_map
|
||||||
|
SELECT u.id, u_new.id
|
||||||
|
FROM users u
|
||||||
|
JOIN users_new u_new ON u_new.api_key = u.api_key;
|
||||||
|
|
||||||
|
-- 2. Create new links table with INTEGER PK
|
||||||
|
CREATE TABLE links_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
user_id INTEGER NOT NULL,
|
||||||
|
slug VARCHAR(8) UNIQUE NOT NULL,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
FOREIGN KEY (user_id) REFERENCES users_new(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Create a mapping table for links
|
||||||
|
CREATE TEMPORARY TABLE link_id_map (
|
||||||
|
old_id TEXT,
|
||||||
|
new_id INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Insert links data with new user_id foreign keys
|
||||||
|
INSERT INTO links_new (user_id, slug, url, created_at, updated_at)
|
||||||
|
SELECT
|
||||||
|
(SELECT new_id FROM user_id_map WHERE old_id = l.user_id),
|
||||||
|
l.slug,
|
||||||
|
l.url,
|
||||||
|
l.created_at,
|
||||||
|
l.updated_at
|
||||||
|
FROM links l;
|
||||||
|
|
||||||
|
-- Create the mapping for links
|
||||||
|
INSERT INTO link_id_map
|
||||||
|
SELECT l.id, l_new.id
|
||||||
|
FROM links l
|
||||||
|
JOIN links_new l_new ON l_new.slug = l.slug AND l_new.url = l.url;
|
||||||
|
|
||||||
|
-- 3. Create new clicks table with INTEGER PK
|
||||||
|
CREATE TABLE clicks_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
link_id INTEGER NOT NULL,
|
||||||
|
user_agent TEXT,
|
||||||
|
browser TEXT,
|
||||||
|
os TEXT,
|
||||||
|
referer TEXT,
|
||||||
|
country TEXT,
|
||||||
|
created_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
updated_at INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
|
||||||
|
FOREIGN KEY (link_id) REFERENCES links_new(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Insert clicks data with new link_id foreign keys
|
||||||
|
INSERT INTO clicks_new (link_id, user_agent, browser, os, referer, country, created_at, updated_at)
|
||||||
|
SELECT
|
||||||
|
(SELECT new_id FROM link_id_map WHERE old_id = c.link_id),
|
||||||
|
c.user_agent,
|
||||||
|
c.browser,
|
||||||
|
c.os,
|
||||||
|
c.referer,
|
||||||
|
c.country,
|
||||||
|
c.created_at,
|
||||||
|
c.updated_at
|
||||||
|
FROM clicks c;
|
||||||
|
|
||||||
|
-- 4. Drop old tables and rename new tables
|
||||||
|
DROP TABLE clicks;
|
||||||
|
DROP TABLE links;
|
||||||
|
DROP TABLE users;
|
||||||
|
|
||||||
|
ALTER TABLE clicks_new RENAME TO clicks;
|
||||||
|
ALTER TABLE links_new RENAME TO links;
|
||||||
|
ALTER TABLE users_new RENAME TO users;
|
||||||
|
|
||||||
|
-- 5. Drop unused indexes
|
||||||
|
DROP INDEX IF EXISTS index_users_api_key;
|
||||||
|
DROP INDEX IF EXISTS idx_links_slug;
|
||||||
|
DROP INDEX IF EXISTS idx_links_slug_optimized;
|
||||||
|
|
||||||
|
-- +micrate Down
|
||||||
|
-- SQL section 'Down' is executed when this migration is rolled back
|
||||||
+69
@@ -0,0 +1,69 @@
|
|||||||
|
INSERT INTO users (name, api_key)
|
||||||
|
VALUES
|
||||||
|
('User 1', 'secure_api_key_1'),
|
||||||
|
('User 2', 'secure_api_key_2');
|
||||||
|
|
||||||
|
-- Create 10,000 links (5,000 per user)
|
||||||
|
WITH RECURSIVE link_numbers(n) AS (
|
||||||
|
SELECT 1
|
||||||
|
UNION ALL
|
||||||
|
SELECT n+1 FROM link_numbers
|
||||||
|
LIMIT 10000
|
||||||
|
)
|
||||||
|
INSERT INTO links (user_id, slug, url)
|
||||||
|
SELECT
|
||||||
|
((n-1) % 2) + 1, -- User ID (1-2)
|
||||||
|
'slug' || n, -- Unique slug
|
||||||
|
'https://sjdonado.com/page/' || n
|
||||||
|
FROM link_numbers;
|
||||||
|
|
||||||
|
-- Create 1,000 clicks per link (10 million total)
|
||||||
|
WITH RECURSIVE counts(n) AS (
|
||||||
|
SELECT 1
|
||||||
|
UNION ALL
|
||||||
|
SELECT n+1 FROM counts
|
||||||
|
LIMIT 1000
|
||||||
|
)
|
||||||
|
INSERT INTO clicks (link_id, user_agent, browser, os, referer, country)
|
||||||
|
SELECT
|
||||||
|
l.id,
|
||||||
|
CASE (c.n % 5)
|
||||||
|
WHEN 0 THEN 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
|
||||||
|
WHEN 1 THEN 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)'
|
||||||
|
WHEN 2 THEN 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0)'
|
||||||
|
WHEN 3 THEN 'Mozilla/5.0 (X11; Linux x86_64)'
|
||||||
|
ELSE 'Mozilla/5.0 (Android 11; Mobile)'
|
||||||
|
END,
|
||||||
|
CASE (c.n % 3)
|
||||||
|
WHEN 0 THEN 'Firefox'
|
||||||
|
WHEN 1 THEN 'Chrome'
|
||||||
|
ELSE 'Safari'
|
||||||
|
END,
|
||||||
|
CASE (c.n % 4)
|
||||||
|
WHEN 0 THEN 'macOS'
|
||||||
|
WHEN 1 THEN 'Windows'
|
||||||
|
WHEN 2 THEN 'iOS'
|
||||||
|
ELSE 'Android'
|
||||||
|
END,
|
||||||
|
CASE (c.n % 6)
|
||||||
|
WHEN 0 THEN 'https://sjdonado.com'
|
||||||
|
WHEN 1 THEN 'https://donado.co'
|
||||||
|
WHEN 2 THEN 'https://idonthavespotify.donado.co'
|
||||||
|
WHEN 3 THEN 'https://spookyplanning.com'
|
||||||
|
WHEN 4 THEN 'https://github.com/sjdonado'
|
||||||
|
ELSE NULL
|
||||||
|
END,
|
||||||
|
CASE (c.n % 10)
|
||||||
|
WHEN 0 THEN 'Colombia'
|
||||||
|
WHEN 1 THEN 'Brazil'
|
||||||
|
WHEN 2 THEN 'Canada'
|
||||||
|
WHEN 3 THEN 'Germany'
|
||||||
|
WHEN 4 THEN 'France'
|
||||||
|
WHEN 5 THEN 'Japan'
|
||||||
|
WHEN 6 THEN 'Australia'
|
||||||
|
WHEN 7 THEN 'Brazil'
|
||||||
|
WHEN 8 THEN 'India'
|
||||||
|
ELSE 'China'
|
||||||
|
END
|
||||||
|
FROM links l
|
||||||
|
CROSS JOIN counts c;
|
||||||
+9
-3
@@ -1,9 +1,15 @@
|
|||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
|
container_name: bit
|
||||||
build: .
|
build: .
|
||||||
environment:
|
environment:
|
||||||
ENV: production
|
ENV: production
|
||||||
DATABASE_URL: sqlite3://./sqlite/data.db?journal_mode=wal&synchronous=normal&foreign_keys=true
|
ADMIN_NAME: 'Tester'
|
||||||
APP_URL: http://0.0.0.0:4001
|
ADMIN_API_KEY: '0p+mDvbpZGLPGVCXnV+EDduR9Blkv27Dhq9XSzSbdQY='
|
||||||
ports:
|
ports:
|
||||||
- 4001:4000
|
- 4000:4000
|
||||||
|
volumes:
|
||||||
|
- sqlite_data:/app/sqlite
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
sqlite_data:
|
||||||
|
|||||||
+149
@@ -0,0 +1,149 @@
|
|||||||
|
# API Reference
|
||||||
|
|
||||||
|
1. **Ping the API**
|
||||||
|
|
||||||
|
- Endpoint: `GET /api/ping`
|
||||||
|
- Payload: None
|
||||||
|
- Response: 200
|
||||||
|
- Response Example
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": "pong"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
2. **Redirect by Slug**
|
||||||
|
|
||||||
|
- Endpoint: `GET /:slug`
|
||||||
|
- Payload: None
|
||||||
|
- Response: 301
|
||||||
|
|
||||||
|
3. **List All Links**
|
||||||
|
|
||||||
|
- Endpoint: `GET /api/links`
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Query Parameters:
|
||||||
|
- `limit` (optional): Number of results per page (default: 100)
|
||||||
|
- `cursor` (optional): Pagination cursor from previous response
|
||||||
|
- Response: 200
|
||||||
|
- Response Example
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "84f0c7a4-8c4e-4665-b676-cb9c5e40f1db",
|
||||||
|
"refer": "http://localhost:4000/3wP4BQ",
|
||||||
|
"origin": "https://monocuco.donado.co"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": {
|
||||||
|
"has_more": true,
|
||||||
|
"next": "75e0a7f4-9c5e-1235-b546-eb9c5e40f7ac"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **List link by ID**
|
||||||
|
- Endpoint: `GET /api/links/:id`
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Payload: None
|
||||||
|
- Note: This endpoint returns up to 100 of the most recent clicks. For complete click history, use the `/api/links/:id/clicks` endpoint with pagination.
|
||||||
|
- Response: 200
|
||||||
|
- Response Example
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"id": "84f0c7a4-8c4e-4665-b676-cb9c5e40f1db",
|
||||||
|
"refer": "http://localhost:4000/3wP4BQ",
|
||||||
|
"origin": "https://monocuco.donado.co",
|
||||||
|
"clicks": [
|
||||||
|
{
|
||||||
|
"id": "730e2202-58f9-478c-a24c-f1c561df6716",
|
||||||
|
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0",
|
||||||
|
"country": "DE",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"os": "Mac OS X",
|
||||||
|
"referer": "Direct",
|
||||||
|
"created_at": "2024-07-12T19:25:22Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **List Clicks for a Link**
|
||||||
|
- Endpoint: `GET /api/links/:id/clicks`
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Query Parameters:
|
||||||
|
- `limit` (optional): Number of results per page (default: 100)
|
||||||
|
- `cursor` (optional): Pagination cursor from previous response
|
||||||
|
- Response: 200
|
||||||
|
- Response Example
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": [
|
||||||
|
{
|
||||||
|
"id": "730e2202-58f9-478c-a24c-f1c561df6716",
|
||||||
|
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0",
|
||||||
|
"country": "DE",
|
||||||
|
"browser": "Firefox",
|
||||||
|
"os": "Mac OS X",
|
||||||
|
"referer": "Direct",
|
||||||
|
"created_at": "2024-07-12T19:25:22Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pagination": {
|
||||||
|
"has_more": true,
|
||||||
|
"next": "629e3301-47f8-389b-b24c-f1c561df9825"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **Create new link**
|
||||||
|
- Endpoint: `POST /api/links`
|
||||||
|
- Payload:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"url": "https://example.com"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Response: 201
|
||||||
|
- Response Example:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"id": "84f0c7a4-8c4e-4665-b676-cb9c5e40f1db",
|
||||||
|
"refer": "http://localhost:4000/3wP4BQ",
|
||||||
|
"origin": "https://example.com",
|
||||||
|
"clicks": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
7. **Update an existing link by ID**
|
||||||
|
- Endpoint: `PUT /api/links/:id`
|
||||||
|
- Payload:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"url": "https://newexample.com"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Response: 200
|
||||||
|
- Response Example:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"id": "84f0c7a4-8c4e-4665-b676-cb9c5e40f1db",
|
||||||
|
"refer": "http://localhost:4000/3wP4BQ",
|
||||||
|
"origin": "https://newexample.com",
|
||||||
|
"clicks": []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
8. **Delete a link by ID**
|
||||||
|
- Endpoint: `DELETE /api/links/:id`
|
||||||
|
- Payload: None
|
||||||
|
- Headers: `X-Api-Key`
|
||||||
|
- Response: 204
|
||||||
+168
@@ -0,0 +1,168 @@
|
|||||||
|
## CLI
|
||||||
|
|
||||||
|
```
|
||||||
|
Usage: ./cli [options]
|
||||||
|
Options:
|
||||||
|
--create-user=NAME Create a new user with the given name
|
||||||
|
--list-users List all users
|
||||||
|
--delete-user=USER_ID Delete a user by ID
|
||||||
|
--update-data Download all required data files
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run It Anywhere
|
||||||
|
|
||||||
|
### Docker Compose
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up
|
||||||
|
|
||||||
|
# Optional: Generate an api key
|
||||||
|
# docker-compose exec -it app cli --create-user=Admin
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker CLI
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run \
|
||||||
|
--name bit \
|
||||||
|
-p 4000:4000 \
|
||||||
|
-e ENV="production" \
|
||||||
|
-e DATABASE_URL="sqlite3://./sqlite/data.db" \
|
||||||
|
-e APP_URL="http://localhost:4000" \
|
||||||
|
-e ADMIN_NAME="Admin" \
|
||||||
|
-e ADMIN_API_KEY=$(openssl rand -base64 32) \
|
||||||
|
sjdonado/bit
|
||||||
|
|
||||||
|
# Create a new user
|
||||||
|
# docker exec -it bit cli --create-user=Admin
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dokku
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM sjdonado/bit
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dokku apps:create bit
|
||||||
|
|
||||||
|
dokku domains:set bit bit.donado.co
|
||||||
|
dokku letsencrypt:enable bit
|
||||||
|
|
||||||
|
dokku storage:ensure-directory bit-sqlite
|
||||||
|
dokku storage:mount bit /var/lib/dokku/data/storage/bit-sqlite:/usr/src/app/sqlite/
|
||||||
|
|
||||||
|
dokku config:set bit DATABASE_URL="sqlite3://./sqlite/data.db" APP_URL=https://bit.donado.co ADMIN_NAME=Admin ADMIN_API_KEY=$(openssl rand -base64 32)
|
||||||
|
|
||||||
|
dokku ports:add bit http:80:4000
|
||||||
|
dokku ports:add bit https:443:4000
|
||||||
|
|
||||||
|
# Create a new user
|
||||||
|
# dokku run bit cli --create-user=Admin
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dokku (same network)
|
||||||
|
Recommended for lower latency communication (no host network traversal)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dokku network:create bit-net
|
||||||
|
dokku network:set bit attach-post-create bit-net
|
||||||
|
dokku network:set myapp attach-post-create bit-net
|
||||||
|
```
|
||||||
|
|
||||||
|
## Local Development
|
||||||
|
|
||||||
|
### Requirements
|
||||||
|
- Crystal 1.12+
|
||||||
|
- Shards package manager
|
||||||
|
- SQLite3
|
||||||
|
|
||||||
|
### Install Dependencies
|
||||||
|
- linux
|
||||||
|
```bash
|
||||||
|
sudo apt-get update && sudo apt-get install -y crystal libssl-dev libsqlite3-dev
|
||||||
|
```
|
||||||
|
|
||||||
|
- macos
|
||||||
|
```bash
|
||||||
|
brew tap amberframework/micrate
|
||||||
|
brew install micrate
|
||||||
|
```
|
||||||
|
|
||||||
|
### Install Shards and Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
shards run bit
|
||||||
|
```
|
||||||
|
|
||||||
|
- Generate the `X-Api-Key`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
shards run cli -- --create-user=Admin
|
||||||
|
```
|
||||||
|
|
||||||
|
- Run tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ENV=test crystal spec
|
||||||
|
```
|
||||||
|
|
||||||
|
## Benchmark
|
||||||
|
|
||||||
|
- Colima: cpu 1, mem 1
|
||||||
|
- SoC: Apple M3 Pro
|
||||||
|
|
||||||
|
```
|
||||||
|
~/p/bit> colima start --cpu 1 --memory 1
|
||||||
|
INFO[0000] starting colima
|
||||||
|
INFO[0000] runtime: docker
|
||||||
|
INFO[0001] starting ... context=vm
|
||||||
|
INFO[0076] provisioning ... context=docker
|
||||||
|
INFO[0077] starting ... context=docker
|
||||||
|
INFO[0077] done
|
||||||
|
~/p/bit> ./benchmark.cr
|
||||||
|
Setting up...
|
||||||
|
Waiting for the application to be ready...
|
||||||
|
Seeding the database...
|
||||||
|
Checking seed results...
|
||||||
|
Fetching all created links from /api/links...
|
||||||
|
Selected link for benchmarking: http://localhost:4000/slug4280
|
||||||
|
Starting benchmark with Bombardier...
|
||||||
|
Bombarding http://localhost:4000/slug4280 with 100000 request(s) using 125 connection(s)
|
||||||
|
100000 / 100000 [==============================================================] 100.00% 6562/s 15s
|
||||||
|
Done!
|
||||||
|
Statistics Avg Stdev Max
|
||||||
|
Reqs/sec 6609.73 1508.34 13145.76
|
||||||
|
Latency 18.92ms 2.34ms 74.58ms
|
||||||
|
Latency Distribution
|
||||||
|
50% 18.83ms
|
||||||
|
75% 20.19ms
|
||||||
|
90% 21.80ms
|
||||||
|
95% 23.10ms
|
||||||
|
99% 26.54ms
|
||||||
|
HTTP codes:
|
||||||
|
1xx - 0, 2xx - 0, 3xx - 100000, 4xx - 0, 5xx - 0
|
||||||
|
others - 0
|
||||||
|
Throughput: 1.80MB/s
|
||||||
|
Benchmark completed successfully.
|
||||||
|
Analyzing resource usage...
|
||||||
|
Timestamp CPU(%) Memory(MiB)
|
||||||
|
1742732843 0.02 44.71
|
||||||
|
1742732845 0.02 44.71
|
||||||
|
1742732847 85.34 69.55
|
||||||
|
1742732849 83.5 69.93
|
||||||
|
1742732851 84.26 69.97
|
||||||
|
1742732853 83.64 70.01
|
||||||
|
1742732855 84.23 70.04
|
||||||
|
1742732857 86.41 69.17
|
||||||
|
1742732859 85.77 69.2
|
||||||
|
1742732861 59.67 68.55
|
||||||
|
|
||||||
|
**** Resource Usage Statistics ****
|
||||||
|
Measurements: 10
|
||||||
|
Average CPU Usage: 65.29%
|
||||||
|
Average Memory Usage: 64.58 MiB
|
||||||
|
Peak CPU Usage: 86.41%
|
||||||
|
Peak Memory Usage: 70.04 MiB
|
||||||
|
Cleanup completed. Resource usage data saved in resource_usage.txt
|
||||||
|
```
|
||||||
+12
-4
@@ -1,4 +1,3 @@
|
|||||||
require "uuid"
|
|
||||||
require "option_parser"
|
require "option_parser"
|
||||||
|
|
||||||
require "../app/services/cli"
|
require "../app/services/cli"
|
||||||
@@ -19,11 +18,20 @@ OptionParser.parse do |parser|
|
|||||||
exit
|
exit
|
||||||
end
|
end
|
||||||
|
|
||||||
|
parser.on("--update-data", "Download all required data files (UA Parser and GeoLite2)") do
|
||||||
|
puts "=== Starting data files update ==="
|
||||||
|
App::Services::Cli.update_uap_regexes
|
||||||
|
App::Services::Cli.download_geolite_db
|
||||||
|
puts "=== All data files updated successfully ==="
|
||||||
|
exit
|
||||||
|
end
|
||||||
|
|
||||||
if ARGV.empty?
|
if ARGV.empty?
|
||||||
puts "Usage: ./cli [options]"
|
puts "Usage: ./cli [options]"
|
||||||
puts "Options:"
|
puts "Options:"
|
||||||
puts " --create-user=NAME Create a new user with the given name"
|
puts " --create-user=NAME Create a new user with the given name"
|
||||||
puts " --list-users List all users"
|
puts " --list-users List all users"
|
||||||
puts " --delete-user=USER_ID Delete a user by ID"
|
puts " --delete-user=USER_ID Delete a user by ID"
|
||||||
|
puts " --update-data Download all required data files"
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
require "sqlite3"
|
|
||||||
require"micrate"
|
|
||||||
|
|
||||||
require "../app/config/env"
|
|
||||||
|
|
||||||
Micrate::DB.connection_url = ENV["DATABASE_URL"]
|
|
||||||
Micrate::Cli.run_up
|
|
||||||
@@ -20,10 +20,18 @@ shards:
|
|||||||
git: https://github.com/crystal-loot/exception_page.git
|
git: https://github.com/crystal-loot/exception_page.git
|
||||||
version: 0.4.1
|
version: 0.4.1
|
||||||
|
|
||||||
|
ipaddress:
|
||||||
|
git: https://github.com/sija/ipaddress.cr.git
|
||||||
|
version: 0.2.3
|
||||||
|
|
||||||
kemal:
|
kemal:
|
||||||
git: https://github.com/kemalcr/kemal.git
|
git: https://github.com/kemalcr/kemal.git
|
||||||
version: 1.5.0
|
version: 1.5.0
|
||||||
|
|
||||||
|
maxminddb:
|
||||||
|
git: https://github.com/delef/maxminddb.cr.git
|
||||||
|
version: 1.5.0
|
||||||
|
|
||||||
micrate:
|
micrate:
|
||||||
git: https://github.com/amberframework/micrate.git
|
git: https://github.com/amberframework/micrate.git
|
||||||
version: 0.15.1
|
version: 0.15.1
|
||||||
|
|||||||
@@ -1,16 +1,14 @@
|
|||||||
name: url-shortener
|
name: bit
|
||||||
version: 0.1.0
|
version: 1.5.2
|
||||||
|
|
||||||
authors:
|
authors:
|
||||||
- Juan Rodriguez <sjdonado@icloud.com>
|
- Juan Rodriguez <sjdonado@icloud.com>
|
||||||
|
|
||||||
targets:
|
targets:
|
||||||
url-shortener:
|
bit:
|
||||||
main: url-shortener.cr
|
main: bit.cr
|
||||||
cli:
|
cli:
|
||||||
main: scripts/cli.cr
|
main: scripts/cli.cr
|
||||||
migrate:
|
|
||||||
main: scripts/migrate.cr
|
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
kemal:
|
kemal:
|
||||||
@@ -22,6 +20,8 @@ dependencies:
|
|||||||
micrate:
|
micrate:
|
||||||
github: amberframework/micrate
|
github: amberframework/micrate
|
||||||
version: 0.15.1
|
version: 0.15.1
|
||||||
|
maxminddb:
|
||||||
|
github: delef/maxminddb.cr
|
||||||
|
|
||||||
development_dependencies:
|
development_dependencies:
|
||||||
dotenv:
|
dotenv:
|
||||||
@@ -29,6 +29,6 @@ development_dependencies:
|
|||||||
spec-kemal:
|
spec-kemal:
|
||||||
github: kemalcr/spec-kemal
|
github: kemalcr/spec-kemal
|
||||||
|
|
||||||
crystal: '>= 1.12.1'
|
crystal: ">= 1.12.1"
|
||||||
|
|
||||||
license: MIT
|
license: MIT
|
||||||
|
|||||||
+258
-39
@@ -15,10 +15,34 @@ describe "App::Controllers::Link" do
|
|||||||
body: payload.to_json
|
body: payload.to_json
|
||||||
)
|
)
|
||||||
|
|
||||||
parsed_response = Hash(String, Hash(String, String | Int64)).from_json(response.body)
|
parsed_response = Hash(String, Hash(String, String | Int64 | Array(Hash(String, String)))).from_json(response.body)
|
||||||
parsed_response["data"]["origin"].should eq(payload["url"])
|
parsed_response["data"]["origin"].should eq(payload["url"])
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "should return existing link if url already exists" do
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
payload = {"url" => "http://idonthavespotify.donado.co"}
|
||||||
|
post(
|
||||||
|
"/api/links",
|
||||||
|
headers: HTTP::Headers{"Content-Type" => "application/json", "X-Api-Key" => test_user.api_key.to_s},
|
||||||
|
body: payload.to_json
|
||||||
|
)
|
||||||
|
|
||||||
|
first_response = Hash(String, Hash(String, String | Int64 | Array(Hash(String, String)))).from_json(response.body)
|
||||||
|
first_response["data"]["origin"].should eq(payload["url"])
|
||||||
|
|
||||||
|
post(
|
||||||
|
"/api/links",
|
||||||
|
headers: HTTP::Headers{"Content-Type" => "application/json", "X-Api-Key" => test_user.api_key.to_s},
|
||||||
|
body: payload.to_json
|
||||||
|
)
|
||||||
|
|
||||||
|
second_response = Hash(String, Hash(String, String | Int64 | Array(Hash(String, String)))).from_json(response.body)
|
||||||
|
second_response["data"]["origin"].should eq(payload["url"])
|
||||||
|
second_response["data"]["id"].should eq(first_response["data"]["id"])
|
||||||
|
end
|
||||||
|
|
||||||
it "should return 400 - url required field" do
|
it "should return 400 - url required field" do
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
@@ -51,61 +75,94 @@ describe "App::Controllers::Link" do
|
|||||||
payload = {"url" => "https://kagi.com"}
|
payload = {"url" => "https://kagi.com"}
|
||||||
post("/api/links", headers: HTTP::Headers{"Content-Type" => "application/json"}, body: payload.to_json)
|
post("/api/links", headers: HTTP::Headers{"Content-Type" => "application/json"}, body: payload.to_json)
|
||||||
|
|
||||||
expected = {"error" => "Unauthorized"}.to_json
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
response.status_code.should eq(401)
|
response.status_code.should eq(401)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "Index" do
|
describe "Index" do
|
||||||
it "should redirect to origin domain" do
|
it "should redirect to origin domain with forwarded headers" do
|
||||||
link = "https://kagi.com"
|
link = "https://test.com"
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
test_link = create_test_link(test_user, link)
|
test_link = create_test_link(test_user, link)
|
||||||
serialized_link = App::Serializers::Link.new(test_link)
|
serialized_link = App::Serializers::Link.new(test_link)
|
||||||
|
|
||||||
get(serialized_link.refer, headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0"
|
||||||
|
|
||||||
|
get(serialized_link.refer, headers: HTTP::Headers{
|
||||||
|
"X-Api-Key" => test_user.api_key.to_s,
|
||||||
|
"User-Agent" => user_agent
|
||||||
|
})
|
||||||
|
|
||||||
response.headers["Location"].should eq(link)
|
response.headers["Location"].should eq(link)
|
||||||
|
response.headers["User-Agent"].should eq(user_agent)
|
||||||
|
response.headers.has_key?("X-Forwarded-For").should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should increase click counter after redirect" do
|
it "should create a new click after redirect with proper information" do
|
||||||
link = "https://kagi.com"
|
link = "https://sjdonado.com"
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
test_link = create_test_link(test_user, link)
|
test_link = create_test_link(test_user, link)
|
||||||
serialized_link = App::Serializers::Link.new(test_link)
|
serialized_link = App::Serializers::Link.new(test_link)
|
||||||
|
|
||||||
get(serialized_link.refer, headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0"
|
||||||
Fiber.yield
|
referer = "https://example.com/page"
|
||||||
|
|
||||||
|
get(serialized_link.refer, headers: HTTP::Headers{
|
||||||
|
"User-Agent" => user_agent,
|
||||||
|
"Referer" => referer
|
||||||
|
})
|
||||||
|
|
||||||
|
Fiber.yield # replace yield with sleep 5 to debug errors
|
||||||
|
|
||||||
response.headers["Location"].should eq(link)
|
response.headers["Location"].should eq(link)
|
||||||
|
|
||||||
|
# Verify that the click was recorded
|
||||||
updated_test_link = get_test_link(test_link.id)
|
updated_test_link = get_test_link(test_link.id)
|
||||||
updated_test_link.click_counter.should eq(1)
|
updated_test_link.clicks.size.should eq(test_link.clicks.size + 1)
|
||||||
|
|
||||||
|
# Verify click details
|
||||||
|
latest_click = updated_test_link.clicks.last
|
||||||
|
latest_click.user_agent.should eq(user_agent)
|
||||||
|
latest_click.browser.should eq("Firefox")
|
||||||
|
latest_click.os.should eq("Mac OS X")
|
||||||
|
latest_click.referer.should eq("example.com") # Should extract host from the referer
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should create a click with utm_source when no referer is provided" do
|
||||||
|
link = "https://sjdonado.com"
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
test_link = create_test_link(test_user, link)
|
||||||
|
serialized_link = App::Serializers::Link.new(test_link)
|
||||||
|
|
||||||
|
# Add utm_source parameter
|
||||||
|
get("#{serialized_link.refer}?utm_source=email_campaign")
|
||||||
|
|
||||||
|
Fiber.yield
|
||||||
|
|
||||||
|
updated_test_link = get_test_link(test_link.id)
|
||||||
|
latest_click = updated_test_link.clicks.last
|
||||||
|
latest_click.referer.should eq("email_campaign")
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should return 404 - link does not exist" do
|
it "should return 404 - link does not exist" do
|
||||||
link = "https://kagi.com"
|
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
test_link = create_test_link(test_user, link)
|
get("https://localhost:4001/R4kj2")
|
||||||
serialized_link = App::Serializers::Link.new(test_link)
|
|
||||||
|
|
||||||
delete_test_link(test_link.id)
|
expected = {"error" => "Resource not found"}.to_json
|
||||||
|
|
||||||
get(serialized_link.refer, headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
|
||||||
|
|
||||||
expected = {"error" => "Not Found"}.to_json
|
|
||||||
response.status_code.should eq(404)
|
response.status_code.should eq(404)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
describe "All" do
|
describe "All" do
|
||||||
it "should return all links" do
|
it "should return all links with pagination" do
|
||||||
links = ["https://google.com", "google.com", "google.com.co"]
|
links = ["https://sjdonado.com", "sjdonado.com", "sjdonado.com.co"]
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
links.each do |link|
|
links.each do |link|
|
||||||
@@ -114,14 +171,58 @@ describe "App::Controllers::Link" do
|
|||||||
|
|
||||||
get("/api/links", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
get("/api/links", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
parsed_response = Hash(String, Array(Hash(String, String | Int64))).from_json(response.body)
|
parsed_response = Hash(String, Array(Hash(String, String | Int64)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
parsed_response["data"][0]["origin"].should eq(links[0])
|
|
||||||
parsed_response["data"][1]["origin"].should eq(links[1])
|
# Check that each link is in the response data
|
||||||
parsed_response["data"][2]["origin"].should eq(links[2])
|
origins = parsed_response["data"].as(Array).map { |link| link["origin"] }
|
||||||
|
links.each do |link|
|
||||||
|
origins.should contain(link)
|
||||||
|
end
|
||||||
|
|
||||||
|
parsed_response["pagination"].as(Hash)["has_more"].should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should respect custom limit parameter" do
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
5.times do |i|
|
||||||
|
create_test_link(test_user, "https://example.com/#{i}")
|
||||||
|
end
|
||||||
|
|
||||||
|
get("/api/links?limit=2", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
parsed_response = Hash(String, Array(Hash(String, String | Int64)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
parsed_response["data"].as(Array).size.should eq(2)
|
||||||
|
parsed_response["pagination"].as(Hash)["has_more"].should be_true
|
||||||
|
parsed_response["pagination"].as(Hash)["next"].should_not be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should support cursor-based pagination" do
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
5.times do |i|
|
||||||
|
create_test_link(test_user, "https://example.com/#{i}")
|
||||||
|
end
|
||||||
|
|
||||||
|
# Get first page
|
||||||
|
get("/api/links?limit=2", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
first_page = Hash(String, Array(Hash(String, String | Int64)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
cursor = first_page["pagination"].as(Hash)["next"]
|
||||||
|
|
||||||
|
# Get second page using cursor
|
||||||
|
get("/api/links?limit=2&cursor=#{cursor}", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
second_page = Hash(String, Array(Hash(String, String | Int64)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
|
||||||
|
# Ensure different links are returned
|
||||||
|
first_page_ids = first_page["data"].as(Array).map { |link| link["id"] }
|
||||||
|
second_page_ids = second_page["data"].as(Array).map { |link| link["id"] }
|
||||||
|
|
||||||
|
# Check that no IDs from first page appear in second page
|
||||||
|
(first_page_ids & second_page_ids).empty?.should be_true
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should return owned links only" do
|
it "should return owned links only" do
|
||||||
links = ["https://google.com", "google.com", "google.com.co", "kagi.com"]
|
links = ["https://donado.co", "donado.co", "uninorte.edu.co", "kagi.com"]
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
|
|
||||||
links[0..2].each do |link|
|
links[0..2].each do |link|
|
||||||
@@ -133,17 +234,135 @@ describe "App::Controllers::Link" do
|
|||||||
|
|
||||||
get("/api/links", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
get("/api/links", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
parsed_response = Hash(String, Array(Hash(String, String | Int64))).from_json(response.body)
|
parsed_response = Hash(String, Array(Hash(String, String | Int64)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
parsed_response["data"].size.should eq(3)
|
parsed_response["data"].as(Array).size.should eq(3)
|
||||||
parsed_response["data"][0]["origin"].should eq(links[0])
|
|
||||||
parsed_response["data"][1]["origin"].should eq(links[1])
|
origins = parsed_response["data"].as(Array).map { |link| link["origin"] }
|
||||||
parsed_response["data"][2]["origin"].should eq(links[2])
|
links[0..2].each do |link|
|
||||||
|
origins.should contain(link)
|
||||||
|
end
|
||||||
|
origins.should_not contain(links[3])
|
||||||
end
|
end
|
||||||
|
|
||||||
it "should return 401 - missing api key" do
|
it "should return 401 - missing api key" do
|
||||||
get "/api/links"
|
get "/api/links"
|
||||||
|
|
||||||
expected = {"error" => "Unauthorized"}.to_json
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
|
response.status_code.should eq(401)
|
||||||
|
response.body.should eq(expected)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "Get" do
|
||||||
|
it "should return the specified link with limited click details" do
|
||||||
|
link = "https://bing.com"
|
||||||
|
test_user = create_test_user()
|
||||||
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
|
110.times do
|
||||||
|
create_test_click(test_link)
|
||||||
|
end
|
||||||
|
|
||||||
|
get("/api/links/#{test_link.id}", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
parsed_response = Hash(String, Hash(String, String | Int64 | Array(Hash(String, String)))).from_json(response.body)
|
||||||
|
parsed_response["data"]["origin"].should eq(link)
|
||||||
|
parsed_response["data"]["clicks"].as(Array).size.should eq(100)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should return 404 - link does not exist" do
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
get("/api/links/1", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
expected = {"error" => "Resource not found"}.to_json
|
||||||
|
response.status_code.should eq(404)
|
||||||
|
response.body.should eq(expected)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should return 401 - missing api key" do
|
||||||
|
get "/api/links/1"
|
||||||
|
|
||||||
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
|
response.status_code.should eq(401)
|
||||||
|
response.body.should eq(expected)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe "Clicks" do
|
||||||
|
it "should return paginated clicks for a link" do
|
||||||
|
link = "https://example.com"
|
||||||
|
test_user = create_test_user()
|
||||||
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
|
5.times do
|
||||||
|
create_test_click(test_link)
|
||||||
|
end
|
||||||
|
|
||||||
|
get("/api/links/#{test_link.id}/clicks", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
parsed_response = Hash(String, Array(Hash(String, String)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
parsed_response["data"].as(Array).size.should eq(5)
|
||||||
|
parsed_response["pagination"].as(Hash)["has_more"].should be_false
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should respect limit parameter" do
|
||||||
|
link = "https://example.com"
|
||||||
|
test_user = create_test_user()
|
||||||
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
|
10.times do
|
||||||
|
create_test_click(test_link)
|
||||||
|
end
|
||||||
|
|
||||||
|
get("/api/links/#{test_link.id}/clicks?limit=3", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
parsed_response = Hash(String, Array(Hash(String, String)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
parsed_response["data"].as(Array).size.should eq(3)
|
||||||
|
parsed_response["pagination"].as(Hash)["has_more"].should be_true
|
||||||
|
parsed_response["pagination"].as(Hash)["next"].should_not be_nil
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should support cursor-based pagination" do
|
||||||
|
link = "https://example.com"
|
||||||
|
test_user = create_test_user()
|
||||||
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
|
10.times do
|
||||||
|
create_test_click(test_link)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Get first page
|
||||||
|
get("/api/links/#{test_link.id}/clicks?limit=3", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
first_page = Hash(String, Array(Hash(String, String)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
cursor = first_page["pagination"].as(Hash)["next"]
|
||||||
|
|
||||||
|
# Get second page using cursor
|
||||||
|
get("/api/links/#{test_link.id}/clicks?limit=3&cursor=#{cursor}", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
second_page = Hash(String, Array(Hash(String, String)) | Hash(String, Bool | String?)).from_json(response.body)
|
||||||
|
|
||||||
|
# Ensure different clicks are returned
|
||||||
|
first_page_ids = first_page["data"].as(Array).map { |click| click["id"] }
|
||||||
|
second_page_ids = second_page["data"].as(Array).map { |click| click["id"] }
|
||||||
|
|
||||||
|
# Check that no IDs from first page appear in second page
|
||||||
|
(first_page_ids & second_page_ids).empty?.should be_true
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should return 404 - link does not exist" do
|
||||||
|
test_user = create_test_user()
|
||||||
|
|
||||||
|
get("/api/links/nonexistent_id/clicks", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
|
expected = {"error" => "Resource not found"}.to_json
|
||||||
|
response.status_code.should eq(404)
|
||||||
|
response.body.should eq(expected)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "should return 401 - missing api key" do
|
||||||
|
get("/api/links/1/clicks")
|
||||||
|
|
||||||
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
response.status_code.should eq(401)
|
response.status_code.should eq(401)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
@@ -151,18 +370,18 @@ describe "App::Controllers::Link" do
|
|||||||
|
|
||||||
describe "Update" do
|
describe "Update" do
|
||||||
it "should update link url" do
|
it "should update link url" do
|
||||||
link = "https://kagi.com"
|
link = "https://github.com"
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
test_link = create_test_link(test_user, link)
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
payload = {"url" => "https://kagi.com.co"}
|
payload = {"url" => "https://github.com.co"}
|
||||||
put(
|
put(
|
||||||
"/api/links/#{test_link.id}",
|
"/api/links/#{test_link.id}",
|
||||||
headers: HTTP::Headers{"Content-Type" => "application/json", "X-Api-Key" => test_user.api_key.to_s},
|
headers: HTTP::Headers{"Content-Type" => "application/json", "X-Api-Key" => test_user.api_key.to_s},
|
||||||
body: payload.to_json
|
body: payload.to_json
|
||||||
)
|
)
|
||||||
|
|
||||||
parsed_response = Hash(String, Hash(String, String | Int64)).from_json(response.body)
|
parsed_response = Hash(String, Hash(String, String | Int64 | Array(Hash(String, String)))).from_json(response.body)
|
||||||
parsed_response["data"]["origin"].should eq(payload["url"])
|
parsed_response["data"]["origin"].should eq(payload["url"])
|
||||||
end
|
end
|
||||||
|
|
||||||
@@ -176,7 +395,7 @@ describe "App::Controllers::Link" do
|
|||||||
body: payload.to_json
|
body: payload.to_json
|
||||||
)
|
)
|
||||||
|
|
||||||
expected = {"error" => "Not Found"}.to_json
|
expected = {"error" => "Resource not found"}.to_json
|
||||||
response.status_code.should eq(404)
|
response.status_code.should eq(404)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
@@ -189,7 +408,7 @@ describe "App::Controllers::Link" do
|
|||||||
body: payload.to_json
|
body: payload.to_json
|
||||||
)
|
)
|
||||||
|
|
||||||
expected = {"error" => "Unauthorized"}.to_json
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
response.status_code.should eq(401)
|
response.status_code.should eq(401)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
@@ -197,7 +416,7 @@ describe "App::Controllers::Link" do
|
|||||||
|
|
||||||
describe "Delete" do
|
describe "Delete" do
|
||||||
it "should delete link url" do
|
it "should delete link url" do
|
||||||
link = "https://kagi.com"
|
link = "https://news.ycombinator.com"
|
||||||
test_user = create_test_user()
|
test_user = create_test_user()
|
||||||
test_link = create_test_link(test_user, link)
|
test_link = create_test_link(test_user, link)
|
||||||
|
|
||||||
@@ -211,7 +430,7 @@ describe "App::Controllers::Link" do
|
|||||||
|
|
||||||
delete("/api/links/1", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
delete("/api/links/1", headers: HTTP::Headers{"X-Api-Key" => test_user.api_key.to_s})
|
||||||
|
|
||||||
expected = {"error" => "Not Found"}.to_json
|
expected = {"error" => "Resource not found"}.to_json
|
||||||
response.status_code.should eq(404)
|
response.status_code.should eq(404)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
@@ -219,7 +438,7 @@ describe "App::Controllers::Link" do
|
|||||||
it "should return 401 - missing api key" do
|
it "should return 401 - missing api key" do
|
||||||
delete "/api/links/1"
|
delete "/api/links/1"
|
||||||
|
|
||||||
expected = {"error" => "Unauthorized"}.to_json
|
expected = {"error" => "Unauthorized access"}.to_json
|
||||||
response.status_code.should eq(401)
|
response.status_code.should eq(401)
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ describe "App::Controllers::Ping" do
|
|||||||
it "should return pong" do
|
it "should return pong" do
|
||||||
get "/api/ping"
|
get "/api/ping"
|
||||||
|
|
||||||
expected = {"pong" => "ok"}.to_json
|
expected = {"data" => "pong"}.to_json
|
||||||
response.body.should eq(expected)
|
response.body.should eq(expected)
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -34,4 +34,29 @@ describe "App::Services::Cli" do
|
|||||||
|
|
||||||
output.should contain "Failed to delete user"
|
output.should contain "Failed to delete user"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
it "sets up an admin user if environment variables are present" do
|
||||||
|
ENV["ADMIN_NAME"] = "adminuser"
|
||||||
|
ENV["ADMIN_API_KEY"] = "secure_admin_key"
|
||||||
|
|
||||||
|
App::Services::Cli.setup_admin_user
|
||||||
|
|
||||||
|
admin_user = App::Lib::Database.all(App::Models::User).find { |u| u.name == "adminuser" }
|
||||||
|
admin_user.should_not be_nil
|
||||||
|
admin_user = admin_user.not_nil!
|
||||||
|
|
||||||
|
admin_user.api_key.should eq "secure_admin_key"
|
||||||
|
|
||||||
|
App::Services::Cli.delete_user(admin_user.id)
|
||||||
|
end
|
||||||
|
|
||||||
|
it "skips admin setup if environment variables are missing" do
|
||||||
|
ENV.delete("ADMIN_NAME")
|
||||||
|
ENV.delete("ADMIN_API_KEY")
|
||||||
|
|
||||||
|
App::Services::Cli.setup_admin_user
|
||||||
|
|
||||||
|
users = App::Lib::Database.all(App::Models::User)
|
||||||
|
users.none? { |u| u.name == "adminuser" }.should be_true
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
+46
-11
@@ -1,11 +1,20 @@
|
|||||||
require "uuid"
|
require "file_utils"
|
||||||
|
|
||||||
require "spec-kemal"
|
require "spec-kemal"
|
||||||
require "micrate"
|
require "micrate"
|
||||||
|
|
||||||
require "../url-shortener"
|
require "dotenv"
|
||||||
|
Dotenv.load ".env.#{ENV["ENV"]}"
|
||||||
|
|
||||||
|
require "../bit"
|
||||||
|
|
||||||
Spec.before_suite do
|
Spec.before_suite do
|
||||||
|
# Delete the SQLite database file if it exists
|
||||||
|
db_file_path = ENV["DATABASE_URL"].split("sqlite3://").last.split("?").first
|
||||||
|
if File.exists?(db_file_path)
|
||||||
|
File.delete(db_file_path)
|
||||||
|
end
|
||||||
|
|
||||||
Micrate::DB.connection_url = ENV["DATABASE_URL"]
|
Micrate::DB.connection_url = ENV["DATABASE_URL"]
|
||||||
Micrate::Cli.run_up
|
Micrate::Cli.run_up
|
||||||
|
|
||||||
@@ -14,13 +23,13 @@ end
|
|||||||
|
|
||||||
def create_test_user
|
def create_test_user
|
||||||
user = App::Models::User.new
|
user = App::Models::User.new
|
||||||
user.id = UUID.v4.to_s
|
|
||||||
user.name = "Tester"
|
user.name = "Tester"
|
||||||
user.api_key = Random::Secure.urlsafe_base64()
|
user.api_key = Random::Secure.urlsafe_base64()
|
||||||
|
|
||||||
changeset = App::Lib::Database.insert(user)
|
changeset = App::Lib::Database.insert(user)
|
||||||
if !changeset.valid?
|
if !changeset.valid?
|
||||||
raise "Test user creation failed"
|
error_messages = changeset.errors.map { |error| "#{error}" }.join(", ")
|
||||||
|
raise "Test user creation failed #{error_messages}"
|
||||||
end
|
end
|
||||||
|
|
||||||
user
|
user
|
||||||
@@ -28,23 +37,49 @@ end
|
|||||||
|
|
||||||
def create_test_link(user, url)
|
def create_test_link(user, url)
|
||||||
link = App::Models::Link.new
|
link = App::Models::Link.new
|
||||||
link.id = UUID.v4.to_s
|
link.slug = App::Services::SlugService.shorten_url(url, user.id)
|
||||||
link.url = url
|
link.url = url
|
||||||
link.slug = Random::Secure.urlsafe_base64(4)
|
|
||||||
link.user = user
|
link.user = user
|
||||||
|
|
||||||
changeset = App::Lib::Database.insert(link)
|
changeset = App::Lib::Database.insert(link)
|
||||||
if !changeset.valid?
|
unless changeset.valid?
|
||||||
raise "Test link creation failed"
|
error_messages = changeset.errors.map { |error| "#{error}" }.join(", ")
|
||||||
|
raise "Test link creation failed: #{error_messages}"
|
||||||
end
|
end
|
||||||
|
|
||||||
|
link.clicks = [] of App::Models::Click
|
||||||
|
|
||||||
link
|
link
|
||||||
end
|
end
|
||||||
|
|
||||||
def get_test_link(link_id)
|
def create_test_click(link)
|
||||||
App::Lib::Database.get!(App::Models::Link, link_id)
|
click = App::Models::Click.new
|
||||||
|
click.user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:127.0) Gecko/20100101 Firefox/127.0"
|
||||||
|
click.browser = "Firefox"
|
||||||
|
click.os = "Mac OS X"
|
||||||
|
click.referer = "example.com"
|
||||||
|
click.country = "US"
|
||||||
|
click.created_at = Time.utc
|
||||||
|
click.link = link
|
||||||
|
click.link_id = link.id
|
||||||
|
|
||||||
|
changeset = App::Lib::Database.insert(click)
|
||||||
|
unless changeset.valid?
|
||||||
|
error_messages = changeset.errors.map { |error| "#{error}" }.join(", ")
|
||||||
|
raise "Test click creation failed: #{error_messages}"
|
||||||
|
end
|
||||||
|
click
|
||||||
end
|
end
|
||||||
|
|
||||||
def delete_test_link(link_id)
|
def get_test_link(link_id: Int64)
|
||||||
|
query = App::Lib::Database::Query.where(id: link_id).limit(1)
|
||||||
|
link = App::Lib::Database.all(App::Models::Link, query, preload: [:clicks]).first?
|
||||||
|
|
||||||
|
raise "Link not found" if link.nil?
|
||||||
|
|
||||||
|
link
|
||||||
|
end
|
||||||
|
|
||||||
|
def delete_test_link(link_id: Int64)
|
||||||
App::Lib::Database.raw_exec("DELETE FROM links WHERE id = (?)", link_id) # tempfix: Database.delete does not work
|
App::Lib::Database.raw_exec("DELETE FROM links WHERE id = (?)", link_id) # tempfix: Database.delete does not work
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user