feat(proton): finish OIDB migration — runOidb on protobuf_encode<OidbBase<T>>

Closes the OIDB phase of the proton migration. Every consumer that
talked to the OIDB service through the old runtime
`makeOidbBaseSchema()` factory now goes through the compile-time
generic `OidbBase<T>` instead — proton monomorphizes the codec per
call-site instantiation.

@snowluma/proton — two analyzer fixes uncovered by the migration:

1. Skip queuing call-site type-args that reference an *enclosing
   generic function's* type parameter for monomorphization. Before
   this, a wrapper like

     export function encodeOidbEnv<T>(env: OidbBase<T>): Uint8Array {
       return protobuf_encode<OidbBase<T>>(env);
     }

   would cause the analyzer to mint a literal `OidbBase__T` registry
   entry with `body.typeName = 'T'`, which the post-walk wire-type
   guard then tripped on. The enclosing-scope type params are tracked
   on a stack as the walker descends into FunctionDeclaration,
   FunctionExpression, ArrowFunction, MethodDeclaration nodes; matching
   call sites are skipped (the wrapper-binding path is still
   responsible for materialising concrete codecs at downstream call
   sites).

2. Register *explicitly* empty interfaces (`interface X {}`) as
   zero-field proto messages. OIDB has a handful of these
   ('this call has no meaningful response body' placeholders —
   Oidb0xeb7Resp, Oidb0xcd4Resp, Oidb0x112aResp, Oidb0x8a0Resp,
   Oidb0xf16Resp, OidbClientKeyReq). Proto3 wire allows zero-field
   messages, and downstream code does `protobuf_decode<OidbBase<X>>`
   where X is one of these — the wire-type guard would otherwise trip
   on the missing `X` registration. Interfaces that have members but
   no pb-marked fields are still NOT registered.

@snowluma/core — the OIDB-layer refactor itself:

bridge-oidb.ts ditches the runtime ProtoSchema factory and exposes:
  - makeOidbEnvelope<T>(oidbCmd, subCmd, body, isUid)   pure helper
  - encodeOidbEnv<T>(env)                               pass-through
  - decodeOidbEnv<T>(bytes)                             pass-through
  - runOidb(bridge, cmd, envelopeBytes)                 non-generic raw

`encodeOidbEnv` / `decodeOidbEnv` are pure pass-through generic
wrappers — proton wrapper-binds them and substitutes every call site
with the inlined `protobuf_encode_OidbBase__X` / `protobuf_decode_…`
function. `runOidb` is non-generic (proton leaves it alone) so it can
be mocked in tests. `makeOidbEnvelope` is plain TS — also mockable for
introspection.

56 `runOidb` call sites across 11 files migrated to the new API:
  - bridge-contacts.ts, actions/extras.ts, actions/friend.ts,
    actions/group-admin.ts, actions/group-file.ts,
    actions/group-message.ts, actions/interaction.ts,
    actions/misc.ts, actions/profile.ts, web-actions/cookies.ts,
    highway/pipeline.ts

pipeline.ts also drops `makeOidbBaseSchema(NTV2UploadRichMediaReqSchema)`
and the residual `protoEncode({...}, EncodableMediaMsgInfoSchema)` —
both go through proton now.

Tests:
  - 8 test files migrated from `vi.mocked(decodeOidbEnv).mockReturnValueOnce`
    to `vi.mocked(runOidb).mockResolvedValueOnce(protobuf_encode<OidbBase<X>>({body: …}))`
    — the proton substitution means the old mock layer is bypassed at
    build time, so the only mockable point is the bytes layer at `runOidb`.
  - 2 new parity tests pinning `OidbBase<T>` ↔ legacy
    `makeOidbBaseSchema(InnerSchema)` byte equivalence.

Verification:
  - @snowluma/proton: 95/95 tests pass, tsc --noEmit clean
  - @snowluma/core:   605/605 tests pass (network-manager.test.ts
    fails to load due to a missing darwin-arm64 native binary in this
    environment — pre-existing), tsc --noEmit clean
This commit is contained in:
DrSmoothl committed 2026-05-19 08:19:14 +08:00
1 parent 6f3646e956
commit 5802812392
25 files changed
+1144 -977

No files matched your search

