Compare commits

...

2 commits

Author SHA1 Message Date
af8647f3aa Updated configurations for deployment
All checks were successful
Publish FaceAI Container / publish (push) Successful in 2m56s
2026-04-12 15:21:33 +02:00
bbb9c193ce feat: add processor service with Redis-backed job queue
- Introduced a new `processor` service in the Docker Compose setup to handle face matching jobs.
- Configured Redis as a job queue and state management system for processing searches.
- Updated the backend to enqueue jobs and manage user locks using Redis.
- Added environment variables for Redis configuration and runtime paths.
- Created technical design documentation for the processor service outlining architecture, queue model, and search lifecycle.
- Updated package.json and package-lock.json to include dependencies for BullMQ and ioredis in the processor workspace.
- Added sample PKL files for local testing in the `test_pkl` directory.
2026-04-11 17:53:22 +02:00
28 changed files with 1638 additions and 251 deletions

View file

@ -5,7 +5,8 @@ This folder scaffolds the new FaceAI app described in the integration plan.
It includes: It includes:
- a Vue frontend for the FaceAI upload and polling flow - a Vue frontend for the FaceAI upload and polling flow
- a Node/Express backend for session exchange, mocked searches, and return handoff - a Node/Express backend for session exchange, queueing, and return handoff
- a dedicated processor runner that consumes matcher jobs from Redis and executes `face_matcher`
- a local legacy simulator so the launch and return flow can be tested without the old Java site - a local legacy simulator so the launch and return flow can be tested without the old Java site
- a Dockerized PHP Apache stack for exercising the real `www/faceai_handoff.php` and `www/faceai_return.php` bridge files - a Dockerized PHP Apache stack for exercising the real `www/faceai_handoff.php` and `www/faceai_return.php` bridge files
@ -16,64 +17,91 @@ faceai/
apps/ apps/
backend/ backend/
frontend/ frontend/
processor/
docker/ docker/
Dockerfile Dockerfile
``` ```
## What The Local Test Covers ## Runtime Topology
The scaffold currently expects four runtime roles:
- `faceai`: public HTTP service on port `3001`, serving the built Vue app and the authenticated API
- `processor`: background matcher runner consuming BullMQ jobs from Redis and executing the Linux `face_matcher` binary
- `redis`: short-lived queue and search-state store
- `legacy-php`: local-only PHP Apache simulator for exercising the real bridge files under `www/`
For hosted deployment, the long-lived application topology is `faceai` + `processor` + `redis`. The PHP simulator stays local-only and the real legacy site remains on its existing stack.
## What The End-To-End Local Test Covers
The local simulator exercises the exact flow the plan is aiming for: The local simulator exercises the exact flow the plan is aiming for:
1. a legacy-like race page shows a `Face ID` button instead of `tipoPuntoFoto` 1. a legacy-like race page loads the original `www/_js/rus-ecom-240621.js` script and shows a `Face ID` button instead of `tipoPuntoFoto`
2. clicking it hits a mock legacy handoff endpoint 2. clicking it hits the real PHP handoff bridge at `www/faceai_handoff.php`
3. the backend signs a short-lived handoff token and redirects to the Vue app 3. the backend signs a short-lived handoff token and redirects to the Vue app
4. the Vue app exchanges the token for its own FaceAI session cookie 4. the Vue app exchanges the token for its own FaceAI session cookie
5. the user uploads a selfie and starts a mocked race-scoped search 5. the user uploads a selfie and starts a Redis-backed race-scoped search
6. the frontend polls until the job completes 6. the frontend polls until the job completes
7. FaceAI requests a signed return URL 7. FaceAI requests a signed return URL
8. the browser is redirected back to a legacy-like filtered race page showing only the matched photos 8. the browser is redirected back to the real PHP return bridge at `www/faceai_return.php`
9. the PHP bridge fetches the signed result from FaceAI and renders a filtered legacy-like race page
## Local Run ## Local Testing With The Legacy PHP Simulator
This is the recommended local test path because it exercises the public site, the processor, Redis, and the real PHP bridge files together.
### Prerequisites
- Docker Desktop or another Docker Engine with Compose support
- local npm dependencies installed in this `faceai/` workspace
### Start The Stack
From this folder: From this folder:
```bash
npm install
npm run dev
```
Then open:
```text
http://localhost:3001/dev/legacy/race?raceId=101&lang=it
```
That page simulates the old site and launches the FaceAI app at `http://localhost:5173`.
## Docker Run With PHP Simulator
If you do not have PHP locally, use Docker instead:
```bash ```bash
npm install npm install
npm run build npm run build
docker compose up --build docker compose up --build
``` ```
The Docker stack reuses the local FaceAI workspace and only containerizes the runtime services. That means PHP is fully containerized, while the Node service runs inside Docker against the already-installed local workspace dependencies and the already-built frontend assets. The checked-in `docker-compose.yml` starts:
This starts: - FaceAI public site on `http://localhost:3001`
- processor runner on the internal Compose network
- Redis on the internal Compose network
- PHP Apache serving `../www` on `http://localhost:8080`
- FaceAI app on `http://localhost:3001` The local stack also mounts:
- PHP Apache serving `www` on `http://localhost:8080`
For the end-to-end test through the PHP bridge, open: - `../bin/Face_Recognition_Unix` into the processor container as the matcher binary source
- `../test_pkl` into the processor container as fallback PKL test data
- `../www` into the PHP container so the real bridge files are used
### Run The Browser Test
Open:
```text ```text
http://localhost:8080/faceai_simulator.php?raceId=101&lang=it http://localhost:8080/faceai_simulator.php?raceId=101&lang=it
``` ```
That page loads the original race-page JavaScript from `www/_js/rus-ecom-240621.js`, lets the script replace the visible `tipoPuntoFoto` selector with the new `Face ID` button, and launches the real PHP handoff bridge at `www/faceai_handoff.php`. That page simulates the legacy race page, loads the original race-page JavaScript from `www/_js/rus-ecom-240621.js`, lets the script replace the visible `tipoPuntoFoto` selector with the new `Face ID` button, and launches the real PHP handoff bridge at `www/faceai_handoff.php`.
### Expected Local Flow
Use the page above and verify this sequence:
1. the simulator page renders on port `8080`
2. the visible checkpoint selector is replaced with the `Face ID` launch button
3. clicking `Face ID` redirects through `faceai_handoff.php` into `http://localhost:3001/auth/callback?token=...`
4. the FaceAI app establishes its session and loads the upload flow
5. uploading a selfie creates a queued search that the processor picks up
6. when polling completes, FaceAI redirects back to `http://localhost:8080/faceai_return.php?...`
7. the PHP return page renders the filtered photo list from the FaceAI result payload
### Rebuild Notes
If you change frontend code and want Docker to serve the updated UI, rebuild first with: If you change frontend code and want Docker to serve the updated UI, rebuild first with:
@ -81,6 +109,180 @@ If you change frontend code and want Docker to serve the updated UI, rebuild fir
npm run build npm run build
``` ```
If you want to stop and remove the local containers afterward, run:
```bash
docker compose down
```
## Optional Backend And Frontend Dev Loop
If you only want to iterate on the app without the PHP simulator, you can still run the public site and the processor separately. The queue-backed flow now requires Redis and the processor, so `npm run dev` alone is no longer the full stack.
One workable loop is:
```bash
npm install
docker compose up redis -d
npm run dev
```
Then start the processor in a second shell, either with its own local environment or by keeping the Compose-managed processor service running.
## Docker Compose Deployment For The Public Site And Matcher Runner
The checked-in `docker-compose.yml` is for local integration testing because it also includes the PHP simulator and local bind mounts. For hosted deployment, keep the same three-service application topology but remove `legacy-php` and replace the local mounts with your production matcher and PKL paths.
The public FaceAI site and the matcher runner can both use the same application image. The difference is only the process command:
- `npm run start` for the public site
- `npm run start:processor` for the matcher runner
### Production Compose Example
Replace the registry path, secrets, and host paths with the real deployment values.
```yaml
services:
faceai:
image: registry.example.com/my-namespace/faceai:latest
container_name: regalami-faceai
restart: unless-stopped
environment:
NODE_ENV: production
PORT: 3001
FACEAI_FRONTEND_URL: https://ai.regalamiunsorriso.it
FACEAI_PUBLIC_BASE_URL: https://ai.regalamiunsorriso.it
FACEAI_LEGACY_RETURN_URL: https://www.regalamiunsorriso.it/faceai_return.php
FACEAI_SHARED_SECRET: change-this-to-a-long-random-secret
FACEAI_SESSION_COOKIE: rus_faceai_session
FACEAI_REDIS_URL: redis://redis:6379
FACEAI_QUEUE_NAME: faceai-searches
FACEAI_RUNTIME_ROOT: /data/runtime
FACEAI_UPLOAD_ROOT: /data/runtime/uploads
FACEAI_ENABLE_LOCAL_LEGACY_STATIC: 0
volumes:
- faceai-runtime:/data/runtime
ports:
- "127.0.0.1:3001:3001"
depends_on:
- redis
processor:
image: registry.example.com/my-namespace/faceai:latest
container_name: regalami-faceai-processor
restart: unless-stopped
command: npm run start:processor
environment:
NODE_ENV: production
FACEAI_REDIS_URL: redis://redis:6379
FACEAI_QUEUE_NAME: faceai-searches
FACEAI_RUNTIME_ROOT: /data/runtime
FACEAI_PKL_ROOT: /data/pkl
FACEAI_MATCHER_BINARY: /opt/face-recognition/face_matcher
FACEAI_WORKER_CONCURRENCY: 2
FACEAI_WORKER_TIMEOUT_MS: 300000
volumes:
- faceai-runtime:/data/runtime
- /srv/faceai/pkl:/data/pkl:ro
- /srv/faceai/bin/Face_Recognition_Unix:/opt/face-recognition:ro
depends_on:
- redis
redis:
image: redis:7-alpine
container_name: regalami-faceai-redis
restart: unless-stopped
command: redis-server --appendonly no
volumes:
faceai-runtime:
```
This pattern assumes a reverse proxy on the host publishes `https://ai.regalamiunsorriso.it` and forwards to `127.0.0.1:3001`. The processor is internal-only and does not expose any public port.
### Required Runtime Configuration
Shared application settings:
| Variable | Required | Example | Purpose |
| --- | --- | --- | --- |
| `NODE_ENV` | yes | `production` | disables development defaults |
| `FACEAI_REDIS_URL` | yes | `redis://redis:6379` | queue and search-state backend |
| `FACEAI_QUEUE_NAME` | optional | `faceai-searches` | BullMQ queue name |
| `FACEAI_RUNTIME_ROOT` | yes | `/data/runtime` | shared writable runtime root between site and processor |
| `FACEAI_SHARED_SECRET` | yes | long random secret | trust boundary between FaceAI and the legacy bridge |
Public site settings:
| Variable | Required | Example | Purpose |
| --- | --- | --- | --- |
| `PORT` | optional | `3001` | internal listen port |
| `FACEAI_FRONTEND_URL` | yes | `https://ai.regalamiunsorriso.it` | URL used when the legacy bridge redirects into the app |
| `FACEAI_PUBLIC_BASE_URL` | yes | `https://ai.regalamiunsorriso.it` | public base URL used for local links and return flow generation |
| `FACEAI_LEGACY_RETURN_URL` | yes | `https://www.regalamiunsorriso.it/faceai_return.php` | legacy endpoint that receives the signed FaceAI result handoff |
| `FACEAI_SESSION_COOKIE` | optional | `rus_faceai_session` | cookie name for the FaceAI session |
| `FACEAI_UPLOAD_ROOT` | optional | `/data/runtime/uploads` | upload directory inside the shared runtime volume |
| `FACEAI_ENABLE_LOCAL_LEGACY_STATIC` | recommended | `0` | disables development-only static serving of local legacy assets |
Processor settings:
| Variable | Required | Example | Purpose |
| --- | --- | --- | --- |
| `FACEAI_PKL_ROOT` | yes | `/data/pkl` | mounted race-to-PKL dataset root |
| `FACEAI_TEST_PKL_ROOT` | optional | `/data/pkl/test` | local-only fallback PKL location |
| `FACEAI_MATCHER_BINARY` | yes | `/opt/face-recognition/face_matcher` | matcher executable inside the processor container |
| `FACEAI_WORKER_CONCURRENCY` | optional | `2` | BullMQ worker concurrency |
| `FACEAI_WORKER_TIMEOUT_MS` | optional | `300000` | matcher timeout in milliseconds |
Do not enable `FACEAI_ENABLE_LOCAL_LEGACY_STATIC` in production. That mode exists only for local simulator flows.
### Legacy-Side Configuration That Must Match
The deployment will not work correctly unless the legacy bridge is configured consistently.
The legacy site must:
- redirect users into `FACEAI_FRONTEND_URL` with a valid signed handoff token
- use the same `FACEAI_SHARED_SECRET` as the FaceAI deployment
- expose the configured `FACEAI_LEGACY_RETURN_URL`
- validate the signed return token and fetch the result payload from FaceAI
The shared secret is the trust boundary between the legacy site and FaceAI. Treat it like any other production secret and inject it through the platform secret store, not through source control.
### Reverse Proxy Expectations
The app should sit behind HTTPS. In practice that means:
- publish only the public FaceAI host name externally
- forward the original host and scheme headers from the proxy
- keep the container bound to localhost or a private network if possible
- allow normal browser redirects between the legacy site and the FaceAI host
### Post-Deploy Validation
After the Compose stack is up, validate at least the following:
1. `GET /health` returns `{"ok":true}` through the public FaceAI host.
2. The legacy handoff endpoint redirects to `https://faceai.../auth/callback?token=...`.
3. FaceAI can exchange the token and establish a session.
4. A search is enqueued in Redis and picked up by the processor.
5. Completing a search produces a redirect URL that points to `FACEAI_LEGACY_RETURN_URL`.
6. The legacy return endpoint can resolve the signed result and render the filtered race page.
### Current Production Limitations
This scaffold can now be deployed with the public site, processor, and Redis, but it still has important limitations:
- search state is short-lived in Redis and is not backed by a durable database
- runtime uploads and matcher output still need an agreed production retention and cleanup policy
- the final production PKL/NAS layout is not yet locked down
- the backend currently sets the FaceAI session cookie with `secure: false`, which should be hardened before final public rollout
- the local simulator endpoints under `/dev/*` are still present in the app and should be treated as non-production scaffolding
- the processor CSV parser is still based on the current scaffolded matcher output assumptions
So the Compose deployment is appropriate for hosted integration and controlled production-like rollout, but not yet for the final hardened architecture described in the integration plan.
## Environment ## Environment
Defaults are already set for local development, but these can be overridden: Defaults are already set for local development, but these can be overridden:
@ -92,6 +294,13 @@ FACEAI_PUBLIC_BASE_URL=http://localhost:3001
FACEAI_LEGACY_RETURN_URL=http://localhost:3001/dev/legacy/return FACEAI_LEGACY_RETURN_URL=http://localhost:3001/dev/legacy/return
FACEAI_SHARED_SECRET=change-me FACEAI_SHARED_SECRET=change-me
FACEAI_SESSION_COOKIE=rus_faceai_session FACEAI_SESSION_COOKIE=rus_faceai_session
FACEAI_REDIS_URL=redis://redis:6379
FACEAI_QUEUE_NAME=faceai-searches
FACEAI_RUNTIME_ROOT=/data/runtime
FACEAI_UPLOAD_ROOT=/data/runtime/uploads
FACEAI_PKL_ROOT=/data/pkl
FACEAI_TEST_PKL_ROOT=/data/pkl/test
FACEAI_MATCHER_BINARY=/opt/face-recognition/face_matcher
``` ```
If you want FaceAI to return through the new PHP bridge prepared under `www`, point `FACEAI_LEGACY_RETURN_URL` to that endpoint instead, for example `http://localhost/faceai_return.php` or the equivalent URL in your local PHP setup. If you want FaceAI to return through the new PHP bridge prepared under `www`, point `FACEAI_LEGACY_RETURN_URL` to that endpoint instead, for example `http://localhost/faceai_return.php` or the equivalent URL in your local PHP setup.
@ -104,8 +313,8 @@ FACEAI_LEGACY_RETURN_URL=http://localhost:8080/faceai_return.php
## Notes ## Notes
- The backend currently uses in-memory stores and mocked search results. - Search orchestration now uses Redis and a dedicated processor worker.
- No database or real queue is wired yet. - The checked-in Compose file is meant for local integration testing, not as-is production use.
- The local legacy simulator is intentionally backend-driven so the handoff can be tested without compiling the existing Java application. - The local legacy simulator is intentionally backend-driven so the handoff can be tested without compiling the existing Java application.
- `www/faceai_simulator.php` exists only for local testing. It does not replace the actual JSP race page. - `www/faceai_simulator.php` exists only for local testing. It does not replace the actual JSP race page.
- The final legacy integration still needs a real signed identity source and a real return-filter implementation on the old site. - The final legacy integration still needs a real signed identity source and a real return-filter implementation on the old site.

