fix: 修复排行榜数据自增长(冷启动重复创建云端文档)
每次小程序冷启动都会为同一用户创建新的云端文档, 导致 leaderboard 把同一份数据累加 N 次。 改动: - app.js: onLaunch 改为 async,每次启动先 pullAll 填充 _openid / _docId 缓存 - utils/cloud.js: 引入 _ensureOpenid() 单次解析;_doPush 总是先按 openid 定位现有文档;update 失败不再回退到 add()(避免创建重复文档) - utils/storage.js: getTodayRecord 按日期部分比较,修复一天第二次训练
This commit is contained in:
+66
-12
@@ -8,6 +8,9 @@ let _docId = null // cache doc id after first successful push
|
||||
let _openid = null // cache openid from first successful add, used to
|
||||
// re-locate our doc when _docId goes stale
|
||||
// (e.g. user manually deleted the doc in the console)
|
||||
let _openidPromise = null // in-flight _fetchOpenid promise, prevents
|
||||
// concurrent pushAll calls from racing the
|
||||
// openid lookup (and each issuing an add())
|
||||
|
||||
const getDb = () => {
|
||||
if (!_enabled) return null
|
||||
@@ -68,11 +71,44 @@ const _fetchOpenid = async () => {
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and cache the user's openid exactly once per app session,
|
||||
* sharing a single in-flight promise across concurrent callers.
|
||||
*
|
||||
* Why this exists: pushAll() schedules _doPush() 2s later. Between the
|
||||
* schedule and the actual run, the module-level caches (_openid, _docId)
|
||||
* are null on every cold start. The original code would let _doPush fall
|
||||
* straight through to add() and create a brand-new cloud doc on every
|
||||
* cold start — which leaderboard then summed across N docs for the same
|
||||
* _openid. Pre-resolving openid here lets _doPush always locate the
|
||||
* existing doc (or skip the write if lookup fails) before considering
|
||||
* add().
|
||||
*/
|
||||
const _ensureOpenid = async () => {
|
||||
if (_openid) return _openid
|
||||
if (!_openidPromise) {
|
||||
_openidPromise = _fetchOpenid().then(o => {
|
||||
_openid = o
|
||||
_openidPromise = null
|
||||
return o
|
||||
}).catch(e => {
|
||||
_openidPromise = null
|
||||
return null
|
||||
})
|
||||
}
|
||||
return _openidPromise
|
||||
}
|
||||
|
||||
const pushAll = () => {
|
||||
if (!_enabled) { console.log('[cloud] pushAll skipped (not enabled)'); return }
|
||||
if (_pushTimer) clearTimeout(_pushTimer)
|
||||
console.log('[cloud] pushAll scheduled')
|
||||
_pushTimer = setTimeout(() => _doPush(), 2000)
|
||||
// Pre-warm openid so _doPush never sees _openid=null on a cold start
|
||||
// (which used to bypass the locate-by-openid branch and call add(),
|
||||
// creating a duplicate cloud doc every cold start).
|
||||
_ensureOpenid().finally(() => {
|
||||
if (_pushTimer) clearTimeout(_pushTimer)
|
||||
_pushTimer = setTimeout(() => _doPush(), 2000)
|
||||
})
|
||||
}
|
||||
|
||||
const _doPush = async () => {
|
||||
@@ -94,7 +130,7 @@ const _doPush = async () => {
|
||||
}
|
||||
console.log('[cloud] _doPush records keys:', Object.keys(data.records || {}))
|
||||
|
||||
// Use cached doc id if available
|
||||
// Fast path: cached _docId update
|
||||
if (_docId) {
|
||||
try {
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
@@ -105,28 +141,46 @@ const _doPush = async () => {
|
||||
// the collection in the console). The custom write rule evaluates
|
||||
// `doc._openid == auth.openid` → `undefined == openid` → false,
|
||||
// so this surfaces as -502003 rather than "not found". Either way,
|
||||
// fall through and re-locate the doc via cached _openid (or add).
|
||||
// fall through and re-locate the doc via openid.
|
||||
console.log('[cloud] _doPush cached _docId stale, clearing:', e.message)
|
||||
_docId = null
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: locate OUR doc by _openid (cached from a previous add) and
|
||||
// update it. If we have no cached openid yet (first ever push) just add.
|
||||
if (_openid) {
|
||||
// Required path: always try to locate OUR doc by _openid before any
|
||||
// add(). pushAll() pre-warms _openid via _ensureOpenid, so by the time
|
||||
// we reach this branch on a cold start _openid is populated and we'll
|
||||
// hit the update branch instead of falling through to add(). This is
|
||||
// the fix for the "leaderboard data increases on its own" bug.
|
||||
const openid = await _ensureOpenid()
|
||||
if (openid) {
|
||||
const existing = await db.collection(DB_COLLECTION)
|
||||
.where({ _openid: _openid })
|
||||
.where({ _openid: openid })
|
||||
.limit(1)
|
||||
.get()
|
||||
if (existing && existing.data && existing.data.length > 0) {
|
||||
_docId = existing.data[0]._id
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
console.log('[cloud] _doPush update ok (re-located by _openid)')
|
||||
return
|
||||
try {
|
||||
await db.collection(DB_COLLECTION).doc(_docId).update({ data })
|
||||
console.log('[cloud] _doPush update ok (re-located by _openid)')
|
||||
return
|
||||
} catch (e) {
|
||||
// If even the freshly-located doc rejects our update (custom
|
||||
// permission rule, race with another tab, etc.), DO NOT fall
|
||||
// through to add() — that would silently create a duplicate
|
||||
// cloud doc for the same user. Bail and let the next push retry.
|
||||
console.log('[cloud] _doPush update-by-openid failed, aborting:', e.message)
|
||||
_docId = null
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log('[cloud] _doPush no openid available, aborting (avoid duplicate add)')
|
||||
return
|
||||
}
|
||||
|
||||
// First push ever, or our doc was deleted and no other doc exists.
|
||||
// Reached only when we've positively confirmed no doc exists for our
|
||||
// openid in the cloud — safe to add() the first document.
|
||||
const res = await db.collection(DB_COLLECTION).add({ data })
|
||||
if (res && res._id) _docId = res._id
|
||||
if (res && res._openid) _openid = res._openid
|
||||
|
||||
Reference in New Issue
Block a user