larksuite/oapi-sdk-go

An endless loop caused by an iterator

Opened this issue · 0 comments

SDK: github.com/larksuite/oapi-sdk-go/v3 v3.2.7

issue code

func QueryAllChat() (list []*larkim.ListChat, err error) {
	list = make([]*larkim.ListChat, 0, defaultGroupCnt)
	req := larkim.NewListChatReqBuilder().
		SortType(`ByCreateTimeAsc`).
		PageSize(20).
		Build()

	iterator, err := component.LarkCli.Im.Chat.ListByIterator(defCtx, req)
	if err != nil {
		return
	}

	for {
		hasNext, chat, thisErr := iterator.Next()
		if thisErr != nil {
			err = thisErr
			return
		}

		if !hasNext {
			break
		}

		if chat != nil {
			list = append(list, chat)
		}
	}
	return
}

log

2024-07-06T01:27:12.399+0800    DEBUG   warp_feishu/logger.go:12        req:POST,/open-apis/auth/v3/tenant_access_token/internal
2024-07-06T01:27:12.891+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:13.158+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:13.549+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:13.811+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:14.039+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:14.277+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:14.521+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:14.780+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats
2024-07-06T01:27:15.029+0800    DEBUG   warp_feishu/logger.go:12        req:GET,/open-apis/im/v1/chats

conjecture

# github.com/larksuite/oapi-sdk-go/v3@v3.2.7/service/im/v1/model.go:12076

...
	// 为0则拉取数据
	if iterator.index == 0 || iterator.index >= len(iterator.items) {
		if iterator.index != 0 && iterator.nextPageToken == nil {
			return false, nil, nil
		}
		if iterator.nextPageToken != nil {
			iterator.req.apiReq.QueryParams.Set("page_token", *iterator.nextPageToken)
		}
		resp, err := iterator.listFunc(iterator.ctx, iterator.req, iterator.options...)
		if err != nil {
			return false, nil, err
		}

		if resp.Code != 0 {
			return false, nil, errors.New(fmt.Sprintf("Code:%d,Msg:%s", resp.Code, resp.Msg))
		}

		if len(resp.Data.Items) == 0 {
			return false, nil, nil
		}

		iterator.nextPageToken = resp.Data.PageToken
		iterator.items = resp.Data.Items
		iterator.index = 0
	}
...

当列表仅有一页数据,此时接口返回 pageToken 空,hasMore false

iterator 并没有保存 hasMore 状态,进入死循环

image