View file

@ -8,8 +8,11 @@
"start": "node src/server.js" "start": "node src/server.js"
}, },
"dependencies": { "dependencies": {
"bullmq": "^5.48.1",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.21.2" "express": "^4.21.2",
"ioredis": "^5.4.1",
"multer": "^2.0.0"
} }
} }

View file

@ -14,5 +14,13 @@ export const config = {
: process.env.NODE_ENV !== 'production', : process.env.NODE_ENV !== 'production',
localLegacyStaticRoot: process.env.FACEAI_LOCAL_LEGACY_STATIC_ROOT || defaultLocalLegacyRoot, localLegacyStaticRoot: process.env.FACEAI_LOCAL_LEGACY_STATIC_ROOT || defaultLocalLegacyRoot,
sharedSecret: process.env.FACEAI_SHARED_SECRET || 'change-me', sharedSecret: process.env.FACEAI_SHARED_SECRET || 'change-me',
sessionCookieName: process.env.FACEAI_SESSION_COOKIE || 'rus_faceai_session' sessionCookieName: process.env.FACEAI_SESSION_COOKIE || 'rus_faceai_session',
redisUrl: process.env.FACEAI_REDIS_URL || 'redis://redis:6379',
queueName: process.env.FACEAI_QUEUE_NAME || 'faceai-searches',
runtimeRoot: process.env.FACEAI_RUNTIME_ROOT || '/data/runtime',
uploadRoot: process.env.FACEAI_UPLOAD_ROOT || path.join(process.env.FACEAI_RUNTIME_ROOT || '/data/runtime', 'uploads'),
searchTtlSeconds: Number(process.env.FACEAI_SEARCH_TTL_SECONDS || 24 * 60 * 60),
resultTtlSeconds: Number(process.env.FACEAI_RESULT_TTL_SECONDS || 24 * 60 * 60),
rateLimitWindowSeconds: Number(process.env.FACEAI_RATE_LIMIT_WINDOW_SECONDS || 10 * 60),
rateLimitMaxRequests: Number(process.env.FACEAI_RATE_LIMIT_MAX_REQUESTS || 5)
}; };

View file

@ -0,0 +1,9 @@
export function normalizeMatches(result) {
return (result.matches || []).map((match) => ({
id: match.photoId,
label: match.label || match.photoId,
checkpoint: match.checkpoint || '-',
thumb: match.thumb || match.photoId,
score: match.score ?? null
}));
}

View file

@ -0,0 +1,11 @@
import { Queue } from 'bullmq';
let queue = null;
export function getSearchQueue({ queueName, connection }) {
if (!queue) {
queue = new Queue(queueName, { connection });
}
return queue;
}

View file

