mirror of
https://github.com/bitbaum/datacat.git
synced 2026-12-04 06:28:38 +01:00
* chore(repo): drop ralph.sh residue, ignore the generated Prisma client at the root
ralph.sh was byte-identical to reparaturbonus-zh/ralph.sh ("Ralph Loop for
Revamp-Hirn") and PROMPT.md was its blank task template; nothing in CI, docs
or scripts referenced either.
backend/generated/ is produced by `prisma generate` (typecheck, build and
Dockerfile.backend all run it) and was already ignored by backend/.gitignore,
so it was never committed — but tools that only read the root ignore file
(the fleet jscpd sweep) counted its ~1,300 generated lines as duplicated
source and reported the repo at 4.4%. Listing it at the root too makes those
sweeps see what git sees.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(backend): log through one pino instance, lint console.log out
The backend had pino-http for requests and bare console.log everywhere else
(index.js, jobs/, services/websocket.js — 26 lines). lib/logger.js now owns
the pino-http middleware and exposes its logger, so application logs and
request logs share level, destination and redaction. pino stays an indirect
dependency: pnpm does not hoist pino-http's copy, and a second pino would be
a second place to configure.
The backend had no linter at all. eslint.config.mjs enables exactly one rule,
no-console (warn/error allowed), so this cannot drift back; the root `lint`
now runs both halves, which is what `verify` and CI call.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(ingest): one shared kit for the image/video/audio/database ingestion components and the /ingest pages
The four data-ingestion components each carried their own copy of the
upload state machine (idle → uploading → processing → complete/error), the
file picker + drag-drop + object-URL preview, the auth header, the response
reader, the drop zone, progress bar, error banner, result card and submit
button. The five /ingest/<kind> pages likewise repeated the page frame, the
"Recent …" panel with its loading/error/empty states, the status badge and
the detail panel, plus a private copy of formatFileSize/formatDate.
Now there is one of each:
- components/data-ingestion/shared.tsx — useIngestionUpload, useFilePreview,
authHeaders, readIngestionResponse and the shared markup pieces
- components/data-ingestion/icons.tsx — the inline SVG paths as data, one
OutlineIcon/SpinnerIcon component
- ingest/shared.tsx — IngestPage, RecentPanel, StatusBadge, DetailPanel and
the useRecentSources fetch
- lib/format.ts — formatFileSize/formatDuration/formatDate, with a test
Markup and copy are unchanged; the components render exactly what they did.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(forms): type the stored form structure once, drop the dead quick-field builder
`/api/v1/forms` returned `schema as any` and every consumer re-derived its
shape. `StoredFormStructure` / `FormListRow` in types/saved-form.ts are now
the one description of what the builder writes into the Json column, used by
the route, SavedFormsLibrary, ModernFormBuilderLayout and the builder page.
DynamicForm loses its unused `addQuickField` duplicate of FormFieldBuilder's
own field factory and an unused `handleCreateGroup` argument; the autosave
draft effect reads the current form through a ref instead of listing the
form as a dependency (which is what the exhaustive-deps warning was pointing
at — re-running it per keystroke would clobber the user's input).
SavedFormsLibrary wraps fetchForms in useCallback so the token effect is
honest about what it depends on; its `handleLoginSuccess` was never wired to
anything. Rendered output is unchanged.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
* refactor(frontend): fix every ESLint warning, gate lint at --max-warnings 0, ban console.log
The frontend lint config had downgraded no-unused-vars, no-explicit-any,
ban-ts-comment, exhaustive-deps, no-unescaped-entities and no-img-element to
"warn" ("temporarily, for build success") and `eslint .` ran with no
warning cap, so 152 warnings sat there unread. Every one is fixed at the
source rather than silenced:
- no-explicit-any: real types — jose's private `email` claim, the next-auth
Session/User augmentation (`session.user.id` is set by the session
callback), OpenAI.APIError for the vision route's status checks, typed
event/data shapes elsewhere. The ambient `declare module '@dnd-kit/*'`
stub is gone: `@dnd-kit/utilities` is now a declared dependency so its own
types load.
- no-unused-vars: unused imports/params/state dropped. Seven components and
one hook turned out to be rendered nowhere (BuilderToolbar,
FormBuilderQuickStart, FormCreationHub, ModernSidebarStore, MultiStepForm,
MultiStepFormBuilderStore, QuickActions, useApiRequest) — deleted, and the
README paragraph that described the *Store wrappers updated.
- exhaustive-deps: callbacks memoised so the dependency arrays are truthful.
- ban-ts-comment / no-unescaped-entities: the comments were covering typed
code; the entities are escaped.
- The 5 console.log calls in frontend/src (debug leftovers in components
and services) are removed; console.warn/error stay. `no-console` (allow
warn/error) is now an error so they cannot come back, with scripts/**
exempt because printing is their job. (Of the 82 console.log in the repo,
26 were the backend — routed through pino in the previous commit — and
the rest are operator scripts, which print by design.)
The downgrade block is gone, so upstream next/core-web-vitals defaults
apply, and `lint` runs with `--max-warnings 0`: a warning fails the gate.
152 → 0.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8
---------
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
295 lines
8.0 KiB
JavaScript
295 lines
8.0 KiB
JavaScript
const { logger } = require('../lib/logger');
|
|
const { Server } = require('socket.io');
|
|
const jwt = require('jsonwebtoken');
|
|
const prisma = require('../lib/prisma');
|
|
|
|
class WebSocketService {
|
|
constructor() {
|
|
this.io = null;
|
|
this.authenticatedSockets = new Map(); // socketId -> user
|
|
this.userSockets = new Map(); // userId -> Set of socketIds
|
|
}
|
|
|
|
initialize(server) {
|
|
this.io = new Server(server, {
|
|
cors: {
|
|
origin: process.env.FRONTEND_URL || 'http://localhost:3000',
|
|
methods: ['GET', 'POST'],
|
|
credentials: true,
|
|
},
|
|
transports: ['websocket', 'polling'],
|
|
});
|
|
|
|
this.setupEventHandlers();
|
|
logger.info('WebSocket service initialized');
|
|
}
|
|
|
|
setupEventHandlers() {
|
|
this.io.on('connection', (socket) => {
|
|
logger.info(`Socket connected: ${socket.id}`);
|
|
|
|
// Handle authentication
|
|
socket.on('authenticate', async (data) => {
|
|
try {
|
|
const { token } = data;
|
|
|
|
if (!token) {
|
|
socket.emit('auth-error', { message: 'No token provided' });
|
|
return;
|
|
}
|
|
|
|
// Verify JWT token
|
|
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
|
const user = await prisma.user.findUnique({
|
|
where: { id: decoded.userId },
|
|
select: {
|
|
id: true,
|
|
email: true,
|
|
name: true,
|
|
role: true,
|
|
organizationId: true,
|
|
isActive: true,
|
|
},
|
|
});
|
|
|
|
if (!user || !user.isActive) {
|
|
socket.emit('auth-error', { message: 'Invalid or inactive user' });
|
|
return;
|
|
}
|
|
|
|
// Store authenticated user
|
|
this.authenticatedSockets.set(socket.id, user);
|
|
|
|
if (!this.userSockets.has(user.id)) {
|
|
this.userSockets.set(user.id, new Set());
|
|
}
|
|
this.userSockets.get(user.id).add(socket.id);
|
|
|
|
// Join user-specific room
|
|
socket.join(`user:${user.id}`);
|
|
|
|
// Join organization room if applicable
|
|
if (user.organizationId) {
|
|
socket.join(`org:${user.organizationId}`);
|
|
}
|
|
|
|
socket.emit('authenticated', {
|
|
user: {
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
},
|
|
});
|
|
|
|
logger.info(`User ${user.email} authenticated on socket ${socket.id}`);
|
|
} catch (error) {
|
|
logger.error({ err: error }, 'Authentication error');
|
|
socket.emit('auth-error', { message: 'Authentication failed' });
|
|
}
|
|
});
|
|
|
|
// Handle form subscription
|
|
socket.on('subscribe-form', async (data) => {
|
|
const user = this.authenticatedSockets.get(socket.id);
|
|
if (!user) {
|
|
socket.emit('error', { message: 'Not authenticated' });
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const { formId } = data;
|
|
|
|
// Check if user has access to the form
|
|
const form = await prisma.form.findFirst({
|
|
where: {
|
|
id: formId,
|
|
OR: [{ userId: user.id }, { collaborators: { some: { userId: user.id } } }],
|
|
},
|
|
});
|
|
|
|
if (!form) {
|
|
socket.emit('error', { message: 'Form not found or access denied' });
|
|
return;
|
|
}
|
|
|
|
// Join form-specific room
|
|
socket.join(`form:${formId}`);
|
|
socket.emit('subscribed', { formId });
|
|
|
|
logger.info(`User ${user.email} subscribed to form ${formId}`);
|
|
} catch (error) {
|
|
logger.error({ err: error }, 'Form subscription error');
|
|
socket.emit('error', { message: 'Subscription failed' });
|
|
}
|
|
});
|
|
|
|
// Handle form unsubscription
|
|
socket.on('unsubscribe-form', (data) => {
|
|
const { formId } = data;
|
|
socket.leave(`form:${formId}`);
|
|
socket.emit('unsubscribed', { formId });
|
|
});
|
|
|
|
// Handle disconnection
|
|
socket.on('disconnect', () => {
|
|
const user = this.authenticatedSockets.get(socket.id);
|
|
if (user) {
|
|
// Remove socket from user's socket set
|
|
const userSocketSet = this.userSockets.get(user.id);
|
|
if (userSocketSet) {
|
|
userSocketSet.delete(socket.id);
|
|
if (userSocketSet.size === 0) {
|
|
this.userSockets.delete(user.id);
|
|
}
|
|
}
|
|
|
|
this.authenticatedSockets.delete(socket.id);
|
|
logger.info(`User ${user.email} disconnected from socket ${socket.id}`);
|
|
} else {
|
|
logger.info(`Unauthenticated socket disconnected: ${socket.id}`);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
// Send real-time notifications
|
|
notifyNewSubmission(formId, submission) {
|
|
if (this.io) {
|
|
this.io.to(`form:${formId}`).emit('new-submission', {
|
|
type: 'new-submission',
|
|
formId,
|
|
submission: {
|
|
id: submission.id,
|
|
submittedAt: submission.submittedAt,
|
|
status: submission.status,
|
|
source: submission.source,
|
|
},
|
|
timestamp: new Date(),
|
|
});
|
|
}
|
|
}
|
|
|
|
notifyAnalysisComplete(formId, submissionId, analysisResults) {
|
|
if (this.io) {
|
|
this.io.to(`form:${formId}`).emit('analysis-complete', {
|
|
type: 'analysis-complete',
|
|
formId,
|
|
submissionId,
|
|
analysisResults: analysisResults.map((result) => ({
|
|
id: result.id,
|
|
analysisType: result.analysisType,
|
|
confidence: result.confidence,
|
|
status: result.status,
|
|
})),
|
|
timestamp: new Date(),
|
|
});
|
|
}
|
|
}
|
|
|
|
notifyFormUpdate(formId, updateType, data) {
|
|
if (this.io) {
|
|
this.io.to(`form:${formId}`).emit('form-update', {
|
|
type: 'form-update',
|
|
formId,
|
|
updateType, // 'schema', 'settings', 'publish', etc.
|
|
data,
|
|
timestamp: new Date(),
|
|
});
|
|
}
|
|
}
|
|
|
|
notifyCollaboratorActivity(formId, userId, activity) {
|
|
if (this.io) {
|
|
this.io.to(`form:${formId}`).emit('collaborator-activity', {
|
|
type: 'collaborator-activity',
|
|
formId,
|
|
userId,
|
|
activity, // 'joined', 'editing', 'left', etc.
|
|
timestamp: new Date(),
|
|
});
|
|
}
|
|
}
|
|
|
|
// Send notifications to specific user
|
|
notifyUser(userId, notification) {
|
|
if (this.io) {
|
|
this.io.to(`user:${userId}`).emit('notification', {
|
|
...notification,
|
|
timestamp: new Date(),
|
|
});
|
|
}
|
|
}
|
|
|
|
// Send system-wide announcements (admin only)
|
|
broadcastAnnouncement(announcement, excludeUserId = null) {
|
|
if (this.io) {
|
|
const event = {
|
|
type: 'announcement',
|
|
...announcement,
|
|
timestamp: new Date(),
|
|
};
|
|
|
|
if (excludeUserId) {
|
|
// Send to all authenticated users except the excluded one
|
|
this.authenticatedSockets.forEach((user, socketId) => {
|
|
if (user.id !== excludeUserId) {
|
|
this.io.to(socketId).emit('announcement', event);
|
|
}
|
|
});
|
|
} else {
|
|
// Send to all authenticated users
|
|
this.io.emit('announcement', event);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Get online users for a form
|
|
getOnlineUsersForForm(formId) {
|
|
if (!this.io) return [];
|
|
|
|
const room = this.io.sockets.adapter.rooms.get(`form:${formId}`);
|
|
if (!room) return [];
|
|
|
|
const onlineUsers = [];
|
|
room.forEach((socketId) => {
|
|
const user = this.authenticatedSockets.get(socketId);
|
|
if (user) {
|
|
onlineUsers.push({
|
|
id: user.id,
|
|
name: user.name,
|
|
email: user.email,
|
|
});
|
|
}
|
|
});
|
|
|
|
return onlineUsers;
|
|
}
|
|
|
|
// Get connection statistics
|
|
getConnectionStats() {
|
|
if (!this.io) {
|
|
return {
|
|
totalConnections: 0,
|
|
authenticatedConnections: 0,
|
|
uniqueUsers: 0,
|
|
};
|
|
}
|
|
|
|
return {
|
|
totalConnections: this.io.sockets.sockets.size,
|
|
authenticatedConnections: this.authenticatedSockets.size,
|
|
uniqueUsers: this.userSockets.size,
|
|
};
|
|
}
|
|
|
|
// Health check
|
|
isHealthy() {
|
|
return this.io !== null && this.io.sockets.sockets.size >= 0;
|
|
}
|
|
}
|
|
|
|
// Create singleton instance
|
|
const webSocketService = new WebSocketService();
|
|
|
|
module.exports = webSocketService;
|