diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index 650e40dc..9c919be0 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -1,4 +1,4 @@ -import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; +import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; // Re-exported from the legacy oidb-action module while large protocol groups // are split into focused files. @@ -13,7 +13,11 @@ export interface OidbMuteMember { body?: pb<3, OidbMuteMemberBody>; } export interface OidbMuteAllState { - state?: pb<17, uint_32>; + // Explicit presence: the unmute request sends state=0, which proto3 would + // otherwise omit — leaving an empty `muteState` the server can't tell apart + // from the other commands sharing OIDB (0x89A, 0) (SetSearch / SetAddOption, + // disambiguated by body shape). pb_optional forces the 0 onto the wire. + state?: pb_optional<17, uint_32>; } export interface OidbMuteAll { groupUin?: pb<1, uint_32>; diff --git a/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts index 18f9d2b0..33e06dc2 100644 --- a/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts +++ b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts @@ -26,12 +26,18 @@ describe('MuteAll namespace', () => { expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } }); }); - it('enable=false emits state=0', async () => { + it('enable=false forces state=0 ONTO the wire (so the server can disambiguate)', async () => { const deps = makeDeps(); await MuteAll.invoke(deps, { groupId: 12345, enable: false }); const [, bytes] = deps.sendRawPacket.mock.calls[0]!; const env = protobuf_decode>(bytes); - // proto3 default 0 fields are omitted on the wire. - expect(env.body?.muteState?.state ?? 0).toBe(0); + expect(env.body?.muteState?.state).toBe(0); + // The fix (issue #70): state=0 is a `pb_optional<>` field, so it must be + // PRESENT on the wire — field 17 (varint tag 0x88 0x01) + value 0x00 — not + // omitted. An empty `muteState` is indistinguishable from the other + // commands sharing OIDB (0x89A, 0), so the server rejects unmute with 1007. + const arr = Array.from(bytes); + const hasStateField = arr.some((_, i) => arr[i] === 0x88 && arr[i + 1] === 0x01 && arr[i + 2] === 0x00); + expect(hasStateField).toBe(true); }); }); diff --git a/packages/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts index cc2f8deb..b6f52593 100644 --- a/packages/proton/protobuf.d.ts +++ b/packages/proton/protobuf.d.ts @@ -3,6 +3,14 @@ export type pb<_ProtoNumber extends number, Type> = Type; /** Marks a repeated protobuf field: `ids: pb_repeated` → Type[] */ export type pb_repeated<_ProtoNumber extends number, Type> = Type[]; +/** + * Marks a singular field with **explicit presence** (proto3 `optional`): it + * serialises whenever the value is present, INCLUDING its zero/default value + * — unlike `pb<>`, which omits zeros. Use when the wire peer needs the field + * present to disambiguate, e.g. an OIDB sub-command keyed on body shape where + * a zero must still appear on the wire. `name: pb_optional`. + */ +export type pb_optional<_ProtoNumber extends number, Type> = Type; // ── Protobuf primitive types ────────────────────────────────────────── export type uint_32 = number; diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index 6955b308..03552eba 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -1,7 +1,7 @@ import ts from 'typescript'; import { WireType, - PB_MARKER, PB_REPEATED_MARKER, + PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate, type GenericFieldTemplate, } from './types.js'; @@ -85,7 +85,7 @@ function parsePbTypeRef( // Resolve the marker name through aliased imports so `import { pb as P }` // / `import { pb_repeated as PR }` still match the marker constants. const marker = resolveImportedTypeName(t.typeName.text); - if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; + if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) return null; const ta = t.typeArguments; if (!ta || ta.length !== 2) return null; const fnNode = ta[0]; @@ -129,6 +129,7 @@ function extractField( isMessage: false, // placeholder isOptional: member.questionToken != null, isRepeated: parsed.marker === PB_REPEATED_MARKER, + explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, }; } @@ -149,6 +150,7 @@ function extractGenericField( isTypeParam: tpSet.has(raw), isOptional: member.questionToken != null, isRepeated: parsed.marker === PB_REPEATED_MARKER, + explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, }; // If the field's type-arg is itself a generic instantiation (`Wrapper`, // where U is a type param of the enclosing template), capture the original diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts index 29d9e47b..adf7c38e 100644 --- a/packages/proton/src/ast/monomorphizer.ts +++ b/packages/proton/src/ast/monomorphizer.ts @@ -89,6 +89,7 @@ export function monomorphizeTypeNode( isMessage: false, isOptional: f.isOptional, isRepeated: f.isRepeated, + explicitPresence: f.explicitPresence, }; } return { @@ -99,6 +100,7 @@ export function monomorphizeTypeNode( isMessage: false, isOptional: f.isOptional, isRepeated: f.isRepeated, + explicitPresence: f.explicitPresence, }; }); diff --git a/packages/proton/src/ast/types.ts b/packages/proton/src/ast/types.ts index 37f80ea2..a95dfa18 100644 --- a/packages/proton/src/ast/types.ts +++ b/packages/proton/src/ast/types.ts @@ -13,6 +13,14 @@ export interface ProtobufField { isMessage: boolean; isOptional: boolean; isRepeated: boolean; + /** + * Explicit presence (proto3 `optional`), set only by the `pb_optional<>` + * marker. When true, a scalar field serialises even at its zero/default + * value. Distinct from `isOptional` (which merely tracks the TS `?` and is + * true for almost every field) — the encoder keys off THIS flag, never + * `isOptional`, so existing `pb<>` fields are unaffected. + */ + explicitPresence: boolean; } export interface ProtobufMessage { @@ -34,6 +42,8 @@ export interface GenericFieldTemplate { isTypeParam: boolean; isOptional: boolean; isRepeated: boolean; + /** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */ + explicitPresence: boolean; /** * For fields whose type-arg is itself a generic instantiation * (e.g. `wrapped: pb<5, Wrapper>` where `U` is a template type @@ -70,3 +80,4 @@ export const PRIMITIVE_TYPE_MAP: Record` scalar → serialise even at the zero value (proto3 explicit + // presence). Message fields already emit on `!= null`, so they stay on the + // default path; only scalars need the dedicated guard. Every `pb<>` / + // `pb_repeated<>` field has `explicitPresence === false` and so takes the + // untouched branches below — their generated code is byte-for-byte unchanged. + if (field.explicitPresence && !isMessage) { + return buildExplicitPresenceScalarBlock(field, index); + } const valueVar = `_f${index}`; const cacheVar = `_c${index}`; const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; @@ -318,6 +326,221 @@ function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock { return { declare: [], size: [], write: [] }; } +/** + * Encoder block for a singular scalar field marked `pb_optional<>` (proto3 + * explicit presence). Identical to the default scalar paths EXCEPT the guard + * is `!= null` instead of `!= null && !== `, so the field — and a + * `bool`'s real value — is written even when zero/false/empty. Reached only + * when `field.explicitPresence === true`, so default `pb<>` fields never run + * this code. + */ +function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock { + const { name, fieldNumber, typeName, wireType } = field; + const valueVar = `_f${index}`; + const cacheVar = `_c${index}`; + const isLenDelim = typeName === 'string' || typeName === 'bytes'; + const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length; + const declareVal = ` const ${valueVar} = obj.${name};`; + const present = `${valueVar} != null`; + + if (typeName === 'string') { + return { + declare: [declareVal, ` let ${cacheVar};`], + size: [ + ` if (${present}) {`, + ` ${cacheVar} = __utf8Len(${valueVar});`, + ` const _len = ${cacheVar};`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${cacheVar};`, + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (typeName === 'bytes') { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _len = ${valueVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${valueVar}.length;`, + writeVarint('_len', ' '), + ` buf.set(${valueVar}, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } + + if (typeName === 'bool') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 1};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = ${valueVar} ? 1 : 0;`, + ` }`, + ], + }; + } + + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, valueVar); + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ], + write: [ + ` if (${present}) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ], + }; + } + + if (typeName === 'sint_32') { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), + ` }`, + ], + }; + } + + if (wireType === WireType.Varint) { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ${valueVar} >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${valueVar} >>> 0`, ' '), + ` }`, + ], + }; + } + + if (typeName === 'float') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 4};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit32) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 4};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ], + }; + } + + if (typeName === 'double') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (isFixed64BigInt(typeName)) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit64) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ], + }; + } + + return { declare: [], size: [], write: [] }; +} + function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock { const { name, fieldNumber, typeName, wireType, isMessage } = field; const arrayVar = `_f${index}`; diff --git a/packages/proton/src/runtime-map.ts b/packages/proton/src/runtime-map.ts index 8406d194..00f48cd0 100644 --- a/packages/proton/src/runtime-map.ts +++ b/packages/proton/src/runtime-map.ts @@ -25,6 +25,7 @@ function cloneField(field: ProtobufField): ProtobufField { isMessage: field.isMessage, isOptional: field.isOptional, isRepeated: field.isRepeated, + explicitPresence: field.explicitPresence ?? false, }; } diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index 31c543be..09fc54f8 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -139,3 +139,43 @@ interface DoubleMsg { expect(result.values[1]).toBeCloseTo(-0.5); }); }); + +describe('pb_optional explicit presence', () => { + it('serialises a zero scalar (where pb<> would omit it)', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface OptMsg { forced: pb_optional<1, uint_32>; }`, + 'OptMsg', + ); + // field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty). + expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]); + expect(dec(enc({ forced: 0 })).forced).toBe(0); + }); + + it('still omits the field when the value is absent (undefined)', () => { + const { enc } = makeRoundTripFromSchema( + `interface OptMsg2 { forced: pb_optional<1, uint_32>; }`, + 'OptMsg2', + ); + expect(enc({}).length).toBe(0); + }); + + it('does not change a sibling plain pb<> field (it still omits its zero)', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`, + 'MixMsg', + ); + // plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10). + expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]); + expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 }); + }); + + it('forces a false bool onto the wire', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface BoolOpt { flag: pb_optional<1, bool>; }`, + 'BoolOpt', + ); + expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]); + expect(dec(enc({ flag: false })).flag).toBe(false); + expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]); + }); +});