@ -0,0 +1,138 @@
import Redis from 'ioredis';
import { randomId } from './auth.js';
export function createRedisConnection(redisUrl) {
return new Redis(redisUrl, {
maxRetriesPerRequest: null,
enableReadyCheck: true
});
}
function searchKey(searchId) {
return `faceai:search:${searchId}`;
}
function resultKey(resultId) {
return `faceai:result:${resultId}`;
}
function activeSearchKey(userId) {
return `faceai:active-search:user:${userId}`;
}
function rateLimitKey(userId) {
return `faceai:rate-limit:${userId}`;
}
export async function incrementRateLimit(redis, userId, windowSeconds) {
const key = rateLimitKey(userId);
const count = await redis.incr(key);
if (count === 1) {
await redis.expire(key, windowSeconds);
}
return count;
}
export async function acquireActiveSearchLock(redis, userId, searchId, ttlSeconds) {
const result = await redis.set(activeSearchKey(userId), searchId, 'EX', ttlSeconds, 'NX');
return result === 'OK';
}
export async function releaseActiveSearchLock(redis, userId, searchId) {
const key = activeSearchKey(userId);
const current = await redis.get(key);
if (current === String(searchId)) {
await redis.del(key);
}
}
export async function getActiveSearchId(redis, userId) {
return redis.get(activeSearchKey(userId));
}
export async function createSearchRecord(redis, payload, ttlSeconds) {
const searchId = randomId('search');
const record = {
id: searchId,
status: 'queued',
resultId: null,
matchCount: 0,
errorCode: null,
errorMessage: null,
createdAt: Date.now(),
startedAt: null,
completedAt: null,
...payload
};
await redis.set(searchKey(searchId), JSON.stringify(record), 'EX', ttlSeconds);
return record;
}
export async function saveSearchRecord(redis, record, ttlSeconds) {
await redis.set(searchKey(record.id), JSON.stringify(record), 'EX', ttlSeconds);
return record;
}
export async function getSearchRecord(redis, searchId) {
const raw = await redis.get(searchKey(searchId));
return raw ? JSON.parse(raw) : null;
}
async function updateSearchRecord(redis, searchId, updater, ttlSeconds) {
const current = await getSearchRecord(redis, searchId);
if (!current) {
return null;
}
const next = updater(current);
await redis.set(searchKey(searchId), JSON.stringify(next), 'EX', ttlSeconds);
return next;
}
export async function markSearchProcessing(redis, searchId, ttlSeconds = 24 * 60 * 60) {
return updateSearchRecord(redis, searchId, (current) => ({
...current,
status: 'processing',
startedAt: Date.now(),
errorCode: null,
errorMessage: null
}), ttlSeconds);
}
export async function markSearchCompleted(redis, searchId, resultId, matchCount, ttlSeconds) {
return updateSearchRecord(redis, searchId, (current) => ({
...current,
status: 'completed',
resultId,
matchCount,
completedAt: Date.now()
}), ttlSeconds);
}
export async function markSearchFailed(redis, searchId, errorCode, errorMessage, ttlSeconds) {
return updateSearchRecord(redis, searchId, (current) => ({
...current,
status: 'failed',
errorCode,
errorMessage,
completedAt: Date.now()
}), ttlSeconds);
}
export async function storeResultRecord(redis, payload, ttlSeconds) {
const resultId = randomId('result');
const record = {
id: resultId,
createdAt: Date.now(),
...payload
};
await redis.set(resultKey(resultId), JSON.stringify(record), 'EX', ttlSeconds);
return record;
}
export async function getResultRecord(redis, resultId) {
const raw = await redis.get(resultKey(resultId));
return raw ? JSON.parse(raw) : null;
}

View file

