Compare commits

...

3 Commits

Author SHA1 Message Date
Constantin Graf
046b28b3de Replace MinIO with RustFS for local S3 storage 2026-12-05 12:43:13 +01:00
Constantin Graf
560f12242f Test deduplication of members created during an import 2026-12-05 12:42:43 +01:00
Constantin Graf
411377390d Match existing time entries of members with the same email when deduplicating imports 2026-12-05 12:42:43 +01:00
7 changed files with 167 additions and 46 deletions

View File

@@ -28,6 +28,20 @@ We also have an examples repository [here](https://github.com/solidtime-io/self-
If you do not want to self-host solidtime or try it out you can sign up for [solidtime cloud](https://www.solidtime.io/)
## Local Development
The local development environment runs on [Laravel Sail](https://laravel.com/docs/sail) behind a Traefik reverse proxy (see `docker-compose.yml`). Copy `.env.example` to `.env` and start it with `./vendor/bin/sail up -d`. With the default `NGINX_HOST_NAME=solidtime.test` these services are available:
| Service | URL |
| --- | --- |
| solidtime | https://solidtime.test |
| Mailpit (emails) | https://mail.solidtime.test |
| RustFS S3 API (file storage) | https://storage.solidtime.test |
| RustFS admin console | https://storage-management.solidtime.test (login: `sail` / `password`) |
| Playwright UI | https://playwright.solidtime.test |
File storage uses [RustFS](https://rustfs.com), an S3-compatible object storage. The `rustfs-create-bucket` service creates the public `local` bucket on startup.
## Issues & Feature Requests
If you

View File

@@ -4,8 +4,10 @@ declare(strict_types=1);
namespace App\Service\Import;
use App\Models\Member;
use App\Models\TimeEntry;
use Illuminate\Support\Carbon;
use Illuminate\Support\Str;
use RuntimeException;
/**
@@ -16,22 +18,41 @@ use RuntimeException;
* an import are skipped and every further one is created. Re-importing the same data therefore creates nothing,
* while identical time entries within one import are still kept.
*
* Existing time entries are loaded lazily per member and UTC month of their start, so only the members and months an
* import touches are queried (backed by the (member_id, start) index). A member month is always loaded before the
* first time entry of that member month is created by the import, so time entries created by the import itself are
* never counted as existing.
* Members are compared by the email of their user, since the importers map users by email: members of the source
* that share an email (for example a placeholder and the real user it was created for) are merged into one member
* on import. Their existing time entries therefore have to be matched together, otherwise re-importing the data
* would create the time entries of all but one of these members again.
*
* Existing time entries are loaded lazily per member group (members with the same email) and UTC month of their
* start, so only the members and months an import touches are queried (backed by the (member_id, start) index). A
* group month is always loaded before the first time entry of that group month is created by the import, so time
* entries created by the import itself are never counted as existing.
*/
class TimeEntryDeduplicator
{
private const string DATE_FORMAT = 'Y-m-d H:i:s';
/**
* Remaining number of existing time entries per fingerprint, grouped by member and month ("<member_id>|Y-m")
* Remaining number of existing time entries per fingerprint, grouped by member group and month ("<group>|Y-m")
*
* @var array<string, array<string, int>>
*/
private array $existingCounts = [];
/**
* Group key (lower case email of the user) per member ID of the organization, loaded on first use
*
* @var array<string, string>|null
*/
private ?array $groupByMember = null;
/**
* Member IDs per group key
*
* @var array<string, list<string>>
*/
private array $membersByGroup = [];
public function __construct(private readonly string $organizationId) {}
/**
@@ -50,11 +71,11 @@ class TimeEntryDeduplicator
return false;
}
$memberId = $timeEntry->member_id;
$group = $this->getGroup($timeEntry->member_id);
$month = substr($start, 0, 7);
$bucket = $memberId.'|'.$month;
$bucket = $group.'|'.$month;
if (! isset($this->existingCounts[$bucket])) {
$this->existingCounts[$bucket] = $this->loadMemberMonth($memberId, $month);
$this->existingCounts[$bucket] = $this->loadGroupMonth($this->membersByGroup[$group], $month);
}
$fingerprint = $this->getFingerprint(
@@ -76,10 +97,44 @@ class TimeEntryDeduplicator
}
/**
* Returns the group key of the member, members of the organization with the same email share a group
*/
private function getGroup(string $memberId): string
{
if ($this->groupByMember === null) {
$this->groupByMember = [];
$members = Member::query()
->where('members.organization_id', '=', $this->organizationId)
->join('users', 'users.id', '=', 'members.user_id')
->toBase()
->select(['members.id', 'users.email'])
->get();
foreach ($members as $member) {
/** @var object{id: string, email: string} $member */
$group = 'email:'.Str::lower($member->email);
$this->groupByMember[$member->id] = $group;
$this->membersByGroup[$group][] = $member->id;
}
}
if (! isset($this->groupByMember[$memberId])) {
// Note: This is a member the import created after the groups were loaded. The importers only create a
// member if no user with its email is in the organization yet, so it can not share a group with an
// existing member and has no existing time entries.
$group = 'member:'.$memberId;
$this->groupByMember[$memberId] = $group;
$this->membersByGroup[$group] = [$memberId];
}
return $this->groupByMember[$memberId];
}
/**
* @param list<string> $memberIds
* @param string $month Month in the format "Y-m"
* @return array<string, int>
*/
private function loadMemberMonth(string $memberId, string $month): array
private function loadGroupMonth(array $memberIds, string $month): array
{
$monthStart = Carbon::createFromFormat('Y-m-d H:i:s', $month.'-01 00:00:00', 'UTC');
if ($monthStart === null) {
@@ -92,7 +147,7 @@ class TimeEntryDeduplicator
// raw attributes of the imported time entries. The cursor avoids holding all rows in memory at once.
$rows = TimeEntry::query()
->where('organization_id', '=', $this->organizationId)
->where('member_id', '=', $memberId)
->whereIn('member_id', $memberIds)
->where('start', '>=', $monthStart->format(self::DATE_FORMAT))
->where('start', '<', $monthEnd->format(self::DATE_FORMAT))
->whereNotNull('end')

View File

@@ -127,20 +127,24 @@ services:
- reverse-proxy
volumes:
- '.:/src'
minio:
image: 'minio/minio:latest'
rustfs:
image: 'rustfs/rustfs:1.0.7'
environment:
MINIO_BROWSER_REDIRECT_URL: 'https://storage-management.${NGINX_HOST_NAME}'
MINIO_ROOT_USER: 'sail'
MINIO_ROOT_PASSWORD: 'password'
RUSTFS_ACCESS_KEY: 'sail'
RUSTFS_SECRET_KEY: 'password'
RUSTFS_ADDRESS: ':9000'
RUSTFS_CONSOLE_ENABLE: 'true'
RUSTFS_CONSOLE_ADDRESS: ':9001'
RUSTFS_VOLUMES: '/data'
# Logs go to stdout (`docker compose logs rustfs`) instead of /logs inside the container
RUSTFS_OBS_LOG_DIRECTORY: ''
volumes:
- 'sail-minio:/data/minio'
- 'sail-rustfs:/data'
networks:
- reverse-proxy
- sail
command: minio server /data/minio --console-address ":8900"
healthcheck:
test: [ "CMD", "mc", "ready", "local" ]
test: [ "CMD", "curl", "-fsS", "http://localhost:9000/health/ready" ]
interval: 5s
timeout: 5s
retries: 5
@@ -158,36 +162,51 @@ services:
- "traefik.http.routers.solidtime-dev-storage-frontend-https.service=solidtime-dev-storage-frontend"
- "traefik.http.routers.solidtime-dev-storage-frontend-https.entrypoints=websecure"
- "traefik.http.routers.solidtime-dev-storage-frontend-https.tls=true"
# Storage Management
- "traefik.http.services.solidtime-dev-storage-management.loadbalancer.server.port=8900"
# Storage Management (RustFS console)
# The console is served under /rustfs/console/ and `/` returns 403, so GET / is redirected there.
# Only GET / is redirected: the console logs in with a signed STS `POST /`, and redirecting that
# makes the browser replay the signature against /rustfs/console/ (SignatureDoesNotMatch).
- "traefik.http.services.solidtime-dev-storage-management.loadbalancer.server.port=9001"
- "traefik.http.middlewares.solidtime-dev-storage-management-root.redirectregex.regex=^(https?://[^/]+)/?$$"
- "traefik.http.middlewares.solidtime-dev-storage-management-root.redirectregex.replacement=$${1}/rustfs/console/"
# http
- "traefik.http.routers.solidtime-dev-storage-management.rule=Host(`storage-management.${NGINX_HOST_NAME}`)"
- "traefik.http.routers.solidtime-dev-storage-management.service=solidtime-dev-storage-management"
- "traefik.http.routers.solidtime-dev-storage-management.entrypoints=web"
- "traefik.http.routers.solidtime-dev-storage-management-root.rule=Host(`storage-management.${NGINX_HOST_NAME}`) && Method(`GET`) && Path(`/`)"
- "traefik.http.routers.solidtime-dev-storage-management-root.service=solidtime-dev-storage-management"
- "traefik.http.routers.solidtime-dev-storage-management-root.entrypoints=web"
- "traefik.http.routers.solidtime-dev-storage-management-root.middlewares=solidtime-dev-storage-management-root"
# https
- "traefik.http.routers.solidtime-dev-storage-management-https.rule=Host(`storage-management.${NGINX_HOST_NAME}`)"
- "traefik.http.routers.solidtime-dev-storage-management-https.service=solidtime-dev-storage-management"
- "traefik.http.routers.solidtime-dev-storage-management-https.entrypoints=websecure"
- "traefik.http.routers.solidtime-dev-storage-management-https.tls=true"
- "traefik.http.routers.solidtime-dev-storage-management-root-https.rule=Host(`storage-management.${NGINX_HOST_NAME}`) && Method(`GET`) && Path(`/`)"
- "traefik.http.routers.solidtime-dev-storage-management-root-https.service=solidtime-dev-storage-management"
- "traefik.http.routers.solidtime-dev-storage-management-root-https.entrypoints=websecure"
- "traefik.http.routers.solidtime-dev-storage-management-root-https.tls=true"
- "traefik.http.routers.solidtime-dev-storage-management-root-https.middlewares=solidtime-dev-storage-management-root"
minio-create-bucket:
image: minio/mc:latest
rustfs-create-bucket:
image: 'rustfs/rustfs:1.0.7'
depends_on:
minio:
rustfs:
condition: service_healthy
environment:
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID}
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY}
S3_BUCKET: ${S3_BUCKET}
S3_ENDPOINT: ${S3_ENDPOINT}
volumes:
- './docker/local/minio:/etc/minio'
networks:
- sail
- reverse-proxy
entrypoint: /etc/minio/create_bucket.sh
extra_hosts:
- "storage.${NGINX_HOST_NAME}:${REVERSE_PROXY_IP:-10.100.100.10}"
entrypoint: [ '/bin/sh', '-c' ]
command:
- |
set -e
export RC_HOST_local="http://$${S3_ACCESS_KEY_ID}:$${S3_SECRET_ACCESS_KEY}@rustfs:9000"
rc bucket create "local/$${S3_BUCKET}" --ignore-existing
rc bucket anonymous set public "local/$${S3_BUCKET}"
restart: 'no'
gotenberg:
image: gotenberg/gotenberg:8
@@ -206,5 +225,5 @@ volumes:
driver: local
sail-pgsql-test:
driver: local
sail-minio:
sail-rustfs:
driver: local

View File

@@ -1,10 +0,0 @@
#!/bin/sh
# Source: https://helgesver.re/articles/laravel-sail-create-minio-bucket-automatically
/usr/bin/mc alias set local ${S3_ENDPOINT} ${S3_ACCESS_KEY_ID} ${S3_SECRET_ACCESS_KEY};
/usr/bin/mc rm -r --force local/${S3_BUCKET};
/usr/bin/mc mb --ignore-existing local/${S3_BUCKET};
/usr/bin/mc anonymous set public local/${S3_BUCKET};
exit 0;

View File

@@ -95,7 +95,7 @@ class SolidtimeImporterTest extends ImporterTestAbstract
$queryLog = DB::getQueryLog();
// Assert
$this->assertCount(26, $queryLog);
$this->assertCount(27, $queryLog);
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true);
$this->checkTimeEntries($testScenario);
$this->assertSame(2, $report->timeEntriesCreated);
@@ -279,7 +279,7 @@ class SolidtimeImporterTest extends ImporterTestAbstract
$queryLog = DB::getQueryLog();
// Assert
$this->assertCount(12, $queryLog);
$this->assertCount(13, $queryLog);
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries(true);
$this->checkTimeEntries($testScenario);
$this->assertSame(0, $report->timeEntriesCreated);

View File

@@ -42,7 +42,7 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$queryLog = DB::getQueryLog();
// Assert
$this->assertCount(23, $queryLog);
$this->assertCount(24, $queryLog);
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();
$this->checkTimeEntries($testScenario);
$this->assertSame(2, $report->timeEntriesCreated);
@@ -108,7 +108,7 @@ class TogglTimeEntriesImporterTest extends ImporterTestAbstract
$queryLog = DB::getQueryLog();
// Assert
$this->assertCount(13, $queryLog);
$this->assertCount(14, $queryLog);
$testScenario = $this->checkTestScenarioAfterImportExcludingTimeEntries();
$this->checkTimeEntries($testScenario);
$this->assertSame(0, $report->timeEntriesCreated);

View File

@@ -9,6 +9,7 @@ use App\Models\Member;
use App\Models\Organization;
use App\Models\Project;
use App\Models\TimeEntry;
use App\Models\User;
use App\Service\Import\TimeEntryDeduplicator;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
@@ -197,7 +198,8 @@ class TimeEntryDeduplicatorTest extends TestCase
$queryLog = DB::getQueryLog();
// Assert
$this->assertCount(3, $queryLog);
// One query for the member groups and one per member month
$this->assertCount(4, $queryLog);
}
public function test_only_loads_time_entries_of_the_member(): void
@@ -216,4 +218,45 @@ class TimeEntryDeduplicatorTest extends TestCase
// Assert
$this->assertSame([false, true], $results);
}
public function test_does_not_claim_time_entry_of_member_created_after_the_members_were_loaded(): void
{
// Arrange
$deduplicator = new TimeEntryDeduplicator($this->organization->getKey());
$deduplicator->claimExisting($this->makeTimeEntry());
$newMember = Member::factory()->forOrganization($this->organization)->create();
// Act
$first = $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $newMember->getKey()]));
$this->makeTimeEntry(attributes: ['member_id' => $newMember->getKey()])->save();
$second = $deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $newMember->getKey()]));
// Assert
$this->assertFalse($first);
$this->assertFalse($second);
}
public function test_matches_time_entries_of_members_with_the_same_email(): void
{
// Arrange
// The importers map users by email, so both members are merged into one member when the data is imported
$placeholder = User::factory()->placeholder()->create(['email' => 'peter@example.com']);
$placeholderMember = Member::factory()->forUser($placeholder)->forOrganization($this->organization)->create();
$user = User::factory()->create(['email' => 'Peter@example.com']);
$userMember = Member::factory()->forUser($user)->forOrganization($this->organization)->create();
$this->makeTimeEntry(attributes: ['member_id' => $placeholderMember->getKey(), 'user_id' => $placeholder->getKey()])->save();
$this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey(), 'user_id' => $user->getKey()])->save();
$deduplicator = new TimeEntryDeduplicator($this->organization->getKey());
// Act
$results = [
$deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])),
$deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])),
$deduplicator->claimExisting($this->makeTimeEntry(attributes: ['member_id' => $userMember->getKey()])),
$deduplicator->claimExisting($this->makeTimeEntry()),
];
// Assert
$this->assertSame([true, true, false, false], $results);
}
}