@@ -34,11 +34,20 @@ type QuickReply = messagingApi.QuickReply;
3434type QuickReplyItem = messagingApi . QuickReplyItem ;
3535type LineLocation = NonNullable < LineChannelData [ "location" ] > ;
3636
37- const userProfileCache = new Map <
38- string ,
39- { displayName : string ; pictureUrl ?: string ; fetchedAt : number }
40- > ( ) ;
41- const groupNameCache = new Map < string , { groupName : string ; fetchedAt : number } > ( ) ;
37+ type LineUserProfile = { displayName : string ; pictureUrl ?: string } ;
38+ type LineIdentityCache < T > = {
39+ values : Map < string , { value : T ; fetchedAt : number } > ;
40+ pending : Map < string , Promise < T > > ;
41+ } ;
42+
43+ const profileCache : LineIdentityCache < LineUserProfile | null > = {
44+ values : new Map ( ) ,
45+ pending : new Map ( ) ,
46+ } ;
47+ const groupNameCache : LineIdentityCache < string | undefined > = {
48+ values : new Map ( ) ,
49+ pending : new Map ( ) ,
50+ } ;
4251const PROFILE_CACHE_TTL_MS = 5 * 60 * 1000 ;
4352const PROFILE_CACHE_MAX_ENTRIES = 1000 ;
4453const LINE_FLEX_ALT_TEXT_LIMIT = 1500 ;
@@ -48,30 +57,47 @@ const LINE_LOCATION_LABEL_LIMIT = 100;
4857const LINE_PROVIDER_RESPONSE_MAX_BYTES = 16 * 1024 ;
4958
5059// Refresh insertion order so overflow evicts expired entries first, then the oldest live fetch.
51- function rememberLineIdentity < T extends { fetchedAt : number } > (
52- cache : Map < string , T > ,
53- key : string ,
54- value : T ,
55- ) : void {
56- cache . delete ( key ) ;
57- cache . set ( key , value ) ;
58- if ( cache . size <= PROFILE_CACHE_MAX_ENTRIES ) {
60+ function rememberLineIdentity < T > ( cache : LineIdentityCache < T > , key : string , value : T ) : void {
61+ const entry = { value, fetchedAt : Date . now ( ) } ;
62+ cache . values . delete ( key ) ;
63+ cache . values . set ( key , entry ) ;
64+ if ( cache . values . size <= PROFILE_CACHE_MAX_ENTRIES ) {
5965 return ;
6066 }
61- for ( const [ cachedKey , cached ] of cache ) {
62- if ( value . fetchedAt - cached . fetchedAt >= PROFILE_CACHE_TTL_MS ) {
63- cache . delete ( cachedKey ) ;
67+ for ( const [ cachedKey , cached ] of cache . values ) {
68+ if ( entry . fetchedAt - cached . fetchedAt >= PROFILE_CACHE_TTL_MS ) {
69+ cache . values . delete ( cachedKey ) ;
6470 }
6571 }
66- pruneMapToMaxSize ( cache , PROFILE_CACHE_MAX_ENTRIES ) ;
72+ pruneMapToMaxSize ( cache . values , PROFILE_CACHE_MAX_ENTRIES ) ;
6773}
6874
69- function readLineIdentityCache < T extends { fetchedAt : number } > (
70- cache : Map < string , T > ,
75+ async function loadLineIdentity < T > (
76+ cache : LineIdentityCache < T > ,
7177 key : string ,
72- ) : T | undefined {
73- const cached = cache . get ( key ) ;
74- return cached && Date . now ( ) - cached . fetchedAt < PROFILE_CACHE_TTL_MS ? cached : undefined ;
78+ load : ( ) => Promise < T > ,
79+ ) : Promise < T > {
80+ const cached = cache . values . get ( key ) ;
81+ if ( cached && Date . now ( ) - cached . fetchedAt < PROFILE_CACHE_TTL_MS ) {
82+ return cached . value ;
83+ }
84+ const pending = cache . pending . get ( key ) ;
85+ if ( pending ) {
86+ return await pending ;
87+ }
88+ const lookup = load ( ) . then ( ( value ) => {
89+ rememberLineIdentity ( cache , key , value ) ;
90+ return value ;
91+ } ) ;
92+ cache . pending . set ( key , lookup ) ;
93+ pruneMapToMaxSize ( cache . pending , PROFILE_CACHE_MAX_ENTRIES ) ;
94+ try {
95+ return await lookup ;
96+ } finally {
97+ if ( cache . pending . get ( key ) === lookup ) {
98+ cache . pending . delete ( key ) ;
99+ }
100+ }
75101}
76102
77103interface LineSendOpts {
@@ -641,16 +667,21 @@ export async function showLoadingAnimation(
641667 }
642668}
643669
644- async function getLineGroupSummary (
645- groupId : string ,
646- opts : LineClientOpts ,
647- ) : Promise < messagingApi . GroupSummaryResponse > {
648- const { client } = createLineMessagingClient ( opts ) ;
649- return await client . getGroupSummary ( groupId ) ;
650- }
651-
652670export type LineConversationScope = { groupId ?: string ; roomId ?: string } ;
653671
672+ function lineProfileCacheKey (
673+ accountId : string ,
674+ userId : string ,
675+ scope : LineConversationScope ,
676+ ) : string {
677+ const conversation = scope . groupId
678+ ? [ "group" , scope . groupId ]
679+ : scope . roomId
680+ ? [ "room" , scope . roomId ]
681+ : [ "direct" ] ;
682+ return JSON . stringify ( [ accountId , "profile" , ...conversation , userId ] ) ;
683+ }
684+
654685// A group or room member who has not added the bot as a friend is invisible to
655686// the plain profile endpoint, so the sender's conversation decides which one can
656687// answer. Reading the wrong one returns 404 for exactly the people whose names
@@ -672,33 +703,29 @@ function fetchLineMemberProfile(
672703export async function getUserProfile (
673704 userId : string ,
674705 opts : LineClientOpts & { useCache ?: boolean } & LineConversationScope ,
675- ) : Promise < { displayName : string ; pictureUrl ?: string } | null > {
706+ ) : Promise < LineUserProfile | null > {
676707 const useCache = opts . useCache ?? true ;
677-
678- if ( useCache ) {
679- const cached = readLineIdentityCache ( userProfileCache , userId ) ;
680- if ( cached ) {
681- return { displayName : cached . displayName , pictureUrl : cached . pictureUrl } ;
682- }
683- }
684-
685708 try {
686- // Client construction resolves the account token and can throw, so it stays
687- // inside the guard: an unresolvable name degrades to the raw id, never to a
688- // failed inbound turn.
689- const { client } = createLineMessagingClient ( opts ) ;
690- const profile = await fetchLineMemberProfile ( client , userId , opts ) ;
691- const result = {
692- displayName : profile . displayName ,
693- pictureUrl : profile . pictureUrl ,
709+ // Client construction resolves the canonical account for the cache key and
710+ // can throw; an unresolvable name must never cost the inbound turn.
711+ const { account, token } = resolveLineMessagingAccount ( opts ) ;
712+ const cacheKey = lineProfileCacheKey ( account . accountId , userId , opts ) ;
713+ const load = async ( ) => {
714+ try {
715+ const client = new messagingApi . MessagingApiClient ( { channelAccessToken : token } ) ;
716+ const profile = await fetchLineMemberProfile ( client , userId , opts ) ;
717+ return { displayName : profile . displayName , pictureUrl : profile . pictureUrl } ;
718+ } catch ( err ) {
719+ logVerbose ( `line: failed to fetch profile for ${ userId } : ${ String ( err ) } ` ) ;
720+ return null ;
721+ }
694722 } ;
695-
696- rememberLineIdentity ( userProfileCache , userId , {
697- ...result ,
698- fetchedAt : Date . now ( ) ,
699- } ) ;
700-
701- return result ;
723+ if ( ! useCache ) {
724+ const profile = await load ( ) ;
725+ rememberLineIdentity ( profileCache , cacheKey , profile ) ;
726+ return profile ;
727+ }
728+ return await loadLineIdentity ( profileCache , cacheKey , load ) ;
702729 } catch ( err ) {
703730 logVerbose ( `line: failed to fetch profile for ${ userId } : ${ String ( err ) } ` ) ;
704731 return null ;
@@ -719,18 +746,19 @@ export async function getLineGroupName(
719746 groupId : string ,
720747 opts : LineClientOpts ,
721748) : Promise < string | undefined > {
722- const cached = readLineIdentityCache ( groupNameCache , groupId ) ;
723- if ( cached ) {
724- return cached . groupName ;
725- }
726749 try {
727- const summary = await getLineGroupSummary ( groupId , opts ) ;
728- const groupName = summary . groupName . trim ( ) ;
729- if ( ! groupName ) {
730- return undefined ;
731- }
732- rememberLineIdentity ( groupNameCache , groupId , { groupName, fetchedAt : Date . now ( ) } ) ;
733- return groupName ;
750+ const { account, token } = resolveLineMessagingAccount ( opts ) ;
751+ const cacheKey = JSON . stringify ( [ account . accountId , "group" , groupId ] ) ;
752+ return await loadLineIdentity ( groupNameCache , cacheKey , async ( ) => {
753+ try {
754+ const client = new messagingApi . MessagingApiClient ( { channelAccessToken : token } ) ;
755+ const summary = await client . getGroupSummary ( groupId ) ;
756+ return summary . groupName . trim ( ) || undefined ;
757+ } catch ( err ) {
758+ logVerbose ( `line: failed to fetch group summary for ${ groupId } : ${ String ( err ) } ` ) ;
759+ return undefined ;
760+ }
761+ } ) ;
734762 } catch ( err ) {
735763 logVerbose ( `line: failed to fetch group summary for ${ groupId } : ${ String ( err ) } ` ) ;
736764 return undefined ;
0 commit comments