@ -1,16 +1,49 @@
import express from 'express'; import express from 'express';
import cors from 'cors'; import cors from 'cors';
import cookieParser from 'cookie-parser'; import cookieParser from 'cookie-parser';
import multer from 'multer';
import fs from 'node:fs'; import fs from 'node:fs';
import fsp from 'node:fs/promises';
import path from 'node:path'; import path from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { config } from './config.js'; import { config } from './config.js';
import { signPayload, verifySignedPayload } from './auth.js'; import { signPayload, verifySignedPayload } from './auth.js';
import { createSession, createSearch, completeSearch, getResult, getSearch, getSession, mockCatalog } from './store.js'; import { createSession, getSession, mockCatalog } from './store.js';
import {
acquireActiveSearchLock,
createRedisConnection,
createSearchRecord,
getActiveSearchId,
getResultRecord,
getSearchRecord,
incrementRateLimit,
saveSearchRecord
} from './redis-store.js';
import { getSearchQueue } from './queue.js';
import { normalizeMatches } from './matcher-results.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
const frontendDist = path.resolve(__dirname, '../../frontend/dist'); const frontendDist = path.resolve(__dirname, '../../frontend/dist');
const app = express(); const app = express();
const redis = createRedisConnection(config.redisUrl);
const searchQueue = getSearchQueue({ queueName: config.queueName, connection: redis });
await fsp.mkdir(config.uploadRoot, { recursive: true });
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
const pendingRoot = path.join(config.uploadRoot, 'pending');
fsp.mkdir(pendingRoot, { recursive: true })
.then(() => cb(null, pendingRoot))
.catch((error) => cb(error));
},
filename: (req, file, cb) => {
const safeName = file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_');
cb(null, `${Date.now()}_${safeName}`);
}
})
});
app.use(cookieParser()); app.use(cookieParser());
app.use(express.json()); app.use(express.json());
@ -42,6 +75,25 @@ function requireSession(req, res, next) {
next(); next();
} }
async function enforceSearchRateLimit(req, res, next) {
const userId = req.faceaiSession?.user?.id;
if (!userId) {
res.status(401).json({ error: 'Not authenticated with FaceAI' });
return;
}
const count = await incrementRateLimit(redis, userId, config.rateLimitWindowSeconds);
if (count > config.rateLimitMaxRequests) {
res.status(429).json({
error: 'Too many search attempts. Please try again later.',
code: 'RATE_LIMITED'
});
return;
}
next();
}
function issueHandoffToken({ raceId, raceSlug, lang, returnUrl }) { function issueHandoffToken({ raceId, raceSlug, lang, returnUrl }) {
const race = mockCatalog[raceId] || { id: raceId, slug: raceSlug || `race-${raceId}`, name: raceSlug || `Race ${raceId}` }; const race = mockCatalog[raceId] || { id: raceId, slug: raceSlug || `race-${raceId}`, name: raceSlug || `Race ${raceId}` };
@ -185,7 +237,7 @@ app.get('/dev/legacy/launch', (req, res) => {
res.redirect(`${config.frontendUrl}/auth/callback?token=${encodeURIComponent(token)}`); res.redirect(`${config.frontendUrl}/auth/callback?token=${encodeURIComponent(token)}`);
}); });
app.get('/dev/legacy/return', (req, res) => { app.get('/dev/legacy/return', async (req, res) => {
try { try {
const token = String(req.query.token || ''); const token = String(req.query.token || '');
const payload = verifySignedPayload(token, config.sharedSecret); const payload = verifySignedPayload(token, config.sharedSecret);
@ -193,12 +245,17 @@ app.get('/dev/legacy/return', (req, res) => {
throw new Error('Wrong token type'); throw new Error('Wrong token type');
} }
const result = getResult(String(req.query.resultId || payload.resultId)); const result = await getResultRecord(redis, String(req.query.resultId || payload.resultId));
if (!result || result.userId !== payload.userId) { if (!result || result.userId !== payload.userId) {
throw new Error('Result not found'); throw new Error('Result not found');
} }
res.type('html').send(renderLegacyRacePage({ raceId: result.raceId, lang: result.lang || 'it', result })); const normalizedResult = {
...result,
matches: normalizeMatches(result)
};
res.type('html').send(renderLegacyRacePage({ raceId: result.raceId, lang: result.lang || 'it', result: normalizedResult }));
} catch (error) { } catch (error) {
res.status(400).type('html').send(`<h1>Return handoff failed</h1><p>${escapeHtml(error.message)}</p>`); res.status(400).type('html').send(`<h1>Return handoff failed</h1><p>${escapeHtml(error.message)}</p>`);
} }
@ -247,33 +304,86 @@ app.get('/api/session', requireSession, (req, res) => {
res.json(req.faceaiSession); res.json(req.faceaiSession);
}); });
app.post('/api/searches', requireSession, (req, res) => { app.post('/api/searches', requireSession, enforceSearchRateLimit, upload.single('selfie'), async (req, res) => {
const raceId = String(req.body.raceId || req.faceaiSession.race.id); try {
const selfieName = String(req.body.selfieName || 'selfie.jpg'); const raceId = String(req.body.raceId || req.faceaiSession.race.id);
const userId = String(req.faceaiSession.user.id);
const activeSearchId = await getActiveSearchId(redis, userId);
const search = createSearch({ if (activeSearchId) {
raceId, res.status(409).json({
selfieName, error: 'There is already an operation being processed.',
user: req.faceaiSession.user, code: 'ACTIVE_SEARCH_EXISTS',
returnUrl: req.faceaiSession.returnUrl, activeSearchId
lang: req.faceaiSession.lang });
}); return;
}
setTimeout(() => { if (!req.file) {
completeSearch(search.id); res.status(400).json({
}, 3500); error: 'Choose a selfie before starting the search.',
code: 'MISSING_SELFIE'
});
return;
}
res.status(201).json({ const race = mockCatalog[raceId] || req.faceaiSession.race;
id: search.id, const search = await createSearchRecord(redis, {
status: search.status, raceId,
raceId: search.raceId, raceName: race?.name || raceId,
selfieName: search.selfieName userId,
}); returnUrl: req.faceaiSession.returnUrl,
lang: req.faceaiSession.lang,
selfieName: req.file.originalname,
selfiePath: req.file.path,
uploadPath: req.file.path
}, config.searchTtlSeconds);
const lockAcquired = await acquireActiveSearchLock(redis, userId, search.id, config.searchTtlSeconds);
if (!lockAcquired) {
await fsp.unlink(req.file.path).catch(() => {});
res.status(409).json({
error: 'There is already an operation being processed.',
code: 'ACTIVE_SEARCH_EXISTS'
});
return;
}
const finalUploadDir = path.join(config.uploadRoot, search.id);
await fsp.mkdir(finalUploadDir, { recursive: true });
const finalUploadPath = path.join(finalUploadDir, path.basename(req.file.path));
await fsp.rename(req.file.path, finalUploadPath);
const updatedSearch = await saveSearchRecord(redis, {
...search,
selfiePath: finalUploadPath,
uploadPath: finalUploadPath
}, config.searchTtlSeconds);
await searchQueue.add('run-search', {
searchId: search.id
}, {
removeOnComplete: 100,
removeOnFail: 100
});
res.status(201).json({
id: updatedSearch.id,
status: updatedSearch.status,
raceId: updatedSearch.raceId,
selfieName: updatedSearch.selfieName,
matchCount: updatedSearch.matchCount,
errorCode: updatedSearch.errorCode,
errorMessage: updatedSearch.errorMessage
});
} catch (error) {
res.status(500).json({ error: error.message || 'Unable to create the search.' });
}
}); });
app.get('/api/searches/:id', requireSession, (req, res) => { app.get('/api/searches/:id', requireSession, async (req, res) => {
const search = getSearch(req.params.id); const search = await getSearchRecord(redis, req.params.id);
if (!search || search.user.id !== req.faceaiSession.user.id) { if (!search || search.userId !== req.faceaiSession.user.id) {
res.status(404).json({ error: 'Search not found' }); res.status(404).json({ error: 'Search not found' });
return; return;
} }
@ -285,13 +395,15 @@ app.get('/api/searches/:id', requireSession, (req, res) => {
resultId: search.resultId, resultId: search.resultId,
createdAt: search.createdAt, createdAt: search.createdAt,
completedAt: search.completedAt, completedAt: search.completedAt,
matchCount: search.matches.length matchCount: search.matchCount || 0,
errorCode: search.errorCode,
errorMessage: search.errorMessage
}); });
}); });
app.get('/api/searches/:id/redirect', requireSession, (req, res) => { app.get('/api/searches/:id/redirect', requireSession, async (req, res) => {
const search = getSearch(req.params.id); const search = await getSearchRecord(redis, req.params.id);
if (!search || search.user.id !== req.faceaiSession.user.id) { if (!search || search.userId !== req.faceaiSession.user.id) {
res.status(404).json({ error: 'Search not found' }); res.status(404).json({ error: 'Search not found' });
return; return;
} }
@ -301,7 +413,12 @@ app.get('/api/searches/:id/redirect', requireSession, (req, res) => {
return; return;
} }
const result = getResult(search.resultId); const result = await getResultRecord(redis, search.resultId);
if (!result) {
res.status(404).json({ error: 'Result not found' });
return;
}
const token = issueReturnToken(result); const token = issueReturnToken(result);
res.json({ res.json({
@ -309,7 +426,7 @@ app.get('/api/searches/:id/redirect', requireSession, (req, res) => {
}); });
}); });
app.get('/bridge/results/:id', (req, res) => { app.get('/bridge/results/:id', async (req, res) => {
try { try {
const token = String(req.query.token || ''); const token = String(req.query.token || '');
const payload = verifySignedPayload(token, config.sharedSecret); const payload = verifySignedPayload(token, config.sharedSecret);
@ -321,7 +438,7 @@ app.get('/bridge/results/:id', (req, res) => {
throw new Error('Result id mismatch'); throw new Error('Result id mismatch');
} }
const result = getResult(req.params.id); const result = await getResultRecord(redis, req.params.id);
if (!result || result.userId !== payload.userId) { if (!result || result.userId !== payload.userId) {
throw new Error('Result not found'); throw new Error('Result not found');
} }
@ -340,6 +457,15 @@ app.get('/bridge/results/:id', (req, res) => {
} }
}); });
app.get('/api/health/queue', async (req, res) => {
try {
await redis.ping();
res.json({ ok: true });
} catch (error) {
res.status(500).json({ ok: false, error: error.message });
}
});
if (fs.existsSync(frontendDist)) { if (fs.existsSync(frontendDist)) {
app.use(express.static(frontendDist)); app.use(express.static(frontendDist));
app.get('*', (req, res, next) => { app.get('*', (req, res, next) => {

View file

@ -34,8 +34,6 @@ export const mockCatalog = {
}; };
const sessions = new Map(); const sessions = new Map();
const searches = new Map();
const results = new Map();
export function createSession(session) { export function createSession(session) {
const sessionId = randomId('sess'); const sessionId = randomId('sess');
@ -49,62 +47,3 @@ export function createSession(session) {
export function getSession(sessionId) { export function getSession(sessionId) {
return sessions.get(sessionId) || null; return sessions.get(sessionId) || null;
} }
export function createSearch({ raceId, user, selfieName, returnUrl, lang }) {
const searchId = randomId('search');
searches.set(searchId, {
id: searchId,
raceId,
user,
selfieName,
returnUrl,
lang,
status: 'processing',
createdAt: Date.now(),
completedAt: null,
resultId: null,
matches: []
});
return searches.get(searchId);
}
export function getSearch(searchId) {
return searches.get(searchId) || null;
}
export function completeSearch(searchId) {
const search = searches.get(searchId);
if (!search) {
return null;
}
const race = mockCatalog[search.raceId];
const matches = (race?.photos || []).slice(0, Math.min(4, race?.photos?.length || 0));
const resultId = randomId('result');
results.set(resultId, {
id: resultId,
raceId: search.raceId,
raceName: race?.name || search.raceId,
userId: search.user.id,
returnUrl: search.returnUrl,
lang: search.lang,
matches,
createdAt: Date.now()
});
const completed = {
...search,
status: 'completed',
completedAt: Date.now(),
resultId,
matches
};
searches.set(searchId, completed);
return completed;
}
export function getResult(resultId) {
return results.get(resultId) || null;
}

View file

@ -46,6 +46,10 @@ const statusLabel = computed(() => {
return `Ricerca completata. Trovate ${activeSearch.value.matchCount} foto corrispondenti.`; return `Ricerca completata. Trovate ${activeSearch.value.matchCount} foto corrispondenti.`;
} }
if (activeSearch.value.status === 'failed') {
return 'La ricerca non e stata completata. Verifica il messaggio di errore e riprova.';
}
return 'Ricerca in corso. Il sistema aggiorna automaticamente lo stato finche il risultato non e pronto.'; return 'Ricerca in corso. Il sistema aggiorna automaticamente lo stato finche il risultato non e pronto.';
}); });
@ -75,6 +79,12 @@ async function pollSearch(searchId) {
} }
activeSearch.value = await response.json(); activeSearch.value = await response.json();
if (activeSearch.value.status === 'failed') {
isSubmitting.value = false;
errorMessage.value = activeSearch.value.errorMessage || 'The search failed.';
return;
}
if (activeSearch.value.status === 'completed') { if (activeSearch.value.status === 'completed') {
isSubmitting.value = false; isSubmitting.value = false;
const redirectResponse = await fetch(`/api/searches/${searchId}/redirect`, { credentials: 'include' }); const redirectResponse = await fetch(`/api/searches/${searchId}/redirect`, { credentials: 'include' });
@ -108,16 +118,14 @@ async function submitSearch() {
isSubmitting.value = true; isSubmitting.value = true;
const formData = new FormData();
formData.set('raceId', session.value.race.id);
formData.set('selfie', selectedFile.value);
const response = await fetch('/api/searches', { const response = await fetch('/api/searches', {
method: 'POST', method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include', credentials: 'include',
body: JSON.stringify({ body: formData
raceId: session.value.race.id,
selfieName: selectedFile.value.name
})
}); });
const payload = await response.json(); const payload = await response.json();

View file

@ -0,0 +1,14 @@
{
"name": "@regalami/faceai-processor",
"private": true,
"type": "module",
"scripts": {
"dev": "node --watch src/worker.js",
"build": "node -e \"console.log('processor build not required')\"",
"start": "node src/worker.js"
},
"dependencies": {
"bullmq": "^5.48.1",
"ioredis": "^5.4.1"
}
}

View file

@ -0,0 +1,12 @@
export const config = {
redisUrl: process.env.FACEAI_REDIS_URL || 'redis://redis:6379',
queueName: process.env.FACEAI_QUEUE_NAME || 'faceai-searches',
workerConcurrency: Number(process.env.FACEAI_WORKER_CONCURRENCY || 2),
workerTimeoutMs: Number(process.env.FACEAI_WORKER_TIMEOUT_MS || 5 * 60 * 1000),
runtimeRoot: process.env.FACEAI_RUNTIME_ROOT || '/data/runtime',
pklRoot: process.env.FACEAI_PKL_ROOT || '/data/pkl',
fallbackPklRoot: process.env.FACEAI_TEST_PKL_ROOT || '/data/pkl/test',
matcherBinary: process.env.FACEAI_MATCHER_BINARY || '/opt/face-recognition/face_matcher',
searchTtlSeconds: Number(process.env.FACEAI_SEARCH_TTL_SECONDS || 24 * 60 * 60),
resultTtlSeconds: Number(process.env.FACEAI_RESULT_TTL_SECONDS || 24 * 60 * 60)
};

View file

@ -0,0 +1,99 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { spawn } from 'node:child_process';
async function fileExists(filePath) {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
}
export async function resolvePklPath({ raceId, pklRoot, fallbackPklRoot }) {
const preferred = path.join(pklRoot, String(raceId), 'face_encodings.pkl');
if (await fileExists(preferred)) {
return preferred;
}
const flatFile = path.join(pklRoot, `${raceId}.pkl`);
if (await fileExists(flatFile)) {
return flatFile;
}
const fallbackEntries = await fs.readdir(fallbackPklRoot).catch(() => []);
const fallbackFile = fallbackEntries.find((entry) => entry.toLowerCase().endsWith('.pkl'));
if (fallbackFile) {
return path.join(fallbackPklRoot, fallbackFile);
}
throw new Error(`No PKL file available for race ${raceId}`);
}
export async function runFaceMatcher({ matcherBinary, selfiePath, pklPath, csvPath, logPath, timeoutMs }) {
await fs.mkdir(path.dirname(csvPath), { recursive: true });
await fs.mkdir(path.dirname(logPath), { recursive: true });
return new Promise((resolve, reject) => {
const child = spawn(matcherBinary, [
'--image', selfiePath,
'--encodings', pklPath,
'--out', csvPath,
'--log', logPath
], {
stdio: 'ignore'
});
const timer = setTimeout(() => {
child.kill('SIGKILL');
reject(new Error('face_matcher timed out'));
}, timeoutMs);
child.on('error', (error) => {
clearTimeout(timer);
reject(error);
});
child.on('exit', (code) => {
clearTimeout(timer);
if (code === 0) {
resolve();
return;
}
reject(new Error(`face_matcher exited with code ${code}`));
});
});
}
export async function parseMatcherCsv(csvPath) {
const content = await fs.readFile(csvPath, 'utf8');
const lines = content
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
if (!lines.length) {
return [];
}
const rows = lines.map((line) => line.split(',').map((part) => part.trim().replace(/^"|"$/g, '')));
const firstRow = rows[0];
const hasHeader = firstRow.some((cell) => /file|image|score|distance|confidence/i.test(cell));
const dataRows = hasHeader ? rows.slice(1) : rows;
return dataRows
.filter((cells) => cells[0])
.map((cells) => {
const photoId = path.basename(cells[0]);
const numericCell = cells.find((cell, index) => index > 0 && !Number.isNaN(Number(cell)));
const score = numericCell ? Number(numericCell) : null;
return {
photoId,
score,
label: photoId
};
});
}

View file

@ -0,0 +1,82 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { Worker } from 'bullmq';
import { config } from './config.js';
import {
createRedisConnection,
getSearchRecord,
markSearchCompleted,
markSearchFailed,
markSearchProcessing,
releaseActiveSearchLock,
storeResultRecord
} from '../../backend/src/redis-store.js';
import { parseMatcherCsv, resolvePklPath, runFaceMatcher } from './worker-utils.js';
const connection = createRedisConnection(config.redisUrl);
async function processJob(job) {
const searchId = String(job.data.searchId || '');
const search = await getSearchRecord(connection, searchId);
if (!search) {
throw new Error(`Search ${searchId} not found`);
}
await markSearchProcessing(connection, searchId, config.searchTtlSeconds);
const searchDir = path.join(config.runtimeRoot, 'searches', searchId);
await fs.mkdir(searchDir, { recursive: true });
try {
const pklPath = await resolvePklPath({
raceId: search.raceId,
pklRoot: config.pklRoot,
fallbackPklRoot: config.fallbackPklRoot
});
const csvPath = path.join(searchDir, 'result.csv');
const logPath = path.join(searchDir, 'matcher.log');
await runFaceMatcher({
matcherBinary: config.matcherBinary,
selfiePath: search.selfiePath,
pklPath,
csvPath,
logPath,
timeoutMs: config.workerTimeoutMs
});
const matches = await parseMatcherCsv(csvPath);
const result = await storeResultRecord(connection, {
raceId: search.raceId,
raceName: search.raceName,
userId: search.userId,
returnUrl: search.returnUrl,
lang: search.lang,
matches
}, config.resultTtlSeconds);
await markSearchCompleted(connection, searchId, result.id, matches.length, config.searchTtlSeconds);
await releaseActiveSearchLock(connection, search.userId, searchId);
} catch (error) {
await markSearchFailed(connection, searchId, 'PROCESSOR_ERROR', error.message, config.searchTtlSeconds);
await releaseActiveSearchLock(connection, search.userId, searchId);
throw error;
}
}
const worker = new Worker(config.queueName, processJob, {
connection,
concurrency: config.workerConcurrency
});
worker.on('completed', (job) => {
console.log(`Completed FaceAI search ${job.data.searchId}`);
});
worker.on('failed', (job, error) => {
const searchId = job?.data?.searchId || 'unknown';
console.error(`Failed FaceAI search ${searchId}: ${error.message}`);
});
console.log(`FaceAI processor listening on queue ${config.queueName} with concurrency ${config.workerConcurrency}`);

View file

@ -13,11 +13,43 @@ services:
FACEAI_LOCAL_LEGACY_STATIC_ROOT: /legacy-www FACEAI_LOCAL_LEGACY_STATIC_ROOT: /legacy-www
FACEAI_SHARED_SECRET: change-me FACEAI_SHARED_SECRET: change-me
FACEAI_SESSION_COOKIE: rus_faceai_session FACEAI_SESSION_COOKIE: rus_faceai_session
FACEAI_REDIS_URL: redis://redis:6379
FACEAI_RUNTIME_ROOT: /data/runtime
FACEAI_UPLOAD_ROOT: /data/runtime/uploads
volumes: volumes:
- .:/app - .:/app
- ../www:/legacy-www:ro - ../www:/legacy-www:ro
- faceai-runtime:/data/runtime
ports: ports:
- "3001:3001" - "3001:3001"
depends_on:
- redis
processor:
image: node:20-bookworm-slim
container_name: regalami-faceai-processor
working_dir: /app
command: sh -c "npm run start --workspace @regalami/faceai-processor"
environment:
FACEAI_REDIS_URL: redis://redis:6379
FACEAI_QUEUE_NAME: faceai-searches
FACEAI_RUNTIME_ROOT: /data/runtime
FACEAI_PKL_ROOT: /data/pkl
FACEAI_TEST_PKL_ROOT: /data/pkl/test
FACEAI_WORKER_CONCURRENCY: 2
FACEAI_MATCHER_BINARY: /opt/face-recognition/face_matcher
volumes:
- .:/app
- ../bin/Face_Recognition_Unix:/opt/face-recognition:ro
- ../test_pkl:/data/pkl/test:ro
- faceai-runtime:/data/runtime
depends_on:
- redis
redis:
image: redis:7-alpine
container_name: regalami-faceai-redis
command: redis-server --appendonly no
legacy-php: legacy-php:
image: php:8.3-apache image: php:8.3-apache
@ -32,3 +64,6 @@ services:
- ../www:/var/www/html - ../www:/var/www/html
ports: ports:
- "8080:80" - "8080:80"
volumes:
faceai-runtime:

View file

@ -5,6 +5,7 @@ WORKDIR /app
COPY package.json ./ COPY package.json ./
COPY apps/frontend/package.json apps/frontend/package.json COPY apps/frontend/package.json apps/frontend/package.json
COPY apps/backend/package.json apps/backend/package.json COPY apps/backend/package.json apps/backend/package.json
COPY apps/processor/package.json apps/processor/package.json
RUN npm install RUN npm install

View file

@ -0,0 +1,166 @@
# FaceAI Processor Technical Design
## Goal
Add an internal processor service that executes `face_matcher` jobs for the public FaceAI site, while preventing duplicate searches per user and keeping all state short-lived and restart-safe.
## Scope Of This Slice
- add Redis-backed queue and job state
- add a dedicated `processor` workspace and container scaffold
- replace in-memory search orchestration in the public backend
- preserve the existing frontend polling and legacy return flow
- support local PKL testing from `test_pkl/`
This slice does not yet implement production NAS mounting, persistent databases, or a final parser tailored to the real matcher CSV format.
## Runtime Architecture
### Public backend
- owns the authenticated API used by the Vue frontend
- stores uploaded selfies in a shared runtime volume
- enqueues jobs into BullMQ
- keeps per-search state, results, rate limits, and active-user locks in Redis
- never executes `face_matcher` directly
### Processor
- consumes queue jobs from Redis using BullMQ worker concurrency
- resolves the race-scoped PKL path for each job
- executes the Linux `face_matcher` binary
- parses the CSV result into legacy-compatible `photoId` matches
- writes final state and result payload back to Redis
### Redis
- queue broker for BullMQ
- source of truth for active-user locks
- source of truth for search status and short-lived results
- source of truth for rate-limit counters
## Queue And Locking Model
- queue name: `faceai-searches`
- active lock key: `faceai:active-search:user:{legacyUserId}`
- search record key: `faceai:search:{searchId}`
- result record key: `faceai:result:{resultId}`
- rate limit key prefix: `faceai:rate-limit:{legacyUserId}`
`POST /api/searches` must acquire the active-user lock before enqueueing. If the lock already exists, the backend returns `409` with error code `ACTIVE_SEARCH_EXISTS`.
The lock is released only when the processor marks the search as terminal: `completed`, `failed`, or `timed_out`.
## Race And PKL Resolution
The canonical race key is the legacy `id_gara`, already exposed as `raceId` in the existing handoff flow.
The processor resolves the PKL path using a race-based directory layout:
```text
/data/pkl/
101/
face_encodings.pkl
202/
face_encodings.pkl
```
The lookup rule is:
1. try `/data/pkl/{raceId}/face_encodings.pkl`
2. optionally fall back to `/data/pkl/{raceId}.pkl`
3. fail the job if neither exists
For local development, `test_pkl/` is mounted into `/data/pkl/test` and the backend can fall back to the first `.pkl` file in that folder when no race-specific file exists yet.
## Shared Runtime Storage
Both the public backend and the processor mount the same writable runtime directory:
```text
/data/runtime/
uploads/
searches/
```
- uploaded selfies are written under `uploads/{searchId}/`
- worker output and logs are written under `searches/{searchId}/`
- cleanup can safely remove old per-search directories after retention expires
## Search Lifecycle
1. frontend uploads a selfie and calls `POST /api/searches`
2. backend validates session, rate limit, and active-user lock
3. backend stores the upload and creates a Redis search record with status `queued`
4. backend enqueues a BullMQ job
5. processor picks up the job and sets status `processing`
6. processor runs `face_matcher`
7. processor parses CSV output into matches
8. processor stores a result record and marks the search `completed`
9. frontend polling reads Redis-backed state through `GET /api/searches/:id`
10. existing redirect flow sends the user back to the legacy filtered page
## Search Record Shape
```json
{
"id": "search_...",
"status": "queued",
"raceId": "101",
"userId": "legacy-user-1",
"returnUrl": "https://...",
"lang": "it",
"selfieName": "selfie.jpg",
"selfiePath": "/data/runtime/uploads/search_.../selfie.jpg",
"resultId": null,
"matchCount": 0,
"errorCode": null,
"errorMessage": null,
"createdAt": 0,
"startedAt": null,
"completedAt": null
}
```
## Result Shape
```json
{
"id": "result_...",
"raceId": "101",
"raceName": "Mezza di Firenze",
"userId": "legacy-user-1",
"returnUrl": "https://...",
"lang": "it",
"matches": [
{
"photoId": "legacy-photo-id",
"score": 0.98,
"label": "legacy-photo-id"
}
],
"createdAt": 0
}
```
## Compose Topology
- `faceai`: public backend plus built frontend
- `processor`: queue consumer and matcher executor
- `redis`: queue and short-lived state
- `legacy-php`: local bridge simulator for end-to-end testing
## Operational Defaults
- worker concurrency: `2`
- active search retention: `24h`
- result retention: `24h`
- rate limit window: `5 requests / 10 minutes / user`
- worker timeout: `5 minutes`
## Known Follow-Up Work
- confirm the real CSV columns emitted by `face_matcher`
- verify the Linux binary shared library requirements inside the processor image
- replace the PKL fallback with a strict NAS-backed race mapping once the final folder layout is agreed
- add cleanup jobs for expired runtime files

431
faceai/package-lock.json generated
View file

@ -7,7 +7,8 @@
"name": "faceai", "name": "faceai",
"workspaces": [ "workspaces": [
"apps/frontend", "apps/frontend",
"apps/backend" "apps/backend",
"apps/processor"
], ],
"devDependencies": { "devDependencies": {
"concurrently": "^9.1.2" "concurrently": "^9.1.2"
@ -16,9 +17,12 @@
"apps/backend": { "apps/backend": {
"name": "@regalami/faceai-backend", "name": "@regalami/faceai-backend",
"dependencies": { "dependencies": {
"bullmq": "^5.48.1",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.21.2" "express": "^4.21.2",
"ioredis": "^5.4.1",
"multer": "^2.0.0"
} }
}, },
"apps/frontend": { "apps/frontend": {
@ -32,6 +36,13 @@
"vite": "^6.1.0" "vite": "^6.1.0"
} }
}, },
"apps/processor": {
"name": "@regalami/faceai-processor",
"dependencies": {
"bullmq": "^5.48.1",
"ioredis": "^5.4.1"
}
},
"node_modules/@babel/helper-string-parser": { "node_modules/@babel/helper-string-parser": {
"version": "7.27.1", "version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
@ -520,12 +531,96 @@
"node": ">=18" "node": ">=18"
} }
}, },
"node_modules/@ioredis/commands": {
"version": "1.5.1",
"resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz",
"integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==",
"license": "MIT"
},
"node_modules/@jridgewell/sourcemap-codec": { "node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5", "version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
"integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.3.tgz",
"integrity": "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.3.tgz",
"integrity": "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
]
},
"node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.3.tgz",
"integrity": "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==",
"cpu": [
"arm"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.3.tgz",
"integrity": "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.3.tgz",
"integrity": "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.3.tgz",
"integrity": "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
]
},
"node_modules/@regalami/faceai-backend": { "node_modules/@regalami/faceai-backend": {
"resolved": "apps/backend", "resolved": "apps/backend",
"link": true "link": true
@ -534,6 +629,10 @@
"resolved": "apps/frontend", "resolved": "apps/frontend",
"link": true "link": true
}, },
"node_modules/@regalami/faceai-processor": {
"resolved": "apps/processor",
"link": true
},
"node_modules/@rollup/rollup-android-arm-eabi": { "node_modules/@rollup/rollup-android-arm-eabi": {
"version": "4.60.1", "version": "4.60.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz",
@ -1050,6 +1149,12 @@
"url": "https://github.com/chalk/ansi-styles?sponsor=1" "url": "https://github.com/chalk/ansi-styles?sponsor=1"
} }
}, },
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/array-flatten": { "node_modules/array-flatten": {
"version": "1.1.1", "version": "1.1.1",
"resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
@ -1080,6 +1185,38 @@
"npm": "1.2.8000 || >= 1.4.16" "npm": "1.2.8000 || >= 1.4.16"
} }
}, },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/bullmq": {
"version": "5.73.4",
"resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.73.4.tgz",
"integrity": "sha512-Q+NeFLtdKSD3GDPYSX4pH+Mc9E4OZVKimXwrnZ5WmndNy31COMy4vQV9zfhgfHGSUFrlpsBicfKYbSjx9FbO+A==",
"license": "MIT",
"dependencies": {
"cron-parser": "4.9.0",
"ioredis": "5.10.1",
"msgpackr": "1.11.5",
"node-abort-controller": "3.1.1",
"semver": "7.7.4",
"tslib": "2.8.1",
"uuid": "11.1.0"
}
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": { "node_modules/bytes": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@ -1163,6 +1300,15 @@
"node": ">=12" "node": ">=12"
} }
}, },
"node_modules/cluster-key-slot": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz",
"integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/color-convert": { "node_modules/color-convert": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@ -1183,6 +1329,21 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/concurrently": { "node_modules/concurrently": {
"version": "9.2.1", "version": "9.2.1",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz", "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.1.tgz",
@ -1274,6 +1435,18 @@
"url": "https://opencollective.com/express" "url": "https://opencollective.com/express"
} }
}, },
"node_modules/cron-parser": {
"version": "4.9.0",
"resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz",
"integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",
"license": "MIT",
"dependencies": {
"luxon": "^3.2.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/csstype": { "node_modules/csstype": {
"version": "3.2.3", "version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@ -1289,6 +1462,15 @@
"ms": "2.0.0" "ms": "2.0.0"
} }
}, },
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10"
}
},
"node_modules/depd": { "node_modules/depd": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@ -1308,6 +1490,16 @@
"npm": "1.2.8000 || >= 1.4.16" "npm": "1.2.8000 || >= 1.4.16"
} }
}, },
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"license": "Apache-2.0",
"optional": true,
"engines": {
"node": ">=8"
}
},
"node_modules/dunder-proto": { "node_modules/dunder-proto": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@ -1714,6 +1906,53 @@
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC" "license": "ISC"
}, },
"node_modules/ioredis": {
"version": "5.10.1",
"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.1.tgz",
"integrity": "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==",
"license": "MIT",
"dependencies": {
"@ioredis/commands": "1.5.1",
"cluster-key-slot": "^1.1.0",
"debug": "^4.3.4",
"denque": "^2.1.0",
"lodash.defaults": "^4.2.0",
"lodash.isarguments": "^3.1.0",
"redis-errors": "^1.2.0",
"redis-parser": "^3.0.0",
"standard-as-callback": "^2.1.0"
},
"engines": {
"node": ">=12.22.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/ioredis"
}
},
"node_modules/ioredis/node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/ioredis/node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/ipaddr.js": { "node_modules/ipaddr.js": {
"version": "1.9.1", "version": "1.9.1",
"resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
@ -1733,6 +1972,27 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/lodash.defaults": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
"integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
"license": "MIT"
},
"node_modules/lodash.isarguments": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz",
"integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
"license": "MIT"
},
"node_modules/luxon": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
"integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/magic-string": { "node_modules/magic-string": {
"version": "0.30.21", "version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@ -1817,6 +2077,56 @@
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/msgpackr": {
"version": "1.11.5",
"resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.11.5.tgz",
"integrity": "sha512-UjkUHN0yqp9RWKy0Lplhh+wlpdt9oQBYgULZOiFhV3VclSF1JnSQWZ5r9gORQlNYaUKQoR8itv7g7z1xDDuACA==",
"license": "MIT",
"optionalDependencies": {
"msgpackr-extract": "^3.0.2"
}
},
"node_modules/msgpackr-extract": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.3.tgz",
"integrity": "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"dependencies": {
"node-gyp-build-optional-packages": "5.2.2"
},
"bin": {
"download-msgpackr-prebuilds": "bin/download-prebuilds.js"
},
"optionalDependencies": {
"@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3",
"@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3",
"@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3",
"@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3",
"@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3",
"@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"
}
},
"node_modules/multer": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.1.1.tgz",
"integrity": "sha512-mo+QTzKlx8R7E5ylSXxWzGoXoZbOsRMpyitcht8By2KHvMbf3tjwosZ/Mu/XYU6UuJ3VZnODIrak5ZrPiPyB6A==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.6.0",
"concat-stream": "^2.0.0",
"type-is": "^1.6.18"
},
"engines": {
"node": ">= 10.16.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/nanoid": { "node_modules/nanoid": {
"version": "3.3.11", "version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
@ -1844,6 +2154,27 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/node-abort-controller": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz",
"integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
"license": "MIT"
},
"node_modules/node-gyp-build-optional-packages": {
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
"integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==",
"license": "MIT",
"optional": true,
"dependencies": {
"detect-libc": "^2.0.1"
},
"bin": {
"node-gyp-build-optional-packages": "bin.js",
"node-gyp-build-optional-packages-optional": "optional.js",
"node-gyp-build-optional-packages-test": "build-test.js"
}
},
"node_modules/object-assign": { "node_modules/object-assign": {
"version": "4.1.1", "version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -1991,6 +2322,41 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/redis-errors": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz",
"integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/redis-parser": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz",
"integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==",
"license": "MIT",
"dependencies": {
"redis-errors": "^1.0.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/require-directory": { "node_modules/require-directory": {
"version": "2.1.1", "version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
@ -2082,6 +2448,18 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/semver": {
"version": "7.7.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",
"integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/send": { "node_modules/send": {
"version": "0.19.2", "version": "0.19.2",
"resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz",
@ -2227,6 +2605,12 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/standard-as-callback": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz",
"integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==",
"license": "MIT"
},
"node_modules/statuses": { "node_modules/statuses": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
@ -2236,6 +2620,23 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/string-width": { "node_modules/string-width": {
"version": "4.2.3", "version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@ -2320,7 +2721,6 @@
"version": "2.8.1", "version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"dev": true,
"license": "0BSD" "license": "0BSD"
}, },
"node_modules/type-is": { "node_modules/type-is": {
@ -2336,6 +2736,12 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/unpipe": { "node_modules/unpipe": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@ -2345,6 +2751,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",
@ -2354,6 +2766,19 @@
"node": ">= 0.4.0" "node": ">= 0.4.0"
} }
}, },
"node_modules/uuid": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz",
"integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/esm/bin/uuid"
}
},
"node_modules/vary": { "node_modules/vary": {
"version": "1.1.2", "version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",

View file

@ -3,14 +3,17 @@
"private": true, "private": true,
"workspaces": [ "workspaces": [
"apps/frontend", "apps/frontend",
"apps/backend" "apps/backend",
"apps/processor"
], ],
"scripts": { "scripts": {
"dev": "concurrently \"npm:dev:backend\" \"npm:dev:frontend\"", "dev": "concurrently \"npm:dev:backend\" \"npm:dev:frontend\"",
"dev:backend": "npm run dev --workspace @regalami/faceai-backend", "dev:backend": "npm run dev --workspace @regalami/faceai-backend",
"dev:frontend": "npm run dev --workspace @regalami/faceai-frontend", "dev:frontend": "npm run dev --workspace @regalami/faceai-frontend",
"dev:processor": "npm run dev --workspace @regalami/faceai-processor",
"build": "npm run build --workspace @regalami/faceai-frontend && npm run build --workspace @regalami/faceai-backend", "build": "npm run build --workspace @regalami/faceai-frontend && npm run build --workspace @regalami/faceai-backend",
"start": "npm run start --workspace @regalami/faceai-backend" "start": "npm run start --workspace @regalami/faceai-backend",
"start:processor": "npm run start --workspace @regalami/faceai-processor"
}, },
"devDependencies": { "devDependencies": {
"concurrently": "^9.1.2" "concurrently": "^9.1.2"

View file

@ -1,117 +1,47 @@
# WWW Deployment Manifest # WWW Deployment Manifest
This document lists the files under `www/` that changed after the initial `www` import baseline and should be copied to the remote staging path: This document lists the files under `www/` in the current FaceAI feature-flag rollout that should be copied to the remote staging path:
`/home/marco/regalamiunsorriso/incoming/www` `/home/marco/regalamiunsorriso/incoming/www`
## Baseline Used ## Deployment Set
- Excluded the initial `www` import history by using commit `cc69770608bd0f1c32eeac01e16042f4e8a47012` (`First commit`) as the baseline. All files in this rollout are deployed from the current working tree.
- Included committed changes after that baseline up to `HEAD`.
- Included the current uncommitted workspace change in `www/controlCode.jsp`.
## New Files ## New Files
- `www/faceai_config.php` - None in this rollout.
- `www/faceai_handoff.php`
- `www/faceai_return.php`
- `www/faceai_simulator.php`
- `www/faceai_simulator_view.php`
## Updated Files ## Updated Files
- `www/_inc_footer.jsp`
- `www/_js/rus-ecom-240621.js` - `www/_js/rus-ecom-240621.js`
- `www/associazione-en.jsp` - `www/faceai_config.php`
- `www/associazione.jsp` - `www/faceai_handoff.php`
- `www/atleticaImmagine_chiSiamo-en.jsp` - `www/faceai_simulator_view.php`
- `www/atleticaImmagine_chiSiamo.jsp` - `www/fotoCR-en.jsp`
- `www/controlCode-en.jsp` - `www/fotoCR.jsp`
- `www/controlCode.jsp`
- `www/includes/inc-header.php`
- `www/lostPwd.jsp`
- `www/mailMessage/noMorePic.html`
- `www/mailMessage/noMorePic.txt`
- `www/mailMessage/noMorePicCc.html`
- `www/mailMessage/noMorePicScad.html`
- `www/mailMessage/noMorePicScad.txt`
- `www/mailMessage/perScadereMsg.html`
- `www/mailMessage/userMsg_it.html`
- `www/mailMessage/userMsg_itCC.html`
- `www/newsCR-en.jsp`
- `www/newsCR.jsp`
- `www/pg/controlCode.jsp`
- `www/pg/logon.jsp`
- `www/pg/registra.jsp`
- `www/users-en.jsp`
- `www/users.jsp`
## Local Workspace-Only Change Included
- `www/controlCode.jsp` currently has an uncommitted local modification and should be deployed from the working tree version, not just from `HEAD`.
## Remote Copy Target ## Remote Copy Target
- Source root: `K:\various\regalamiunsorriso` - Source root: `K:\various\regalamiunsorriso`
- Remote host: `marco@83.149.164.4:410` - Remote host: `marco@83.149.164.4:410`
- Remote path: `/home/marco/regalamiunsorriso/incoming/www` - Remote staging path: `/home/marco/regalamiunsorriso/incoming/www`
- Total files in this manifest: `30` - Remote live path: `/home/sites/regalamiunsorriso/www`
- Total files in this manifest: `6`
## Transfer Notes ## Transfer Method
- Transfer completed by streaming a tar archive over SSH and extracting it into `/home/marco/regalamiunsorriso/incoming` so the `www/...` directory structure was preserved. - Stage by streaming a tar archive over SSH and extracting it into `/home/marco/regalamiunsorriso/incoming` so the `www/...` directory structure is preserved.
- Representative remote verification succeeded for new files and updated files, including `www/faceai_config.php`, `www/faceai_handoff.php`, `www/faceai_return.php`, `www/faceai_simulator.php`, `www/faceai_simulator_view.php`, `www/controlCode.jsp`, `www/_js/rus-ecom-240621.js`, `www/includes/inc-header.php`, and `www/pg/logon.jsp`. - Promote with `/home/marco/promote-file.sh` through `sudo tcsh` so the live destination keeps its required owner, group, and mode.
- `www/controlCode.jsp` was uploaded from the local working tree, which includes an uncommitted change.
## Issues Encountered ## Verification Expectations
- The remote login shell behaves as `tcsh`, so POSIX shell loops like `for ...; do ...; done` fail unless they are explicitly run through `sh -c`. - Verify staged files with `ls -l` and `cksum`.
- The server `sh` does not accept the `-l` option, so verification commands must use `sh -c`, not `sh -lc`. - Verify live files with `ls -l`, `stat -f`, and `cksum`.
- The direct SSH and tar-based copy path works; the MCP SSH tools were not used for this transfer because they were previously failing authentication or transport checks. - Existing destination files should retain their original metadata after promotion.
## Single-File Live Promotion Test ## Known Shell Quirks
- Tested file: `www/associazione-en.jsp` - The remote login shell behaves as `tcsh`, so POSIX shell loops fail unless run through `sh -c`.
- Staged source: `/home/marco/regalamiunsorriso/incoming/www/associazione-en.jsp` - The server `sh` does not support `-l`, so use `sh -c`, not `sh -lc`.
- Live destination: `/home/sites/regalamiunsorriso/www/associazione-en.jsp` - Direct SSH plus tar works reliably on this host; MCP SSH was previously unreliable and is avoided.
- Original live metadata before copy: owner `jenkins`, group `www`, mode `100644`, size `6289`
- Live metadata after copy: owner `jenkins`, group `www`, mode `100644`, size `6139`
- Content verification after copy succeeded: `cksum` matched for staged and live files.
## Promotion Script
- Local template: `sync/promote-file.sh`
- Remote installed script: `/home/marco/promote-file.sh`
- Purpose: copy one source file to one destination file, then restore the destination file owner, group, and mode from the original live file.
- Supports an optional third argument: a metadata source file to use when the destination file does not exist yet and the target directory has mixed permission patterns.
### Command That Worked
```powershell
ssh -tt -i C:\Users\Maddo\.ssh\id_rsa -p 410 marco@83.149.164.4 "sudo tcsh -c '/home/marco/promote-file.sh /home/marco/regalamiunsorriso/incoming/www/associazione-en.jsp /home/sites/regalamiunsorriso/www/associazione-en.jsp'"
```
## Additional Problems Found During Live Promotion
- Uploading a multi-line script inline from PowerShell was unreliable in the local terminal because the prompt layer interfered with the here-string before SSH execution. Using a normal local file plus `scp` worked cleanly.
- The live-site verification command was interrupted once when run in parallel with the promotion command. Re-running verification separately avoided that issue.
- Promotion to `/home/sites/regalamiunsorriso/www` must run through `sudo tcsh`; copying as `marco` alone is not sufficient for the live path and would not preserve the required live ownership.
- Root-level PHP files on the live site do not have a single uniform mode. For example, `_inc_footer.php` and `gallery1.php` are `775`, while `test.php` is `644`. The promotion helper was extended to accept an explicit metadata source so new files can follow a chosen live pattern instead of relying on the first sibling match.
## Recommended Replication Procedure
1. Stage the file under `/home/marco/regalamiunsorriso/incoming/www/...`.
2. Inspect the live destination metadata before changing anything.
3. Run `/home/marco/promote-file.sh <staged-path> <live-path> [metadata-source]` through `sudo tcsh` in an SSH session opened with `-tt`.
4. Verify the live file with `ls -l`, `stat -f`, and `cksum` against the staged source.
## Full Live Promotion Result
- After the single-file test with `www/associazione-en.jsp`, the remaining `29` files in the manifest were promoted successfully to `/home/sites/regalamiunsorriso/www`.
- Existing destination files kept their original live owner, group, and mode.
- The new `faceai_*.php` files were created as `jenkins:www` with mode `775`, using `/home/sites/regalamiunsorriso/www/_inc_footer.php` as the explicit metadata source.
- Representative content verification succeeded with matching `cksum` values for:
- `www/faceai_config.php`
- `www/controlCode.jsp`
- `www/pg/logon.jsp`
- Representative metadata verification succeeded for updated files in root, `pg`, `includes`, and `mailMessage` directories.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -114,6 +114,79 @@ function getCurrentLangValue() {
return $("html").attr("lang") || "it"; return $("html").attr("lang") || "it";
} }
function faceAiFeatureEnabled() {
var config = window.faceAiConfig || {};
var simulatorConfig = window.faceAiSimulator || {};
var value = typeof config.enabled !== "undefined" ? config.enabled : simulatorConfig.enabled;
if (typeof value === "string") {
value = value.toLowerCase();
return value === "1" || value === "true" || value === "yes" || value === "on";
}
return value === true;
}
function faceAiEscapeHtml(value) {
return String(value || "")
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function getFaceAiErrorState() {
if (typeof URLSearchParams === "undefined") {
return null;
}
var params = new URLSearchParams(window.location.search || "");
if (params.get("faceaiError") !== "1") {
return null;
}
return {
title: params.get("faceaiErrorTitle") || "Face ID non disponibile",
message: params.get("faceaiErrorMessage") || "Il servizio Face ID non e al momento disponibile. Riprova piu tardi."
};
}
function clearFaceAiErrorState() {
if (!window.history || !window.history.replaceState || typeof URL === "undefined") {
return;
}
var cleanUrl = new URL(window.location.href);
cleanUrl.searchParams.delete("faceaiError");
cleanUrl.searchParams.delete("faceaiErrorTitle");
cleanUrl.searchParams.delete("faceaiErrorMessage");
window.history.replaceState({}, document.title, cleanUrl.pathname + cleanUrl.search + cleanUrl.hash);
}
function showFaceAiErrorModal(title, message) {
var modal = $("#faceAiErrorModal");
if (!modal.length) {
$("body").append('<div class="modal fade" id="faceAiErrorModal" tabindex="-1" role="dialog" aria-labelledby="faceAiErrorModalLabel" aria-hidden="true"><div class="modal-dialog modal-sm" role="document"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="faceAiErrorModalLabel"></h5><button type="button" class="close" data-dismiss="modal" aria-label="Close"><i class="fa fa-close"></i> </button></div><div class="modal-body text-center"><p id="faceAiErrorModalMessage" class="mb-0"></p></div></div></div></div>');
modal = $("#faceAiErrorModal");
}
$("#faceAiErrorModalLabel").html(faceAiEscapeHtml(title));
$("#faceAiErrorModalMessage").html(faceAiEscapeHtml(message));
modal.modal("show");
}
function initFaceAiErrorModal() {
var errorState = getFaceAiErrorState();
if (!errorState) {
return;
}
showFaceAiErrorModal(errorState.title, errorState.message);
clearFaceAiErrorState();
}
function buildFaceAiLaunchUrl() { function buildFaceAiLaunchUrl() {
var raceId = $("#id_gara").val() || ""; var raceId = $("#id_gara").val() || "";
var raceSlug = $("#garaDesc").val() || ""; var raceSlug = $("#garaDesc").val() || "";
@ -153,7 +226,7 @@ function launchFaceAi() {
function initFaceAiRaceSearchButton() { function initFaceAiRaceSearchButton() {
var select = $("#tipoPuntoFoto"); var select = $("#tipoPuntoFoto");
if (!select.length || $("#faceaiLaunchButton").length) { if (!select.length || $("#faceaiLaunchButton").length || !faceAiFeatureEnabled()) {
return; return;
} }
@ -377,6 +450,7 @@ function goPage()
$(function() { $(function() {
initFaceAiRaceSearchButton(); initFaceAiRaceSearchButton();
initFaceAiErrorModal();
}); });

View file

@ -6,6 +6,69 @@ function faceai_env($key, $default = null)
return $value === false ? $default : $value; return $value === false ? $default : $value;
} }
function faceai_env_flag($key, $default = false)
{
$value = strtolower(trim((string) faceai_env($key, $default ? '1' : '0')));
return in_array($value, array('1', 'true', 'yes', 'on'), true);
}
function faceai_request_host()
{
if (empty($_SERVER['HTTP_HOST'])) {
return '';
}
return strtolower(trim((string) $_SERVER['HTTP_HOST']));
}
function faceai_is_local_host($host)
{
$normalized = strtolower(trim((string) $host));
if ($normalized === '') {
return false;
}
$withoutPort = preg_replace('/:\d+$/', '', $normalized);
return in_array($withoutPort, array('localhost', '127.0.0.1', '::1'), true);
}
function faceai_request_targets_local_frontend()
{
if (faceai_is_local_host(faceai_request_host())) {
return true;
}
$returnUrl = faceai_request_value('returnUrl');
if ($returnUrl === '') {
return false;
}
$host = parse_url($returnUrl, PHP_URL_HOST);
if (!is_string($host) || $host === '') {
return false;
}
return faceai_is_local_host($host);
}
function faceai_default_frontend_url()
{
if (faceai_request_targets_local_frontend()) {
return 'http://localhost:3001';
}
return 'https://ai.regalamiunsorriso.it';
}
function faceai_default_backend_internal_url()
{
if (faceai_is_local_host(faceai_request_host())) {
return 'http://localhost:3001';
}
return 'https://ai.regalamiunsorriso.it';
}
function faceai_config() function faceai_config()
{ {
static $config = null; static $config = null;
@ -15,10 +78,11 @@ function faceai_config()
} }
$config = array( $config = array(
'frontend_url' => rtrim(faceai_env('FACEAI_FRONTEND_URL', 'http://localhost:5173'), '/'), 'feature_enabled' => faceai_env_flag('FACEAI_FEATURE_ENABLED', false),
'backend_internal_url' => rtrim(faceai_env('FACEAI_BACKEND_INTERNAL_URL', 'http://localhost:3001'), '/'), 'frontend_url' => rtrim(faceai_env('FACEAI_FRONTEND_URL', faceai_default_frontend_url()), '/'),
'backend_internal_url' => rtrim(faceai_env('FACEAI_BACKEND_INTERNAL_URL', faceai_default_backend_internal_url()), '/'),
'shared_secret' => (string) faceai_env('FACEAI_SHARED_SECRET', 'change-me'), 'shared_secret' => (string) faceai_env('FACEAI_SHARED_SECRET', 'change-me'),
'allow_dev_handoff' => faceai_env('FACEAI_ALLOW_DEV_HANDOFF', '1') === '1', 'allow_dev_handoff' => faceai_env_flag('FACEAI_ALLOW_DEV_HANDOFF', true),
'identity_cookie' => (string) faceai_env('FACEAI_IDENTITY_COOKIE', 'rus_faceai_identity'), 'identity_cookie' => (string) faceai_env('FACEAI_IDENTITY_COOKIE', 'rus_faceai_identity'),
'return_forward_url' => rtrim((string) faceai_env('FACEAI_RETURN_FORWARD_URL', ''), '/') 'return_forward_url' => rtrim((string) faceai_env('FACEAI_RETURN_FORWARD_URL', ''), '/')
); );
@ -80,6 +144,22 @@ function faceai_build_url($baseUrl, array $params)
return $baseUrl . (strpos($baseUrl, '?') === false ? '?' : '&') . http_build_query($params); return $baseUrl . (strpos($baseUrl, '?') === false ? '?' : '&') . http_build_query($params);
} }
function faceai_redirect_with_error($returnUrl, $message, $title = 'Face ID non disponibile')
{
if (is_string($returnUrl) && trim($returnUrl) !== '') {
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Location: ' . faceai_build_url($returnUrl, array(
'faceaiError' => '1',
'faceaiErrorTitle' => $title,
'faceaiErrorMessage' => $message
)), true, 302);
exit;
}
faceai_render_message_page($title, $message, array(), 503);
}
function faceai_request_value($key, $default = '') function faceai_request_value($key, $default = '')
{ {
if (!isset($_GET[$key])) { if (!isset($_GET[$key])) {

View file

@ -11,6 +11,10 @@ try {
$lang = faceai_request_value('lang', 'it'); $lang = faceai_request_value('lang', 'it');
$returnUrl = faceai_request_value('returnUrl'); $returnUrl = faceai_request_value('returnUrl');
if (empty($config['feature_enabled'])) {
faceai_redirect_with_error($returnUrl, 'La ricerca Face ID non e ancora disponibile.');
}
if ($raceId === '' || $returnUrl === '') { if ($raceId === '' || $returnUrl === '') {
faceai_render_message_page( faceai_render_message_page(
'FaceAI handoff non disponibile', 'FaceAI handoff non disponibile',
@ -25,25 +29,11 @@ try {
$identity = faceai_resolve_identity($config); $identity = faceai_resolve_identity($config);
if ($identity === null) { if ($identity === null) {
faceai_render_message_page( faceai_redirect_with_error($returnUrl, 'Il servizio Face ID non e al momento disponibile. Riprova piu tardi.');
'FaceAI handoff in attesa del bridge legacy',
'Questo endpoint PHP non puo leggere la sessione Java esistente. Per funzionare in produzione deve ricevere una identita firmata dal layer legacy o dal reverse proxy.',
array(
'Opzione consigliata: cookie firmato ' . $config['identity_cookie'] . ' con payload type=legacy-identity.',
'Per test locale e possibile passare devUserId, devDisplayName, devEmail e devMembershipStatus se FACEAI_ALLOW_DEV_HANDOFF=1.',
'Esempio locale: faceai_handoff.php?raceId=101&raceSlug=mezza-di-firenze&lang=it&returnUrl=http%3A%2F%2Flocalhost%2Fold&devUserId=1&devDisplayName=Mario%20Rossi&devEmail=mario%40example.test&devMembershipStatus=active'
),
501
);
} }
if (($identity['membershipStatus'] ?? 'inactive') !== 'active') { if (($identity['membershipStatus'] ?? 'inactive') !== 'active') {
faceai_render_message_page( faceai_redirect_with_error($returnUrl, 'Il tuo account non e abilitato all uso di Face ID.');
'FaceAI non disponibile',
'L utente corrente non risulta abilitato all uso di FaceAI in base allo stato di membership.',
array('Stato attuale: ' . ($identity['membershipStatus'] ?? 'unknown')),
403
);
} }
$payload = array( $payload = array(
@ -72,5 +62,5 @@ try {
header('Location: ' . $targetUrl, true, 302); header('Location: ' . $targetUrl, true, 302);
exit; exit;
} catch (Throwable $error) { } catch (Throwable $error) {
faceai_render_message_page('Errore handoff FaceAI', $error->getMessage(), array(), 500); faceai_redirect_with_error(isset($returnUrl) ? $returnUrl : '', 'Il servizio Face ID non e al momento disponibile. Riprova piu tardi.');
} }

View file

@ -166,6 +166,7 @@ function faceai_sim_render_page(array $options)
<?php if ($showSimulatorBootstrap): ?> <?php if ($showSimulatorBootstrap): ?>
<script> <script>
window.faceAiSimulator = { window.faceAiSimulator = {
enabled: true,
handoffUrl: 'faceai_handoff.php', handoffUrl: 'faceai_handoff.php',
returnUrl: <?php echo json_encode($returnUrl); ?>, returnUrl: <?php echo json_encode($returnUrl); ?>,
devUserId: '1', devUserId: '1',

View file

@ -50,6 +50,13 @@
</jsp:useBean> </jsp:useBean>
<jsp:useBean id="user" class="it.acxent.pg.Users" type="it.acxent.pg.Users" scope="request" > <jsp:useBean id="user" class="it.acxent.pg.Users" type="it.acxent.pg.Users" scope="request" >
</jsp:useBean> </jsp:useBean>
<%
String faceAiFeatureEnabledValue = System.getenv("FACEAI_FEATURE_ENABLED");
if (faceAiFeatureEnabledValue == null) {
faceAiFeatureEnabledValue = System.getProperty("FACEAI_FEATURE_ENABLED", "0");
}
boolean faceAiFeatureEnabled = "1".equals(faceAiFeatureEnabledValue) || "true".equalsIgnoreCase(faceAiFeatureEnabledValue) || "yes".equalsIgnoreCase(faceAiFeatureEnabledValue) || "on".equalsIgnoreCase(faceAiFeatureEnabledValue);
%>
<!-- InstanceEndEditable --> <!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="doctitle" --> <!-- InstanceBeginEditable name="doctitle" -->
<title><acx:lang>Regalami Un Sorriso ETS - Gare</acx:lang><%=CR.getTipoGara().getDescrizione()%></title> <title><acx:lang>Regalami Un Sorriso ETS - Gare</acx:lang><%=CR.getTipoGara().getDescrizione()%></title>
@ -313,6 +320,11 @@
<!-- Footer --> <!-- Footer -->
<jsp:include page="_inc_footer.jsp" flush="true" /> <jsp:include page="_inc_footer.jsp" flush="true" />
<script>
window.faceAiConfig = window.faceAiConfig || {};
window.faceAiConfig.enabled = <%= faceAiFeatureEnabled ? "true" : "false" %>;
</script>
<script> <script>
$('#datepicker-sport').datepicker({ $('#datepicker-sport').datepicker({
language: "it" language: "it"

View file

@ -50,6 +50,13 @@
</jsp:useBean> </jsp:useBean>
<jsp:useBean id="user" class="it.acxent.pg.Users" type="it.acxent.pg.Users" scope="request" > <jsp:useBean id="user" class="it.acxent.pg.Users" type="it.acxent.pg.Users" scope="request" >
</jsp:useBean> </jsp:useBean>
<%
String faceAiFeatureEnabledValue = System.getenv("FACEAI_FEATURE_ENABLED");
if (faceAiFeatureEnabledValue == null) {
faceAiFeatureEnabledValue = System.getProperty("FACEAI_FEATURE_ENABLED", "0");
}
boolean faceAiFeatureEnabled = "1".equals(faceAiFeatureEnabledValue) || "true".equalsIgnoreCase(faceAiFeatureEnabledValue) || "yes".equalsIgnoreCase(faceAiFeatureEnabledValue) || "on".equalsIgnoreCase(faceAiFeatureEnabledValue);
%>
<!-- InstanceEndEditable --> <!-- InstanceEndEditable -->
<!-- InstanceBeginEditable name="doctitle" --> <!-- InstanceBeginEditable name="doctitle" -->
<title><acx:lang>Regalami Un Sorriso ETS - Gare</acx:lang><%=CR.getTipoGara().getDescrizione()%></title> <title><acx:lang>Regalami Un Sorriso ETS - Gare</acx:lang><%=CR.getTipoGara().getDescrizione()%></title>
@ -313,6 +320,11 @@
<!-- Footer --> <!-- Footer -->
<jsp:include page="_inc_footer.jsp" flush="true" /> <jsp:include page="_inc_footer.jsp" flush="true" />
<script>
window.faceAiConfig = window.faceAiConfig || {};
window.faceAiConfig.enabled = <%= faceAiFeatureEnabled ? "true" : "false" %>;
</script>
<script> <script>
$('#datepicker-sport').datepicker({ $('#datepicker-sport').datepicker({
language: "it" language: "it"