+94 -44
View File
@@ -107,58 +107,108 @@ export function analyze(code: string, filePath: string, imported?: ImportedDefin
for (const [k, v] of imported.templates) templates.set(k, v);
}
// Stack of generic-function type-param scopes. When visiting a
// `protobuf_encode/decode<X>` call whose type arg references one of
// these (e.g. `protobuf_encode<OidbBase<T>>(env)` inside
// `function encodeOidbEnv<T>(...)`), we MUST skip monomorphization —
// the type arg only resolves once the wrapper itself is instantiated
// at a downstream call site, and that case is handled separately by
// the wrapper-binding path in `matchForwardedProtobufFn`. Without
// this skip, the analyzer would happily mint a literal `OidbBase__T`
// registry entry with a `body.typeName = 'T'` field, which the
// wire-type guard then trips on.
const enclosingTypeParamStack: Set<string>[] = [];
function typeArgReferencesEnclosingParam(typeArg: ts.TypeNode): boolean {
if (enclosingTypeParamStack.length === 0) return false;
let found = false;
function check(n: ts.Node): void {
if (found) return;
if (ts.isTypeReferenceNode(n) && ts.isIdentifier(n.typeName)) {
const name = n.typeName.text;
for (const scope of enclosingTypeParamStack) {
if (scope.has(name)) { found = true; return; }
}
}
ts.forEachChild(n, check);
}
check(typeArg);
return found;
}
function nodeIntroducesTypeParams(n: ts.Node): readonly ts.TypeParameterDeclaration[] | undefined {
if (ts.isFunctionDeclaration(n)) return n.typeParameters;
if (ts.isFunctionExpression(n)) return n.typeParameters;
if (ts.isArrowFunction(n)) return n.typeParameters;
if (ts.isMethodDeclaration(n)) return n.typeParameters;
return undefined;
}
// ── single walk ─────────────────────────────────────────────────────
ts.forEachChild(sf, function visit(node) {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) {
deferredTypeArgs.push(ta);
}
}
const introduced = nodeIntroducesTypeParams(node);
const pushedScope = !!(introduced && introduced.length);
if (pushedScope) {
enclosingTypeParamStack.push(new Set(introduced!.map(p => p.name.text)));
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
try {
if (ts.isInterfaceDeclaration(node)) {
if (node.typeParameters?.length) {
const tpl = collectGenericInterface(node, sf, resolveImportedTypeName);
if (tpl) templates.set(tpl.name, tpl);
} else {
const msg = collectInterface(node, sf, resolveImportedTypeName);
if (msg) concrete.push(msg);
// Queue any generic-instantiated type-args appearing as field types
// (e.g. `wrapped: pb<5, Wrapper<uint_32>>`) for monomorphization.
// The call-site queue only sees the outer concrete type, so without
// this the nested instantiation would never reach the registry.
for (const ta of collectConcreteFieldGenericTypeArgs(node, resolveImportedTypeName)) {
deferredTypeArgs.push(ta);
}
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
}
if (ts.isCallExpression(node)) {
const cs = matchProtobufCallSite(node, sf, importBindings, {
allowLegacyUnboundCanonical: true,
});
if (cs) {
if (!typeArgReferencesEnclosingParam(cs.firstTypeArg)) {
deferredTypeArgs.push(cs.firstTypeArg);
callSites.push(cs);
}
// else: this call sits inside a generic wrapper definition; the
// wrapper-binding path will materialise concrete codecs at each
// downstream call site instead.
} else if (
node.typeArguments?.length &&
getCallableName(node.expression) &&
wrapperBindings.has(getCallableName(node.expression)!)
) {
const binding = wrapperBindings.get(getCallableName(node.expression)!)!;
const firstTypeArg = instantiateWrapperTypePattern(binding, node.typeArguments, sf);
if (!firstTypeArg) {
ts.forEachChild(node, visit);
return;
}
const exprStart = node.expression.getStart(sf);
const lc = sf.getLineAndCharacterOfPosition(exprStart);
deferredTypeArgs.push(firstTypeArg);
callSites.push({
fnName: binding.fnName,
exprStart,
typeArgsEnd: node.typeArguments.end + 1,
firstTypeArg,
line: lc.line + 1,
column: lc.character + 1,
});
}
}
}
ts.forEachChild(node, visit);
ts.forEachChild(node, visit);
} finally {
if (pushedScope) enclosingTypeParamStack.pop();
}
});
// ── post-walk: monomorphize deferred type args ──────────────────────
+9 -1
View File
@@ -46,7 +46,15 @@ export function collectInterface(
const f = extractField(m, sf, resolveImportedTypeName);
if (f) fields.push(f);
}
return fields.length ? { name: node.name.text, fields } : null;
// Register interfaces that are EXPLICITLY empty (`interface X {}`) as
// zero-field proto messages — proto3 wire format allows them and
// downstream code routinely uses them for "this OIDB call has no
// meaningful response body" placeholders. Interfaces that have
// members but no pb-marked fields are NOT proto messages — they
// belong to regular TS types and must stay unregistered to avoid
// polluting the registry.
if (fields.length === 0 && node.members.length > 0) return null;
return { name: node.name.text, fields };
}
/** Collect a generic interface template. */