Commit pour resoudre le problème de single prediction
This commit is contained in:
parent
53850a4462
commit
cb97439d1a
@ -3,6 +3,7 @@ import { AuthRequest } from '../middleware/auth';
|
||||
export declare function getState(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getCandles(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function placeBet(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getBetOutcome(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getMyBets(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function getAutoSettings(req: AuthRequest, res: Response): Promise<void>;
|
||||
export declare function updateAutoSettings(req: AuthRequest, res: Response): Promise<void>;
|
||||
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"candlePredictController.d.ts","sourceRoot":"","sources":["../../src/controllers/candlePredictController.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAoBjD,wBAAsB,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAsB7E;AAID,wBAAsB,UAAU,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwC/E;AAID,wBAAsB,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwD7E;AAID,wBAAsB,SAAS,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwC9E;AAID,wBAAsB,eAAe,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAwBpF;AAID,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAA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E,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgCxF;AAID,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CA0BxF;AAID,wBAAsB,aAAa,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAkFlF;AAID,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAgBzF;AAID,wBAAsB,sBAAsB,CAAC,GAAG,EAAE,WAAW,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAoB3F"}
|
||||
@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.getState = getState;
|
||||
exports.getCandles = getCandles;
|
||||
exports.placeBet = placeBet;
|
||||
exports.getBetOutcome = getBetOutcome;
|
||||
exports.getMyBets = getMyBets;
|
||||
exports.getAutoSettings = getAutoSettings;
|
||||
exports.updateAutoSettings = updateAutoSettings;
|
||||
@ -115,6 +116,42 @@ async function placeBet(req, res) {
|
||||
res.status(400).json({ error: msg });
|
||||
}
|
||||
}
|
||||
async function getBetOutcome(req, res) {
|
||||
try {
|
||||
if (!req.user?.userId) {
|
||||
res.status(401).json({ error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
const idempotencyKey = String(req.params.idempotencyKey ?? '').trim();
|
||||
if (!idempotencyKey) {
|
||||
res.status(400).json({ error: 'idempotencyKey is required' });
|
||||
return;
|
||||
}
|
||||
const record = await candlePredictService.getBetIdempotency(idempotencyKey);
|
||||
if (!record) {
|
||||
res.status(404).json({ error: 'Bet outcome not found' });
|
||||
return;
|
||||
}
|
||||
if (record.status === 'accepted') {
|
||||
const betUserId = String(record.bet.user_id ?? record.bet.userId ?? '').trim();
|
||||
if (betUserId && betUserId !== req.user.userId) {
|
||||
res.status(403).json({ error: 'Forbidden' });
|
||||
return;
|
||||
}
|
||||
res.json({ status: 'accepted', bet: record.bet });
|
||||
return;
|
||||
}
|
||||
if (record.status === 'rejected') {
|
||||
res.json({ status: 'rejected', error: record.error });
|
||||
return;
|
||||
}
|
||||
res.json({ status: 'processing' });
|
||||
}
|
||||
catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Failed to load bet outcome';
|
||||
res.status(500).json({ error: msg });
|
||||
}
|
||||
}
|
||||
async function getMyBets(req, res) {
|
||||
try {
|
||||
if (!req.user?.userId) {
|
||||
|
||||
File diff suppressed because one or more lines are too long
2
backend/dist/db/connection.d.ts.map
vendored
2
backend/dist/db/connection.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/db/connection.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAIH,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,IAAI,CAAC;AAkDtC,QAAA,MAAM,IAAI,MAIT,CAAC;AAUF,sGAAsG;AACtG,wBAAsB,sBAAsB,CAAC,MAAM,EAAE;IACnD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/D,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhB;AAED,kFAAkF;AAClF,wBAAsB,0BAA0B,CAAC,MAAM,EAAE;IACvD,KAAK,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC/D,GAAG,OAAO,CAAC,IAAI,CAAC,CAGhB;AAED;;;GAGG;AACH,wBAAsB,KAAK,CAAC,CAAC,GAAG,OAAO,EACrC,IAAI,EAAE,MAAM,EACZ,MAAM,CAAC,EAAE,OAAO,EAAE,EAClB,OAAO,CAAC,EAAE;IAAE,kBAAkB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;AAED,6DAA6D;AAC7D,eAAe,IAAI,CAAC"}
|
||||
47
backend/dist/db/connection.js
vendored
47
backend/dist/db/connection.js
vendored
@ -55,28 +55,61 @@ const repoRoot = path.resolve(__dirname, '..', '..', '..');
|
||||
[path.join(backendRoot, '.env'), path.join(repoRoot, '.env')].forEach((envPath) => {
|
||||
dotenv_1.default.config({ path: envPath });
|
||||
});
|
||||
/** Inside Docker, localhost is the container — rewrite to reach Postgres on the host. */
|
||||
function resolveDatabaseUrl(raw) {
|
||||
const trimmed = raw.trim();
|
||||
try {
|
||||
const parsed = new URL(trimmed);
|
||||
const isLocalHost = parsed.hostname === 'localhost' ||
|
||||
parsed.hostname === '127.0.0.1' ||
|
||||
parsed.hostname === '::1' ||
|
||||
parsed.hostname === '[::1]';
|
||||
if (isLocalHost && fs.existsSync('/.dockerenv')) {
|
||||
const dockerHost = process.env.DATABASE_DOCKER_HOST || 'host.docker.internal';
|
||||
console.warn(`[db] DATABASE_URL host "${parsed.hostname}" does not work inside Docker; using "${dockerHost}". ` +
|
||||
'Set DATABASE_URL with host.docker.internal in .env to silence this.');
|
||||
parsed.hostname = dockerHost;
|
||||
return parsed.toString();
|
||||
}
|
||||
}
|
||||
catch {
|
||||
// keep raw URL for connectionString fallback
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
/** Resolves DB password: explicit env vars beat URL (avoids encoding issues in DATABASE_URL). */
|
||||
function resolveDatabasePassword(parsed) {
|
||||
const fromUrl = parsed.password ? decodeURIComponent(parsed.password) : '';
|
||||
for (const candidate of [
|
||||
process.env.DATABASE_PASSWORD,
|
||||
process.env.POSTGRES_PASSWORD,
|
||||
fromUrl,
|
||||
]) {
|
||||
if (typeof candidate === 'string' && candidate !== '') {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
/**
|
||||
* Builds pg Pool configuration from DATABASE_URL, preferring DATABASE_PASSWORD when set.
|
||||
* @returns Parsed host/port config or a raw connectionString fallback
|
||||
* @throws When DATABASE_URL is missing or empty
|
||||
*/
|
||||
function getPoolConfig() {
|
||||
const url = process.env.DATABASE_URL;
|
||||
const url = resolveDatabaseUrl(process.env.DATABASE_URL ?? '');
|
||||
if (!url || url.trim() === '') {
|
||||
throw new Error('DATABASE_URL is not set. Create a .env file with DATABASE_URL=postgresql://user:password@localhost:5432/crypto_wallet');
|
||||
}
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
// Use DATABASE_PASSWORD if set (avoids URL-encoding issues and empty password in URL)
|
||||
const passwordFromEnv = process.env.DATABASE_PASSWORD;
|
||||
const passwordFromUrl = parsed.password ? decodeURIComponent(parsed.password) : '';
|
||||
const password = typeof passwordFromEnv === 'string' && passwordFromEnv !== '' ? passwordFromEnv : passwordFromUrl;
|
||||
const password = resolveDatabasePassword(parsed);
|
||||
return {
|
||||
host: parsed.hostname,
|
||||
port: parsed.port ? parseInt(parsed.port, 10) : 5432,
|
||||
database: parsed.pathname?.slice(1) || 'crypto_wallet',
|
||||
user: parsed.username || process.env.USER || 'postgres',
|
||||
password: typeof password === 'string' ? password : '',
|
||||
user: decodeURIComponent(parsed.username || '') || process.env.POSTGRES_USER || 'postgres',
|
||||
password,
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 10000,
|
||||
|
||||
2
backend/dist/db/connection.js.map
vendored
2
backend/dist/db/connection.js.map
vendored
File diff suppressed because one or more lines are too long
10
backend/dist/db/migrate.js
vendored
10
backend/dist/db/migrate.js
vendored
@ -16,6 +16,16 @@ async function migrate() {
|
||||
process.exit(0);
|
||||
}
|
||||
catch (err) {
|
||||
const code = err && typeof err === 'object' && 'code' in err ? String(err.code) : '';
|
||||
if (code === 'ECONNREFUSED') {
|
||||
console.error('Migration failed: cannot reach PostgreSQL (ECONNREFUSED).\n' +
|
||||
' From Docker containers use host.docker.internal in DATABASE_URL, not localhost.\n' +
|
||||
' Example: DATABASE_URL=postgresql://postgres:PASSWORD@host.docker.internal:5432/games_platform_db');
|
||||
}
|
||||
const msg = err && typeof err === 'object' && 'message' in err ? String(err.message) : '';
|
||||
if (msg.includes('client password must be a string') || msg.includes('password authentication failed')) {
|
||||
console.error(' Set POSTGRES_PASSWORD (and optionally DATABASE_PASSWORD) in .env — they must be passed into Docker containers.');
|
||||
}
|
||||
console.error('Migration failed:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
2
backend/dist/db/migrate.js.map
vendored
2
backend/dist/db/migrate.js.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/db/migrate.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,yBAAuB;AACvB,6CAA6C;AAE7C;;GAEG;AACH,KAAK,UAAU,OAAO;IACpB,IAAI,CAAC;QACH,MAAM,IAAA,0BAAa,GAAE,CAAC;QACtB,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,OAAO,EAAE,CAAC"}
|
||||
{"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/db/migrate.ts"],"names":[],"mappings":";AAAA;;;GAGG;;AAEH,yBAAuB;AACvB,6CAA6C;AAE7C;;GAEG;AACH,KAAK,UAAU,OAAO;IACpB,IAAI,CAAC;QACH,MAAM,IAAA,0BAAa,GAAE,CAAC;QACtB,OAAO,CAAC,GAAG,CAAC,oCAAoC,CAAC,CAAC;QAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,GAAG,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAE,GAAyB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5G,IAAI,IAAI,KAAK,cAAc,EAAE,CAAC;YAC5B,OAAO,CAAC,KAAK,CACX,6DAA6D;gBAC3D,qFAAqF;gBACrF,oGAAoG,CACvG,CAAC;QACJ,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,SAAS,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAE,GAA4B,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;QACpH,IAAI,GAAG,CAAC,QAAQ,CAAC,kCAAkC,CAAC,IAAI,GAAG,CAAC,QAAQ,CAAC,gCAAgC,CAAC,EAAE,CAAC;YACvG,OAAO,CAAC,KAAK,CACX,kHAAkH,CACnH,CAAC;QACJ,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAED,OAAO,EAAE,CAAC"}
|
||||
2
backend/dist/routes/index.d.ts.map
vendored
2
backend/dist/routes/index.d.ts.map
vendored
@ -1 +1 @@
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmCH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAoOxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/routes/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAmCH,QAAA,MAAM,MAAM,4CAAW,CAAC;AAqOxB,oEAAoE;AACpE,eAAe,MAAM,CAAC"}
|
||||
1
backend/dist/routes/index.js
vendored
1
backend/dist/routes/index.js
vendored
@ -128,6 +128,7 @@ router.get('/games', gameController.listGames);
|
||||
router.get('/games/candle-predict/state', candlePredictController.getState);
|
||||
router.get('/games/candle-predict/candles', candlePredictController.getCandles);
|
||||
router.post('/games/candle-predict/bets', candlePredictController.placeBet);
|
||||
router.get('/games/candle-predict/bets/outcome/:idempotencyKey', candlePredictController.getBetOutcome);
|
||||
router.post('/games/candle-predict/bets/multi', candlePredictController.placeMultiBet);
|
||||
router.get('/games/candle-predict/bets/me', candlePredictController.getMyBets);
|
||||
router.get('/games/candle-predict/auto', candlePredictController.getAutoSettings);
|
||||
|
||||
2
backend/dist/routes/index.js.map
vendored
2
backend/dist/routes/index.js.map
vendored
File diff suppressed because one or more lines are too long
@ -24,4 +24,5 @@ export declare const listAdminMultiLevels: typeof domain.listAdminMultiLevels;
|
||||
export declare const updateAdminMultiLevels: typeof domain.updateAdminMultiLevels;
|
||||
export declare const placeMultiCandleBet: typeof domain.placeMultiCandleBet;
|
||||
export declare const startCandlePredictEngine: typeof domain.startCandlePredictEngine;
|
||||
export { getBetIdempotency, type BetIdempotencyRecord } from '../realtime/streams/betQueue';
|
||||
//# sourceMappingURL=candlePredictService.d.ts.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"candlePredictService.d.ts","sourceRoot":"","sources":["../../src/services/candlePredictService.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,OAAO,KAAK,MAAM,MAAM,gCAAgC,CAAC;AAEzD,MAAM,MAAM,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,CAAC;AAEvD,eAAO,MAAM,eAAe,+BAAyB,CAAC;AACtD,eAAO,MAAM,iBAAiB,iCAA2B,CAAC;AAC1D,eAAO,MAAM,kBAAkB,kCAA4B,CAAC;AAC5D,eAAO,MAAM,mBAAmB,mCAA6B,CAAC;AAC9D,eAAO,MAAM,mBAAmB,mCAA6B,CAAC;AAC9D,eAAO,MAAM,mBAAmB,mCAA6B,CAAC;AAC9D,eAAO,MAAM,YAAY,4BAAsB,CAAC;AAChD,eAAO,MAAM,cAAc,8BAAwB,C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8BAAwB,CAAC;AACpD,eAAO,MAAM,qBAAqB,qCAA+B,CAAC;AAClE,eAAO,MAAM,uBAAuB,uCAAiC,CAAC;AACtE,eAAO,MAAM,QAAQ,wBAAkB,CAAC;AACxC,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,cAAc,CAAC;AACnD,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC;AACrD,eAAO,MAAM,oBAAoB,oCAA8B,CAAC;AAChE,eAAO,MAAM,aAAa,6BAAuB,CAAC;AAClD,eAAO,MAAM,gBAAgB,gCAA0B,CAAC;AACxD,eAAO,MAAM,eAAe,+BAAyB,CAAC;AACtD,eAAO,MAAM,oBAAoB,oCAA8B,CAAC;AAChE,eAAO,MAAM,sBAAsB,sCAAgC,CAAC;AACpE,eAAO,MAAM,mBAAmB,mCAA6B,CAAC;AAC9D,eAAO,MAAM,wBAAwB,wCAAkC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,KAAK,oBAAoB,EAAE,MAAM,8BAA8B,CAAC"}
|
||||
@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
|
||||
};
|
||||
})();
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.startCandlePredictEngine = exports.placeMultiCandleBet = exports.updateAdminMultiLevels = exports.listAdminMultiLevels = exports.getAutoSettings = exports.saveAutoSettings = exports.getRecentBets = exports.getRecentPredictions = exports.placeBet = exports.executePlaceBetInternal = exports.processAutoBetForUser = exports.tickGameEngine = exports.getCandles = exports.getCandlesPage = exports.getGameState = exports.deleteAdminInterval = exports.updateAdminInterval = exports.createAdminInterval = exports.listAdminIntervals = exports.updateAdminConfig = exports.getPublicConfig = void 0;
|
||||
exports.getBetIdempotency = exports.startCandlePredictEngine = exports.placeMultiCandleBet = exports.updateAdminMultiLevels = exports.listAdminMultiLevels = exports.getAutoSettings = exports.saveAutoSettings = exports.getRecentBets = exports.getRecentPredictions = exports.placeBet = exports.executePlaceBetInternal = exports.processAutoBetForUser = exports.tickGameEngine = exports.getCandles = exports.getCandlesPage = exports.getGameState = exports.deleteAdminInterval = exports.updateAdminInterval = exports.createAdminInterval = exports.listAdminIntervals = exports.updateAdminConfig = exports.getPublicConfig = void 0;
|
||||
/** Backward-compatible facade — direct bindings so tests can mock methods. */
|
||||
const domain = __importStar(require("../domain/candle-predict/index"));
|
||||
exports.getPublicConfig = domain.getPublicConfig;
|
||||
@ -57,4 +57,6 @@ exports.listAdminMultiLevels = domain.listAdminMultiLevels;
|
||||
exports.updateAdminMultiLevels = domain.updateAdminMultiLevels;
|
||||
exports.placeMultiCandleBet = domain.placeMultiCandleBet;
|
||||
exports.startCandlePredictEngine = domain.startCandlePredictEngine;
|
||||
var betQueue_1 = require("../realtime/streams/betQueue");
|
||||
Object.defineProperty(exports, "getBetIdempotency", { enumerable: true, get: function () { return betQueue_1.getBetIdempotency; } });
|
||||
//# sourceMappingURL=candlePredictService.js.map
|
||||
@ -1 +1 @@
|
||||
{"version":3,"file":"candlePredictService.js","sourceRoot":"","sources":["../../src/services/candlePredictService.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8EAA8E;AAC9E,uEAAyD;AAI5C,QAAA,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC;AACzC,QAAA,iBAAiB,GAAG,MAAM,CAAC,iBAAiB,CAAC;AAC7C,QAAA,kBAAkB,GAAG,MAAM,CAAC,kBAAkB,CAAC;AAC/C,QAAA,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC;AACjD,QAAA,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC;AACjD,QAAA,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC;AACjD,QAAA,YAAY,GAAG,MAAM,CAAC,YAAY,CAAC;AACnC,QAAA,cAAc,GAAG,MAAM,CAAC,cAAc,CAAC;AACvC,QAAA,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;AAC/B,QAAA,cAAc,GA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,GAAG,MAAM,CAAC,cAAc,CAAC;AACvC,QAAA,qBAAqB,GAAG,MAAM,CAAC,qBAAqB,CAAC;AACrD,QAAA,uBAAuB,GAAG,MAAM,CAAC,uBAAuB,CAAC;AACzD,QAAA,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;AAG3B,QAAA,oBAAoB,GAAG,MAAM,CAAC,oBAAoB,CAAC;AACnD,QAAA,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;AACrC,QAAA,gBAAgB,GAAG,MAAM,CAAC,gBAAgB,CAAC;AAC3C,QAAA,eAAe,GAAG,MAAM,CAAC,eAAe,CAAC;AACzC,QAAA,oBAAoB,GAAG,MAAM,CAAC,oBAAoB,CAAC;AACnD,QAAA,sBAAsB,GAAG,MAAM,CAAC,sBAAsB,CAAC;AACvD,QAAA,mBAAmB,GAAG,MAAM,CAAC,mBAAmB,CAAC;AACjD,QAAA,wBAAwB,GAAG,MAAM,CAAC,wBAAwB,CAAC;AACxE,yDAA4F;AAAnF,6GAAA,iBAAiB,OAAA"}
|
||||
@ -150,6 +150,47 @@ export async function placeBet(req: AuthRequest, res: Response): Promise<void> {
|
||||
|
||||
|
||||
|
||||
export async function getBetOutcome(req: AuthRequest, res: Response): Promise<void> {
|
||||
try {
|
||||
if (!req.user?.userId) {
|
||||
res.status(401).json({ error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
const idempotencyKey = String(req.params.idempotencyKey ?? '').trim();
|
||||
if (!idempotencyKey) {
|
||||
res.status(400).json({ error: 'idempotencyKey is required' });
|
||||
return;
|
||||
}
|
||||
|
||||
const record = await candlePredictService.getBetIdempotency(idempotencyKey);
|
||||
if (!record) {
|
||||
res.status(404).json({ error: 'Bet outcome not found' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (record.status === 'accepted') {
|
||||
const betUserId = String(record.bet.user_id ?? record.bet.userId ?? '').trim();
|
||||
if (betUserId && betUserId !== req.user.userId) {
|
||||
res.status(403).json({ error: 'Forbidden' });
|
||||
return;
|
||||
}
|
||||
res.json({ status: 'accepted', bet: record.bet });
|
||||
return;
|
||||
}
|
||||
|
||||
if (record.status === 'rejected') {
|
||||
res.json({ status: 'rejected', error: record.error });
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ status: 'processing' });
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : 'Failed to load bet outcome';
|
||||
res.status(500).json({ error: msg });
|
||||
}
|
||||
}
|
||||
|
||||
export async function getMyBets(req: AuthRequest, res: Response): Promise<void> {
|
||||
|
||||
try {
|
||||
|
||||
@ -123,6 +123,7 @@ router.get('/games', gameController.listGames);
|
||||
router.get('/games/candle-predict/state', candlePredictController.getState);
|
||||
router.get('/games/candle-predict/candles', candlePredictController.getCandles);
|
||||
router.post('/games/candle-predict/bets', candlePredictController.placeBet);
|
||||
router.get('/games/candle-predict/bets/outcome/:idempotencyKey', candlePredictController.getBetOutcome);
|
||||
router.post('/games/candle-predict/bets/multi', candlePredictController.placeMultiBet);
|
||||
router.get('/games/candle-predict/bets/me', candlePredictController.getMyBets);
|
||||
router.get('/games/candle-predict/auto', candlePredictController.getAutoSettings);
|
||||
|
||||
@ -26,3 +26,4 @@ export const listAdminMultiLevels = domain.listAdminMultiLevels;
|
||||
export const updateAdminMultiLevels = domain.updateAdminMultiLevels;
|
||||
export const placeMultiCandleBet = domain.placeMultiCandleBet;
|
||||
export const startCandlePredictEngine = domain.startCandlePredictEngine;
|
||||
export { getBetIdempotency, type BetIdempotencyRecord } from '../realtime/streams/betQueue';
|
||||
|
||||
@ -194,6 +194,18 @@ services:
|
||||
WORKER_ID: ${WORKER_ID:-worker-1}
|
||||
ENGINE_ENABLED: "false"
|
||||
command: ["node", "dist/apps/worker-bets.js"]
|
||||
healthcheck:
|
||||
test:
|
||||
[
|
||||
"CMD",
|
||||
"node",
|
||||
"-e",
|
||||
"const Redis=require('ioredis');const r=new Redis(process.env.REDIS_URL||'redis://redis:6379');r.ping().then(()=>process.exit(0)).catch(()=>process.exit(1)).finally(()=>r.quit());",
|
||||
]
|
||||
interval: 15s
|
||||
timeout: 5s
|
||||
retries: 3
|
||||
start_period: 20s
|
||||
|
||||
prediqo-web:
|
||||
build:
|
||||
|
||||
@ -431,6 +431,41 @@ Vérifiez la variable dans `.env` racine et redémarrez l’API :
|
||||
docker compose restart backend
|
||||
```
|
||||
|
||||
### Prédiction single-candle échoue (auto / multi OK)
|
||||
|
||||
Le pari manuel **single** passe par une file Redis (`BET_ASYNC=true`) traitée par **`backend-worker-bets`**, puis une confirmation WebSocket. L’auto et le multi contournent ce flux (exécution directe ou synchrone).
|
||||
|
||||
**Vérifications sur le VPS :**
|
||||
|
||||
```bash
|
||||
sudo docker compose ps backend-worker-bets backend-ws redis
|
||||
sudo docker compose logs backend-worker-bets --tail 80
|
||||
sudo docker compose logs backend-ws --tail 40
|
||||
```
|
||||
|
||||
Le conteneur `crypto_wallet_worker_bets` doit être **Up** et les logs doivent afficher `[worker-bets] Consumer worker-1 ready`.
|
||||
|
||||
**Test rapide** — désactiver temporairement la file async (pari synchrone comme le multi) :
|
||||
|
||||
```bash
|
||||
# Dans .env racine :
|
||||
BET_ASYNC=false
|
||||
sudo docker compose up -d --build backend
|
||||
```
|
||||
|
||||
Si le single fonctionne avec `BET_ASYNC=false`, le problème vient du worker ou du WebSocket.
|
||||
|
||||
**WebSocket** — le frontend doit être buildé avec la bonne URL (rebuild obligatoire après changement) :
|
||||
|
||||
```env
|
||||
VITE_WS_URL=ws://prediqo.redirectme.net:9080/ws/v1/games/candle-predict
|
||||
VITE_WS_ENABLED=true
|
||||
```
|
||||
|
||||
Puis : `sudo npm run phase-b:up` (rebuild `prediqo-web`).
|
||||
|
||||
**Depuis la version récente**, le frontend interroge aussi l’API `GET /api/v1/games/candle-predict/bets/outcome/:idempotencyKey` en secours si le WebSocket ne confirme pas le pari à temps.
|
||||
|
||||
---
|
||||
|
||||
## 11. Migration vers un VPS dédié (futur)
|
||||
|
||||
@ -39,6 +39,7 @@ import {
|
||||
useCandlePredictState,
|
||||
usePlaceCandleBet,
|
||||
usePlaceMultiCandleBet,
|
||||
pollCandleBetOutcome,
|
||||
} from './hooks/useCandlePredict';
|
||||
import { usePaginatedCandleChart } from './hooks/usePaginatedCandleChart';
|
||||
import type { CandleDirection, StakeAccountKind } from './types';
|
||||
@ -48,7 +49,6 @@ import {
|
||||
createBetOutcomeWait,
|
||||
isBetOutcomeTimeoutMessage,
|
||||
} from './ws/betOutcomeBus';
|
||||
import { isWsEnabled } from './ws/protocol';
|
||||
import { useAuth } from '../../shared/auth/AuthContext';
|
||||
|
||||
const BALANCES_VISIBLE_STORAGE_KEY = 'prediqo-candle-balances-visible';
|
||||
@ -413,12 +413,15 @@ export function CandlePredictPage() {
|
||||
|
||||
if (gen !== submitGenRef.current) return;
|
||||
|
||||
if (result.status === 'queued' && isWsEnabled()) {
|
||||
outcomeWait = createBetOutcomeWait(result.idempotencyKey);
|
||||
if (result.status === 'queued') {
|
||||
outcomeWait = createBetOutcomeWait(result.idempotencyKey, {
|
||||
pollBetOutcome: () => pollCandleBetOutcome(result.idempotencyKey),
|
||||
});
|
||||
const outcome = await outcomeWait.promise;
|
||||
if (gen !== submitGenRef.current || outcome.status === 'cancelled') return;
|
||||
if (gen !== submitGenRef.current) return;
|
||||
if ('status' in outcome && outcome.status === 'cancelled') return;
|
||||
|
||||
if (!outcome.ok) {
|
||||
if ('ok' in outcome && !outcome.ok) {
|
||||
if (isBetOutcomeTimeoutMessage(outcome.error)) {
|
||||
const latest = await stateQ.refetch();
|
||||
const placedForRound =
|
||||
|
||||
@ -267,7 +267,6 @@ function DirectionCell({ direction }: { direction: CandlePredictPrediction['dire
|
||||
|
||||
function MultiSequenceRow({ prediction }: { prediction: CandlePredictPrediction }) {
|
||||
const sequence = prediction.sequenceDirections ?? [];
|
||||
const total = sequence.length || multiCandleCount(prediction);
|
||||
const step = prediction.sequenceStep ?? 0;
|
||||
|
||||
if (!sequence.length) {
|
||||
|
||||
@ -3,6 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { api } from '../../../shared/services/api';
|
||||
import { CANDLE_PREDICT_SLUG, gameApiPath } from '../../games/gameApi';
|
||||
import { isWsEnabled } from '../ws/protocol';
|
||||
import type { BetOutcomeResult } from '../ws/betOutcomeBus';
|
||||
import { useGameSocket } from './useGameSocket';
|
||||
|
||||
import type {
|
||||
@ -167,6 +168,31 @@ export type PlaceCandleBetResult =
|
||||
| { status: 'accepted'; bet: unknown }
|
||||
| { status: 'queued'; idempotencyKey: string };
|
||||
|
||||
type BetOutcomeApiResponse =
|
||||
| { status: 'accepted'; bet: Record<string, unknown> }
|
||||
| { status: 'rejected'; error: string }
|
||||
| { status: 'processing' };
|
||||
|
||||
/** Polls Redis idempotency state when async bets are processed outside WebSocket. */
|
||||
export async function pollCandleBetOutcome(
|
||||
idempotencyKey: string
|
||||
): Promise<BetOutcomeResult | null> {
|
||||
try {
|
||||
const res = await api.get<BetOutcomeApiResponse>(
|
||||
gameApiPath(CANDLE_PREDICT_SLUG, 'bets', 'outcome', idempotencyKey)
|
||||
);
|
||||
if (res.data.status === 'accepted') return { ok: true };
|
||||
if (res.data.status === 'rejected') {
|
||||
return { ok: false, error: res.data.error || 'Bet rejected' };
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
const status = (e as { response?: { status?: number } })?.response?.status;
|
||||
if (status === 404) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export function usePlaceCandleBet() {
|
||||
const qc = useQueryClient();
|
||||
return useMutation({
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
|
||||
import { useAuth } from '../../../shared/auth/AuthContext';
|
||||
import type { CandlePredictPrediction, GameState, MultiCandlePrediction } from '../types';
|
||||
import { emitBetOutcome } from '../ws/betOutcomeBus';
|
||||
import { gameSocketClient } from '../ws/GameSocketClient';
|
||||
@ -65,13 +66,17 @@ function syncAfterSettlement(qc: ReturnType<typeof useQueryClient>, key: readonl
|
||||
/** Keeps React Query cache in sync with WebSocket round updates. */
|
||||
export function useGameSocket(intervalMinutes?: number): { enabled: boolean; connected: boolean } {
|
||||
const qc = useQueryClient();
|
||||
const { auth } = useAuth();
|
||||
const connectedRef = useRef(false);
|
||||
const enabled = isWsEnabled();
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || intervalMinutes == null) return undefined;
|
||||
if (!enabled) return undefined;
|
||||
gameSocketClient.reconnect();
|
||||
}, [enabled, auth.accessToken]);
|
||||
|
||||
gameSocketClient.connect();
|
||||
useEffect(() => {
|
||||
if (!enabled || intervalMinutes == null) return undefined;
|
||||
|
||||
const key = ['candle-predict-state', intervalMinutes] as const;
|
||||
|
||||
|
||||
@ -13,15 +13,32 @@ export class GameSocketClient {
|
||||
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
||||
private subscribedInterval: number | null = null;
|
||||
private closedByUser = false;
|
||||
private lastConnectUrl: string | null = null;
|
||||
|
||||
private static readonly HEARTBEAT_MS = 30_000;
|
||||
|
||||
connect(): void {
|
||||
this.closedByUser = false;
|
||||
connect(force = false): void {
|
||||
const { accessToken } = readAuth();
|
||||
const base = resolveWsBaseUrl();
|
||||
const url = accessToken ? `${base}?token=${encodeURIComponent(accessToken)}` : base;
|
||||
|
||||
if (
|
||||
!force &&
|
||||
this.socket &&
|
||||
(this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) &&
|
||||
this.lastConnectUrl === url
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closedByUser = false;
|
||||
this.lastConnectUrl = url;
|
||||
if (this.socket) {
|
||||
this.socket.onclose = null;
|
||||
this.socket.close();
|
||||
this.socket = null;
|
||||
}
|
||||
|
||||
this.socket = new WebSocket(url);
|
||||
|
||||
this.socket.onopen = () => {
|
||||
@ -47,6 +64,10 @@ export class GameSocketClient {
|
||||
};
|
||||
}
|
||||
|
||||
reconnect(): void {
|
||||
this.connect(true);
|
||||
}
|
||||
|
||||
disconnect(): void {
|
||||
this.closedByUser = true;
|
||||
this.stopHeartbeat();
|
||||
|
||||
@ -59,10 +59,22 @@ export function cancelAllBetOutcomeWaits(): void {
|
||||
pendingCancels.clear();
|
||||
}
|
||||
|
||||
export type BetOutcomeWaitOptions = {
|
||||
timeoutMs?: number;
|
||||
/** HTTP fallback when WebSocket confirmation is delayed or unavailable. */
|
||||
pollBetOutcome?: () => Promise<BetOutcomeResult | null>;
|
||||
pollIntervalMs?: number;
|
||||
};
|
||||
|
||||
export function createBetOutcomeWait(
|
||||
idempotencyKey: string,
|
||||
timeoutMs = 12_000
|
||||
options: BetOutcomeWaitOptions | number = {}
|
||||
): { promise: Promise<BetOutcomeWaitResult>; cancel: () => void } {
|
||||
const opts: BetOutcomeWaitOptions =
|
||||
typeof options === 'number' ? { timeoutMs: options } : options;
|
||||
const timeoutMs = opts.timeoutMs ?? 12_000;
|
||||
const pollIntervalMs = opts.pollIntervalMs ?? 500;
|
||||
|
||||
const cached = readCachedOutcome(idempotencyKey);
|
||||
if (cached) {
|
||||
return { promise: Promise.resolve(cached), cancel: () => undefined };
|
||||
@ -70,6 +82,7 @@ export function createBetOutcomeWait(
|
||||
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pollTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let off: (() => void) | undefined;
|
||||
let resolveWait: (result: BetOutcomeWaitResult) => void;
|
||||
|
||||
@ -77,6 +90,7 @@ export function createBetOutcomeWait(
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
if (pollTimer) clearInterval(pollTimer);
|
||||
off?.();
|
||||
pendingCancels.delete(idempotencyKey);
|
||||
resolveWait(result);
|
||||
@ -99,6 +113,22 @@ export function createBetOutcomeWait(
|
||||
}
|
||||
});
|
||||
|
||||
if (opts.pollBetOutcome) {
|
||||
const poll = async () => {
|
||||
if (settled) return;
|
||||
try {
|
||||
const outcome = await opts.pollBetOutcome!();
|
||||
if (outcome) finish(outcome);
|
||||
} catch {
|
||||
/* keep waiting until timeout */
|
||||
}
|
||||
};
|
||||
void poll();
|
||||
pollTimer = setInterval(() => {
|
||||
void poll();
|
||||
}, pollIntervalMs);
|
||||
}
|
||||
|
||||
timer = setTimeout(() => {
|
||||
const late = readCachedOutcome(idempotencyKey);
|
||||
if (late) {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user