fix(core): bound forward caches with nested result retention
Keep at most 512 outer results per bridge and retain their bundled nested results as one cache group. Reads refresh the whole group, shared inner results survive while another containing group remains cached, and late sender enrichment cannot resurrect evicted entries. Collect uploaded and downloaded nested results before publishing a complete cache group. Cover eviction, account isolation, nested retrieval, shared ownership and asynchronous enrichment through the forward API. Refs #546, #555, #557. Co-authored-by: wanqing-last <[email protected]>
This commit is contained in:
4 files changed
+343
-33
No files matched your search
@@ -0,0 +1,69 @@
|
|||||||
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
|
import type { ForwardNodePayload } from '@snowluma/protocol/events';
|
||||||
|
|
||||||
|
const MAX_CACHED_FORWARDS = 512;
|
||||||
|
const log = createLogger('Bridge.Forward');
|
||||||
|
type ForwardLayers = Map<string, ForwardNodePayload[]>;
|
||||||
|
|
||||||
|
interface ForwardCacheHit {
|
||||||
|
rootId: string;
|
||||||
|
resId: string;
|
||||||
|
layers: ForwardLayers;
|
||||||
|
nodes: ForwardNodePayload[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Nested results share the lifetime and recency of the result that supplied them. */
|
||||||
|
export class ForwardResultCache {
|
||||||
|
private readonly entries = new Map<string, ForwardLayers>();
|
||||||
|
|
||||||
|
get(resId: string): ForwardCacheHit | undefined {
|
||||||
|
let hit: ForwardCacheHit | undefined;
|
||||||
|
|
||||||
|
// A nested result can be supplied by several retained outer results.
|
||||||
|
for (const [rootId, layers] of this.entries) {
|
||||||
|
const nodes = layers.get(resId);
|
||||||
|
|
||||||
|
if (nodes) {
|
||||||
|
hit = { rootId, resId, layers, nodes };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hit) {
|
||||||
|
this.entries.delete(hit.rootId);
|
||||||
|
this.entries.set(hit.rootId, hit.layers);
|
||||||
|
}
|
||||||
|
|
||||||
|
return hit;
|
||||||
|
}
|
||||||
|
|
||||||
|
set(rootId: string, layers: ReadonlyMap<string, ForwardNodePayload[]>): void {
|
||||||
|
if (!layers.has(rootId)) {
|
||||||
|
throw new Error('forward cache entry is missing its outer result');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.entries.delete(rootId);
|
||||||
|
this.entries.set(rootId, new Map(layers));
|
||||||
|
|
||||||
|
while (this.entries.size > MAX_CACHED_FORWARDS) {
|
||||||
|
const oldest = this.entries.entries().next().value!;
|
||||||
|
this.entries.delete(oldest[0]);
|
||||||
|
log.trace(
|
||||||
|
'forward cache evicted: res_id=%s layers=%d remaining=%d',
|
||||||
|
oldest[0],
|
||||||
|
oldest[1].size,
|
||||||
|
this.entries.size,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
update(hit: ForwardCacheHit, nodes: ForwardNodePayload[]): void {
|
||||||
|
// Enrichment may finish after eviction or replacement. It must not revive
|
||||||
|
// an old result or turn a nested result into an independent cache entry.
|
||||||
|
if (
|
||||||
|
this.entries.get(hit.rootId) === hit.layers &&
|
||||||
|
hit.layers.get(hit.resId) === hit.nodes
|
||||||
|
) {
|
||||||
|
hit.layers.set(hit.resId, nodes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,16 +25,15 @@ import { randomUUID } from 'crypto';
|
|||||||
import { gunzipSync, gzipSync } from 'zlib';
|
import { gunzipSync, gzipSync } from 'zlib';
|
||||||
import type { Bridge } from '../bridge';
|
import type { Bridge } from '../bridge';
|
||||||
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
import type { BridgeContext, UploadedFileMeta } from '../bridge-context';
|
||||||
|
import { ForwardResultCache } from './forward-cache';
|
||||||
import { resolveSelfUid, toInt } from './shared';
|
import { resolveSelfUid, toInt } from './shared';
|
||||||
|
|
||||||
function asBridge(ctx: BridgeContext): Bridge {
|
function asBridge(ctx: BridgeContext): Bridge {
|
||||||
return ctx as unknown as Bridge;
|
return ctx as unknown as Bridge;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Module-scoped cache, keyed by res_id. Survives only for the lifetime
|
// Share within a bridge without retaining disconnected accounts.
|
||||||
// of the process — that's enough because OneBot clients typically
|
const forwardCaches = new WeakMap<BridgeContext, ForwardResultCache>();
|
||||||
// resolve a forward immediately after receiving the parent message.
|
|
||||||
const forwardResCache = new Map<string, ForwardNodePayload[]>();
|
|
||||||
|
|
||||||
const log = createLogger('Bridge.Forward');
|
const log = createLogger('Bridge.Forward');
|
||||||
|
|
||||||
@@ -77,6 +76,7 @@ interface ForwardUploadResult {
|
|||||||
// callers concatenate these to their own actions list so the
|
// callers concatenate these to their own actions list so the
|
||||||
// outermost upload carries the full tree.
|
// outermost upload carries the full tree.
|
||||||
innerActions: ForwardInnerAction[];
|
innerActions: ForwardInnerAction[];
|
||||||
|
cachedLayers: Map<string, ForwardNodePayload[]>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
|
// Local hex-decode helper — avoids importing the heavyweight `pipeline`
|
||||||
@@ -353,7 +353,18 @@ function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ForwardApi {
|
export class ForwardApi {
|
||||||
constructor(private readonly ctx: BridgeContext) {}
|
private readonly cache: ForwardResultCache;
|
||||||
|
|
||||||
|
constructor(private readonly ctx: BridgeContext) {
|
||||||
|
let cache = forwardCaches.get(ctx);
|
||||||
|
|
||||||
|
if (!cache) {
|
||||||
|
cache = new ForwardResultCache();
|
||||||
|
forwardCaches.set(ctx, cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.cache = cache;
|
||||||
|
}
|
||||||
|
|
||||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||||
// Reject the complete recursive tree before identity resolution, media
|
// Reject the complete recursive tree before identity resolution, media
|
||||||
@@ -367,7 +378,8 @@ export class ForwardApi {
|
|||||||
assertPrivateForwardFileCapacity(nodes);
|
assertPrivateForwardFileCapacity(nodes);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
const { resId, cachedLayers } = await this.uploadRecursive(nodes, groupId, userId);
|
||||||
|
this.cache.set(resId, cachedLayers);
|
||||||
return resId;
|
return resId;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -593,6 +605,7 @@ export class ForwardApi {
|
|||||||
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
// — see `dev/NapCatQQ/.../SendMsg.ts:241-246` + the `uniseq` round-
|
||||||
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
// trip in `dev/NapCatQQ/.../forward-msg-builder.ts:94`.
|
||||||
const myInnerActions: ForwardInnerAction[] = [];
|
const myInnerActions: ForwardInnerAction[] = [];
|
||||||
|
const cachedLayers = new Map<string, ForwardNodePayload[]>();
|
||||||
const processedNodes: ForwardNodePayload[] = [];
|
const processedNodes: ForwardNodePayload[] = [];
|
||||||
const isGroup = groupId !== undefined;
|
const isGroup = groupId !== undefined;
|
||||||
|
|
||||||
@@ -605,6 +618,11 @@ export class ForwardApi {
|
|||||||
// and `inner.innerActions` already contains deeper layers.
|
// and `inner.innerActions` already contains deeper layers.
|
||||||
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
myInnerActions.push({ uuid: inner.uuid, msgBody: inner.msgBody });
|
||||||
myInnerActions.push(...inner.innerActions);
|
myInnerActions.push(...inner.innerActions);
|
||||||
|
|
||||||
|
for (const [resId, cached] of inner.cachedLayers) {
|
||||||
|
cachedLayers.set(resId, cached);
|
||||||
|
}
|
||||||
|
|
||||||
// Replace the inner placeholder element with a forward preview
|
// Replace the inner placeholder element with a forward preview
|
||||||
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
// pointing at the inner res_id. `forwardUuid: inner.uuid`
|
||||||
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
// baked into the LightApp JSON's `meta.detail.uniseq` is what
|
||||||
@@ -692,7 +710,7 @@ export class ForwardApi {
|
|||||||
throw new Error('upload forward message response missing res_id');
|
throw new Error('upload forward message response missing res_id');
|
||||||
}
|
}
|
||||||
|
|
||||||
forwardResCache.set(
|
cachedLayers.set(
|
||||||
resId,
|
resId,
|
||||||
uploadReadyNodes.map((node) => ({
|
uploadReadyNodes.map((node) => ({
|
||||||
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
...cloneNodeWithElements(node, node.elements.map(cacheableForwardElement)),
|
||||||
@@ -714,20 +732,21 @@ export class ForwardApi {
|
|||||||
// from (1) — no separate fetch needed.
|
// from (1) — no separate fetch needed.
|
||||||
uuid: randomUUID(),
|
uuid: randomUUID(),
|
||||||
innerActions: myInnerActions,
|
innerActions: myInnerActions,
|
||||||
|
cachedLayers,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
async fetch(resId: string): Promise<ForwardNodePayload[]> {
|
||||||
const bridge = asBridge(this.ctx);
|
const bridge = asBridge(this.ctx);
|
||||||
const cached = forwardResCache.get(resId);
|
const cached = this.cache.get(resId);
|
||||||
|
|
||||||
if (cached) {
|
if (cached) {
|
||||||
const nodes = cloneNodes(cached);
|
const nodes = cloneNodes(cached.nodes);
|
||||||
|
|
||||||
// Inner nodes seeded by consumePiggybacks are cached un-enriched; enrich
|
// Bundled inner nodes are cached un-enriched; enrich
|
||||||
// on read (a no-op once names are present) and persist so later hits skip.
|
// on read (a no-op once names are present) and persist so later hits skip.
|
||||||
if (await this.enrichSenders(nodes)) {
|
if (await this.enrichSenders(nodes)) {
|
||||||
forwardResCache.set(resId, cloneNodes(nodes));
|
this.cache.update(cached, cloneNodes(nodes));
|
||||||
}
|
}
|
||||||
|
|
||||||
return nodes;
|
return nodes;
|
||||||
@@ -820,9 +839,7 @@ export class ForwardApi {
|
|||||||
// matching piggyback body, decode it into inner nodes, and seed
|
// matching piggyback body, decode it into inner nodes, and seed
|
||||||
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
// the cache by the inner resId so a follow-up `fetch(innerResId)`
|
||||||
// hits the cache instead of the wire.
|
// hits the cache instead of the wire.
|
||||||
if (piggybackByUuid.size > 0) {
|
const cachedLayers = this.collectForwardLayers(resId, nodes, piggybackByUuid);
|
||||||
this.consumePiggybacks(nodes, piggybackByUuid);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
|
// Fill sender nickname/card for nodes the SsoRecvLongMsg payload left empty
|
||||||
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
|
// or stamped with the "QQ用户" placeholder (#174) — the long-msg member name
|
||||||
@@ -830,7 +847,8 @@ export class ForwardApi {
|
|||||||
await this.enrichSenders(nodes);
|
await this.enrichSenders(nodes);
|
||||||
|
|
||||||
if (nodes.length > 0) {
|
if (nodes.length > 0) {
|
||||||
forwardResCache.set(resId, cloneNodes(nodes));
|
cachedLayers.set(resId, cloneNodes(nodes));
|
||||||
|
this.cache.set(resId, cachedLayers);
|
||||||
}
|
}
|
||||||
|
|
||||||
return nodes;
|
return nodes;
|
||||||
@@ -1017,20 +1035,22 @@ export class ForwardApi {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Recursively resolve forward previews against the piggyback table.
|
/** Resolve forward previews against the piggyback table.
|
||||||
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
* For every `{type: 'forward', resId, forwardUuid}` element we find,
|
||||||
* look up the uniseq in the piggyback map; if hit, decode the
|
* look up the uniseq in the piggyback map; if hit, decode the
|
||||||
* inner msgBody and cache it by inner resId, then descend into that
|
* inner msgBody and cache it by inner resId, then descend into that
|
||||||
* inner layer to resolve deeper nestings carried in the SAME
|
* inner layer to resolve deeper nestings carried in the SAME
|
||||||
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
* piggyback set (NapCat hoists the entire tree's piggybacks onto
|
||||||
* the outermost action list). */
|
* the outermost action list). */
|
||||||
private consumePiggybacks(
|
private collectForwardLayers(
|
||||||
|
resId: string,
|
||||||
nodes: ForwardNodePayload[],
|
nodes: ForwardNodePayload[],
|
||||||
piggybackByUuid: Map<string, PushMsgBody[]>,
|
piggybackByUuid: Map<string, PushMsgBody[]>,
|
||||||
): void {
|
): Map<string, ForwardNodePayload[]> {
|
||||||
const seen = new Set<string>();
|
const layers = new Map([[resId, cloneNodes(nodes)]]);
|
||||||
|
const decodedByUuid = new Map<string, ForwardNodePayload[]>();
|
||||||
|
|
||||||
const visit = (chain: ForwardNodePayload[]): void => {
|
for (const chain of layers.values()) {
|
||||||
for (const node of chain) {
|
for (const node of chain) {
|
||||||
for (const elem of node.elements) {
|
for (const elem of node.elements) {
|
||||||
if (elem.type !== 'forward') {
|
if (elem.type !== 'forward') {
|
||||||
@@ -1040,7 +1060,7 @@ export class ForwardApi {
|
|||||||
const uuid = elem.forwardUuid;
|
const uuid = elem.forwardUuid;
|
||||||
const innerResId = elem.resId;
|
const innerResId = elem.resId;
|
||||||
|
|
||||||
if (!uuid || !innerResId || seen.has(uuid)) {
|
if (!uuid || !innerResId || layers.has(innerResId)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1050,15 +1070,19 @@ export class ForwardApi {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
seen.add(uuid);
|
let innerNodes = decodedByUuid.get(uuid);
|
||||||
const innerNodes = this.decodeMsgBodiesToNodes(body);
|
|
||||||
forwardResCache.set(innerResId, cloneNodes(innerNodes));
|
|
||||||
visit(innerNodes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
visit(nodes);
|
if (!innerNodes) {
|
||||||
|
innerNodes = cloneNodes(this.decodeMsgBodiesToNodes(body));
|
||||||
|
decodedByUuid.set(uuid, innerNodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
layers.set(innerResId, innerNodes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return layers;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ function message(...elems: Elem[]): PushMsgBody {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function setup(downloads: Map<string, LongMsgResult>) {
|
function setup(downloads: Map<string, LongMsgResult>, selfUin = '10001') {
|
||||||
const requested: string[] = [];
|
const requested: string[] = [];
|
||||||
const bridge = mockBridge({
|
const bridge = mockBridge({
|
||||||
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
|
sendRawPacket: vi.fn(async (command: string, bytes: Uint8Array) => {
|
||||||
@@ -61,21 +61,194 @@ function setup(downloads: Map<string, LongMsgResult>) {
|
|||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
bridge.identity.uin = selfUin;
|
||||||
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||||
const ctx = {
|
const ctx = {
|
||||||
selfId: 10001,
|
selfId: Number(selfUin),
|
||||||
bridge: { apis: { forward } },
|
bridge: { apis: { forward } },
|
||||||
converterCtx: {
|
converterCtx: {
|
||||||
selfId: 10001,
|
selfId: Number(selfUin),
|
||||||
imageUrlResolver: null,
|
imageUrlResolver: null,
|
||||||
mediaUrlResolver: null,
|
mediaUrlResolver: null,
|
||||||
messageIdResolver: null,
|
messageIdResolver: null,
|
||||||
mediaSegmentSink: null,
|
mediaSegmentSink: null,
|
||||||
},
|
},
|
||||||
} as unknown as OneBotInstanceContext;
|
} as unknown as OneBotInstanceContext;
|
||||||
return { api: buildApiContext(ctx), requested };
|
return { api: buildApiContext(ctx), requested, bridge, forward };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function plainResult(text: string): LongMsgResult {
|
||||||
|
return {
|
||||||
|
action: [
|
||||||
|
{
|
||||||
|
actionCommand: 'MultiMsg',
|
||||||
|
actionData: { msgBody: [message({ text: { str: text } })] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function nestedResult(inner: string, key: string, body?: PushMsgBody): LongMsgResult {
|
||||||
|
return {
|
||||||
|
action: [
|
||||||
|
{
|
||||||
|
actionCommand: 'MultiMsg',
|
||||||
|
actionData: { msgBody: [message(forwardCard('xml', inner, key))] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
actionCommand: key,
|
||||||
|
actionData: { msgBody: [body ?? message({ text: { str: 'inner content' } })] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fillCache(
|
||||||
|
api: ReturnType<typeof setup>['api'],
|
||||||
|
downloads: Map<string, LongMsgResult>,
|
||||||
|
prefix: string,
|
||||||
|
count: number,
|
||||||
|
): Promise<void> {
|
||||||
|
for (let index = 0; index < count; index++) {
|
||||||
|
const id = `${prefix}-${index}`;
|
||||||
|
downloads.set(id, plainResult(id));
|
||||||
|
await api.getForwardMsg(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('get_forward_msg / cache lifetime', () => {
|
||||||
|
it('bounds cached results while refreshing recently read results', async () => {
|
||||||
|
const downloads = new Map([
|
||||||
|
['cache-cold', plainResult('cold')],
|
||||||
|
['cache-hot', plainResult('hot')],
|
||||||
|
]);
|
||||||
|
const { api, requested } = setup(downloads);
|
||||||
|
await api.getForwardMsg('cache-cold');
|
||||||
|
await api.getForwardMsg('cache-hot');
|
||||||
|
await fillCache(api, downloads, 'cache-pressure', 510);
|
||||||
|
await api.getForwardMsg('cache-hot');
|
||||||
|
await fillCache(api, downloads, 'cache-overflow', 1);
|
||||||
|
requested.length = 0;
|
||||||
|
await api.getForwardMsg('cache-hot');
|
||||||
|
await api.getForwardMsg('cache-cold');
|
||||||
|
expect(requested).toEqual(['cache-cold']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('isolates cached content between bridge accounts', async () => {
|
||||||
|
const first = setup(new Map([['same-resource', plainResult('account one')]]));
|
||||||
|
const second = setup(new Map([['same-resource', plainResult('account two')]]), '10002');
|
||||||
|
await first.api.getForwardMsg('same-resource');
|
||||||
|
expect((await second.api.getForwardMsg('same-resource'))[0]?.message).toEqual([
|
||||||
|
{ type: 'text', data: { text: 'account two' } },
|
||||||
|
]);
|
||||||
|
expect(second.requested).toEqual(['same-resource']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps nested results with a hot outer result under cache pressure', async () => {
|
||||||
|
const downloads = new Map([['hot-outer', nestedResult('hot-inner', 'hot-inner-key')]]);
|
||||||
|
const { api, requested } = setup(downloads);
|
||||||
|
await api.getForwardMsg('hot-outer');
|
||||||
|
await fillCache(api, downloads, 'nested-pressure', 511);
|
||||||
|
await api.getForwardMsg('hot-inner');
|
||||||
|
await fillCache(api, downloads, 'nested-overflow', 1);
|
||||||
|
requested.length = 0;
|
||||||
|
expect((await api.getForwardMsg('hot-outer'))[0]?.message).toEqual([
|
||||||
|
{ type: 'forward', data: { id: 'hot-inner' } },
|
||||||
|
]);
|
||||||
|
expect((await api.getForwardMsg('hot-inner'))[0]?.message).toEqual([
|
||||||
|
{ type: 'text', data: { text: 'inner content' } },
|
||||||
|
]);
|
||||||
|
expect(requested).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an inner result attached to its outer result after sender enrichment', async () => {
|
||||||
|
const nameless = message({ text: { str: 'unnamed sender' } });
|
||||||
|
nameless.responseHead!.grp!.memberCard = '';
|
||||||
|
const downloads = new Map([
|
||||||
|
['enrich-outer', nestedResult('enrich-inner', 'enrich-key', nameless)],
|
||||||
|
]);
|
||||||
|
const { api, requested, bridge } = setup(downloads);
|
||||||
|
bridge.apis.contacts.fetchGroupMemberList.mockResolvedValue([
|
||||||
|
{ uin: 20002, nickname: 'resolved nickname', card: 'resolved card' },
|
||||||
|
]);
|
||||||
|
await api.getForwardMsg('enrich-outer');
|
||||||
|
await fillCache(api, downloads, 'enrich-pressure', 511);
|
||||||
|
requested.length = 0;
|
||||||
|
expect((await api.getForwardMsg('enrich-inner'))[0]).toMatchObject({
|
||||||
|
sender: { nickname: 'resolved card' },
|
||||||
|
});
|
||||||
|
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
|
||||||
|
await api.getForwardMsg('enrich-outer');
|
||||||
|
await api.getForwardMsg('enrich-inner');
|
||||||
|
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce();
|
||||||
|
expect(requested).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retains a shared inner result while another containing outer result remains cached', async () => {
|
||||||
|
const downloads = new Map([
|
||||||
|
['shared-outer-a', nestedResult('shared-inner', 'shared-key-a')],
|
||||||
|
['shared-outer-b', nestedResult('shared-inner', 'shared-key-b')],
|
||||||
|
]);
|
||||||
|
const { api, requested } = setup(downloads);
|
||||||
|
await api.getForwardMsg('shared-outer-a');
|
||||||
|
await api.getForwardMsg('shared-outer-b');
|
||||||
|
await fillCache(api, downloads, 'shared-pressure', 510);
|
||||||
|
await api.getForwardMsg('shared-outer-a');
|
||||||
|
await fillCache(api, downloads, 'shared-overflow', 1);
|
||||||
|
requested.length = 0;
|
||||||
|
expect((await api.getForwardMsg('shared-inner'))[0]?.message).toEqual([
|
||||||
|
{ type: 'text', data: { text: 'inner content' } },
|
||||||
|
]);
|
||||||
|
expect(requested).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('restores all nested results when an evicted outer result is downloaded again', async () => {
|
||||||
|
const downloads = new Map([
|
||||||
|
['restore-outer', nestedResult('restore-inner', 'restore-key')],
|
||||||
|
]);
|
||||||
|
const { api, requested } = setup(downloads);
|
||||||
|
await api.getForwardMsg('restore-outer');
|
||||||
|
await api.getForwardMsg('restore-inner');
|
||||||
|
await fillCache(api, downloads, 'restore-pressure', 512);
|
||||||
|
requested.length = 0;
|
||||||
|
await api.getForwardMsg('restore-outer');
|
||||||
|
expect((await api.getForwardMsg('restore-inner'))[0]?.message).toEqual([
|
||||||
|
{ type: 'text', data: { text: 'inner content' } },
|
||||||
|
]);
|
||||||
|
expect(requested).toEqual(['restore-outer']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not resurrect evicted nested results when enrichment finishes late', async () => {
|
||||||
|
const nameless = message({ text: { str: 'late sender' } });
|
||||||
|
nameless.responseHead!.grp!.memberCard = '';
|
||||||
|
const downloads = new Map([
|
||||||
|
['late-outer', nestedResult('late-inner', 'late-key', nameless)],
|
||||||
|
]);
|
||||||
|
const { api, requested, bridge } = setup(downloads);
|
||||||
|
const members = [{ uin: 20002, nickname: 'late name', card: '' }];
|
||||||
|
let finishEnrichment!: () => void;
|
||||||
|
const enrichment = new Promise<typeof members>((resolve) => {
|
||||||
|
finishEnrichment = () => resolve(members);
|
||||||
|
});
|
||||||
|
bridge.apis.contacts.fetchGroupMemberList.mockReturnValueOnce(enrichment);
|
||||||
|
await api.getForwardMsg('late-outer');
|
||||||
|
const pending = api.getForwardMsg('late-inner');
|
||||||
|
await vi.waitFor(() =>
|
||||||
|
expect(bridge.apis.contacts.fetchGroupMemberList).toHaveBeenCalledOnce(),
|
||||||
|
);
|
||||||
|
await fillCache(api, downloads, 'late-pressure', 512);
|
||||||
|
finishEnrichment();
|
||||||
|
expect((await pending)[0]).toMatchObject({ sender: { nickname: 'late name' } });
|
||||||
|
requested.length = 0;
|
||||||
|
await expect(api.getForwardMsg('late-inner')).rejects.toThrow('payload is empty');
|
||||||
|
await api.getForwardMsg('late-outer');
|
||||||
|
expect((await api.getForwardMsg('late-inner'))[0]?.message).toEqual([
|
||||||
|
{ type: 'text', data: { text: 'late sender' } },
|
||||||
|
]);
|
||||||
|
expect(requested).toEqual(['late-inner', 'late-outer']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('get_forward_msg / nested downloads (#529)', () => {
|
describe('get_forward_msg / nested downloads (#529)', () => {
|
||||||
it.each(['xml', 'lightApp'] as const)(
|
it.each(['xml', 'lightApp'] as const)(
|
||||||
'resolves siblings and three levels of %s forwards from one outer payload',
|
'resolves siblings and three levels of %s forwards from one outer payload',
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import { ForwardApi } from '../../src/bridge/apis/forward';
|
import { ForwardApi } from '../../src/bridge/apis/forward';
|
||||||
|
import type { BridgeContext } from '../../src/bridge/bridge-context';
|
||||||
import { mockBridge } from './_helpers';
|
import { mockBridge } from './_helpers';
|
||||||
|
|
||||||
function uploadResponseWithResId(resId: string) {
|
function uploadResponseWithResId(resId: string) {
|
||||||
@@ -107,6 +108,49 @@ function findLightAppJson(msgBody: PushMsgBody[]): {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('forward / nested upload wire alignment', () => {
|
describe('forward / nested upload wire alignment', () => {
|
||||||
|
it('bounds uploaded results while keeping a recently read nested upload together', async () => {
|
||||||
|
let sequence = 0;
|
||||||
|
const sendRawPacket = vi.fn(async (command: string) => {
|
||||||
|
if (command !== 'trpc.group.long_msg_interface.MsgService.SsoSendLongMsg') {
|
||||||
|
throw new Error('test cache miss');
|
||||||
|
}
|
||||||
|
|
||||||
|
return uploadResponseWithResId(`upload-cache-${++sequence}`);
|
||||||
|
});
|
||||||
|
const bridge = mockBridge({ sendRawPacket });
|
||||||
|
const forward = new ForwardApi(bridge as unknown as BridgeContext);
|
||||||
|
const outer = await forward.upload([
|
||||||
|
{
|
||||||
|
userUin: 111,
|
||||||
|
nickname: 'outer',
|
||||||
|
elements: [],
|
||||||
|
innerForward: [
|
||||||
|
{
|
||||||
|
userUin: 222,
|
||||||
|
nickname: 'inner',
|
||||||
|
elements: [{ type: 'text', text: 'nested upload' }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const filler = [{ userUin: 111, nickname: 'filler', elements: [] }];
|
||||||
|
|
||||||
|
for (let index = 0; index < 511; index++) {
|
||||||
|
await forward.upload(filler);
|
||||||
|
}
|
||||||
|
|
||||||
|
await forward.fetch('upload-cache-1');
|
||||||
|
await forward.upload(filler);
|
||||||
|
const uploadedCount = sendRawPacket.mock.calls.length;
|
||||||
|
const sameBridgeApi = new ForwardApi(bridge as unknown as BridgeContext);
|
||||||
|
expect((await sameBridgeApi.fetch(outer))[0]?.elements[0]?.resId).toBe('upload-cache-1');
|
||||||
|
expect((await sameBridgeApi.fetch('upload-cache-1'))[0]?.elements).toEqual([
|
||||||
|
{ type: 'text', text: 'nested upload' },
|
||||||
|
]);
|
||||||
|
expect(sendRawPacket).toHaveBeenCalledTimes(uploadedCount);
|
||||||
|
await expect(forward.fetch('upload-cache-3')).rejects.toThrow('test cache miss');
|
||||||
|
});
|
||||||
|
|
||||||
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
|
it('outer LongMsgResult contains both MultiMsg and the inner uuid piggyback action', async () => {
|
||||||
// Inner upload returns inner-res; outer upload returns outer-res.
|
// Inner upload returns inner-res; outer upload returns outer-res.
|
||||||
const responses = ['inner-res', 'outer-res'];
|
const responses = ['inner-res', 'outer-res'];
|
||||||
|
|||||||
Reference in new issue
Block a user