chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)
This commit is contained in:
commit
9097ee699d
5769 files changed
+1446466
No files matched your search
@@ -0,0 +1,199 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const attachmentPageEditTime = "2026-10-03T10:00:00Z"
|
||||
|
||||
const attachmentPageJSON = `{"id":"page","object":"page","url":"https://notion.so/page",` +
|
||||
`"last_edited_time":"` + attachmentPageEditTime + `","parent":{"type":"workspace"},` +
|
||||
`"properties":{"title":{"type":"title","title":[{"plain_text":"Attachment page"}]}}}`
|
||||
|
||||
// attachmentRetryFixture serves a single page whose whole content is one pdf
|
||||
// block. The attachment URL keeps answering 500 until failing is cleared.
|
||||
type attachmentRetryFixture struct {
|
||||
baseURL string
|
||||
attachmentURL string
|
||||
failing atomic.Bool
|
||||
blockFetches atomic.Int32
|
||||
downloads atomic.Int32
|
||||
}
|
||||
|
||||
func (f *attachmentRetryFixture) serve(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/v1/search":
|
||||
_, _ = fmt.Fprint(w, `{"results":[`+attachmentPageJSON+`],"has_more":false}`)
|
||||
case "/v1/pages/page":
|
||||
_, _ = fmt.Fprint(w, attachmentPageJSON)
|
||||
case "/v1/blocks/page/children":
|
||||
f.blockFetches.Add(1)
|
||||
_, _ = fmt.Fprintf(w, `{"results":[{"id":"pdf-block","type":"pdf","pdf":{"type":"file",`+
|
||||
`"name":"reference.pdf","file":{"url":%q,"expiry_time":"2030-01-01T00:00:00Z"}}}],`+
|
||||
`"has_more":false}`, f.attachmentURL)
|
||||
case "/att.pdf":
|
||||
f.downloads.Add(1)
|
||||
if f.failing.Load() {
|
||||
http.Error(w, "storage unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte("%PDF-1.4 recovered attachment"))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func newAttachmentRetryFixture(t *testing.T) (*attachmentRetryFixture, *types.DataSourceConfig) {
|
||||
t.Helper()
|
||||
allowNotionTestServer(t)
|
||||
fixture := &attachmentRetryFixture{}
|
||||
fixture.failing.Store(true)
|
||||
server := httptest.NewServer(http.HandlerFunc(fixture.serve))
|
||||
t.Cleanup(server.Close)
|
||||
fixture.baseURL = server.URL
|
||||
fixture.attachmentURL = server.URL + "/att.pdf"
|
||||
return fixture, makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page"})
|
||||
}
|
||||
|
||||
// fileUploadRetryFixture serves a page whose only file block is a file_upload
|
||||
// that the source refuses to resolve.
|
||||
type fileUploadRetryFixture struct {
|
||||
blockFetches atomic.Int32
|
||||
}
|
||||
|
||||
func (f *fileUploadRetryFixture) serve(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/v1/search":
|
||||
_, _ = fmt.Fprint(w, `{"results":[`+attachmentPageJSON+`],"has_more":false}`)
|
||||
case "/v1/pages/page":
|
||||
_, _ = fmt.Fprint(w, attachmentPageJSON)
|
||||
case "/v1/blocks/page/children":
|
||||
f.blockFetches.Add(1)
|
||||
_, _ = fmt.Fprint(w, `{"results":[{"id":"upload-block","type":"file","file":`+
|
||||
`{"type":"file_upload","name":"uploaded.pdf","file_upload":{"id":"upload-1"}}}],`+
|
||||
`"has_more":false}`)
|
||||
case "/v1/blocks/upload-block":
|
||||
http.Error(w, "block unavailable", http.StatusNotFound)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func newFileUploadRetryFixture(t *testing.T) (*fileUploadRetryFixture, *types.DataSourceConfig) {
|
||||
t.Helper()
|
||||
allowNotionTestServer(t)
|
||||
fixture := &fileUploadRetryFixture{}
|
||||
server := httptest.NewServer(http.HandlerFunc(fixture.serve))
|
||||
t.Cleanup(server.Close)
|
||||
return fixture, makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page"})
|
||||
}
|
||||
|
||||
// A page that cannot store one of its attachments must not be reported as a
|
||||
// complete fetch: the caller would otherwise persist the page edit time and the
|
||||
// attachment would stay missing until a full re-sync.
|
||||
func TestNotionAttachmentDownloadFailureFailsPageFetch(t *testing.T) {
|
||||
fixture, _ := newAttachmentRetryFixture(t)
|
||||
client := mustTestClient(t, "test-token", fixture.baseURL)
|
||||
page, err := client.GetPage(context.Background(), "page")
|
||||
require.NoError(t, err)
|
||||
items, truncated, err := NewConnector().fetchPage(
|
||||
context.Background(), client, page, map[string]bool{})
|
||||
if err == nil && !truncated {
|
||||
t.Fatalf("fetchPage reported a complete fetch (truncated=false, err=nil) after the attachment download failed")
|
||||
}
|
||||
require.Error(t, err, "a failed attachment download must abort the page fetch")
|
||||
require.Nil(t, items)
|
||||
require.Positive(t, fixture.downloads.Load())
|
||||
}
|
||||
|
||||
// The sync loop persists the cursor of a round that reported success, so an
|
||||
// attachment failure must leave the page edit time unacknowledged and the next
|
||||
// round must fetch the unchanged page again.
|
||||
func TestNotionAttachmentFailurePreservesRetry(t *testing.T) {
|
||||
fixture, config := newAttachmentRetryFixture(t)
|
||||
connector := NewConnector()
|
||||
previous := buildCursor(map[string]time.Time{"page": time.Date(2026, 10, 2, 10, 0, 0, 0, time.UTC)})
|
||||
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.Error(t, err, "a failed attachment download must fail the round")
|
||||
require.Nil(t, items, "a failed download must not emit a partial page")
|
||||
require.Nil(t, next, "a failed download must not acknowledge the page edit time")
|
||||
|
||||
cursor := previous
|
||||
if next != nil {
|
||||
cursor = next
|
||||
}
|
||||
items, next, err = connector.FetchIncremental(context.Background(), config, cursor)
|
||||
require.Error(t, err, "the second round must retry the page whose attachment is still missing")
|
||||
require.Nil(t, items)
|
||||
require.Nil(t, next)
|
||||
require.GreaterOrEqual(t, fixture.blockFetches.Load(), int32(2),
|
||||
"the unchanged page must be fetched again until its attachment is stored")
|
||||
}
|
||||
|
||||
// Once the source serves the attachment, the retried page must be ingested with
|
||||
// its attachment and only then acknowledged.
|
||||
func TestNotionAttachmentStoredAfterDownloadRecovers(t *testing.T) {
|
||||
fixture, config := newAttachmentRetryFixture(t)
|
||||
connector := NewConnector()
|
||||
previous := buildCursor(map[string]time.Time{"page": time.Date(2026, 10, 2, 10, 0, 0, 0, time.UTC)})
|
||||
|
||||
_, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, next)
|
||||
|
||||
fixture.failing.Store(false)
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, next)
|
||||
|
||||
var foundPage, foundAttachment bool
|
||||
for _, item := range items {
|
||||
if item.ExternalID == "page" && !item.IsDeleted {
|
||||
foundPage = true
|
||||
}
|
||||
if item.Metadata["object_type"] == objectTypeAttachment {
|
||||
foundAttachment = true
|
||||
require.Equal(t, "reference.pdf", item.FileName)
|
||||
require.Contains(t, string(item.Content), "recovered attachment")
|
||||
}
|
||||
}
|
||||
require.True(t, foundPage, "the page markdown must be emitted once the round succeeds")
|
||||
require.True(t, foundAttachment, "the recovered attachment must be emitted")
|
||||
|
||||
items, _, err = connector.FetchIncremental(context.Background(), config, next)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, items, "an acknowledged page must not be fetched again")
|
||||
require.Equal(t, int32(2), fixture.blockFetches.Load())
|
||||
}
|
||||
|
||||
// An unresolved file_upload leaves the file URL empty, which silently drops the
|
||||
// attachment the same way a failed download does.
|
||||
func TestNotionFileUploadResolutionFailurePreservesRetry(t *testing.T) {
|
||||
fixture, config := newFileUploadRetryFixture(t)
|
||||
connector := NewConnector()
|
||||
previous := buildCursor(map[string]time.Time{"page": time.Date(2026, 10, 2, 10, 0, 0, 0, time.UTC)})
|
||||
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.Error(t, err, "an unresolved file_upload must fail the round")
|
||||
require.Nil(t, items)
|
||||
require.Nil(t, next)
|
||||
|
||||
items, next, err = connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.Error(t, err, "the second round must retry the page whose file_upload is unresolved")
|
||||
require.Nil(t, items)
|
||||
require.Nil(t, next)
|
||||
require.GreaterOrEqual(t, fixture.blockFetches.Load(), int32(2))
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const retryPageTime = "2026-09-24T10:00:00Z"
|
||||
|
||||
type blockRetryFixture struct {
|
||||
failed atomic.Bool
|
||||
calls atomic.Int32
|
||||
mode string
|
||||
}
|
||||
|
||||
func (f *blockRetryFixture) serve(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/v1/search":
|
||||
_, _ = w.Write([]byte(`{"results":[` + retryPage("page", "workspace") + `],"has_more":false}`))
|
||||
case "/v1/pages/page":
|
||||
_, _ = w.Write([]byte(retryPage("page", "workspace")))
|
||||
case "/v1/pages/healthy":
|
||||
_, _ = w.Write([]byte(retryPage("healthy", "workspace")))
|
||||
case "/v1/pages/child":
|
||||
_, _ = w.Write([]byte(retryPage("child", "page_id")))
|
||||
case "/v1/blocks/page/children":
|
||||
f.pageBlocks(w, r)
|
||||
case "/v1/blocks/child/children":
|
||||
f.content(w)
|
||||
case "/v1/blocks/healthy/children":
|
||||
_, _ = w.Write([]byte(`{"results":[{"id":"text","type":"paragraph","paragraph":{"rich_text":[` +
|
||||
`{"type":"text","text":{"content":"healthy content"},"plain_text":"healthy content"}]}}]}`))
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func retryPage(id, parentType string) string {
|
||||
return `{"id":"` + id + `","object":"page","last_edited_time":"` + retryPageTime +
|
||||
`","parent":{"type":"` + parentType + `","page_id":"page"}}`
|
||||
}
|
||||
|
||||
func (f *blockRetryFixture) pageBlocks(w http.ResponseWriter, r *http.Request) {
|
||||
switch f.mode {
|
||||
case "child":
|
||||
_, _ = w.Write([]byte(`{"results":[{"id":"child","type":"child_page",` +
|
||||
`"child_page":{"title":"Child"}}],"has_more":false}`))
|
||||
case "later_page":
|
||||
if r.URL.Query().Get("start_cursor") == "later" {
|
||||
f.content(w)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"results":[],"has_more":true,"next_cursor":"later"}`))
|
||||
case "empty":
|
||||
_, _ = w.Write([]byte(`{"results":[],"has_more":false}`))
|
||||
default:
|
||||
f.content(w)
|
||||
}
|
||||
}
|
||||
|
||||
func (f *blockRetryFixture) content(w http.ResponseWriter) {
|
||||
f.calls.Add(1)
|
||||
if f.failed.Load() {
|
||||
status := http.StatusUnauthorized
|
||||
if f.mode == "server_error" {
|
||||
status = http.StatusServiceUnavailable
|
||||
}
|
||||
w.WriteHeader(status)
|
||||
_, _ = w.Write([]byte(`{"code":"unauthorized","message":"test block request rejected"}`))
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(`{"results":[{"id":"text","type":"paragraph","paragraph":{"rich_text":[` +
|
||||
`{"type":"text","text":{"content":"recovered content"},"plain_text":"recovered content"}` +
|
||||
`]}}],"has_more":false}`))
|
||||
}
|
||||
|
||||
func newBlockRetryFixture(t *testing.T, mode string) (*blockRetryFixture, *types.DataSourceConfig) {
|
||||
t.Helper()
|
||||
allowNotionTestServer(t)
|
||||
fixture := &blockRetryFixture{mode: mode}
|
||||
fixture.failed.Store(true)
|
||||
server := httptest.NewServer(http.HandlerFunc(fixture.serve))
|
||||
t.Cleanup(server.Close)
|
||||
return fixture, makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page"})
|
||||
}
|
||||
|
||||
func TestNotionBlockFailurePreservesRetry(t *testing.T) {
|
||||
for _, mode := range []string{"page", "server_error", "later_page", "child"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
fixture, config := newBlockRetryFixture(t, mode)
|
||||
oldTime := time.Date(2026, 9, 23, 10, 0, 0, 0, time.UTC)
|
||||
previous := buildCursor(map[string]time.Time{"page": oldTime, "removed": oldTime})
|
||||
before, err := json.Marshal(previous)
|
||||
require.NoError(t, err)
|
||||
connector := NewConnector()
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.ErrorContains(t, err, "get blocks")
|
||||
require.Nil(t, items, "failed traversal must not emit content or deletion events")
|
||||
require.Nil(t, next, "failed traversal must not acknowledge the new edit time")
|
||||
after, marshalErr := json.Marshal(previous)
|
||||
require.NoError(t, marshalErr)
|
||||
require.Equal(t, before, after)
|
||||
require.Positive(t, fixture.calls.Load())
|
||||
|
||||
fixture.failed.Store(false)
|
||||
items, next, err = connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, next)
|
||||
var foundContent, foundDeletion bool
|
||||
for _, item := range items {
|
||||
foundContent = foundContent || strings.Contains(string(item.Content), "recovered content")
|
||||
foundDeletion = foundDeletion || (item.ExternalID == "removed" && item.IsDeleted)
|
||||
}
|
||||
require.True(t, foundContent, "recovered page must be fetched without another source edit")
|
||||
require.True(t, foundDeletion, "successful traversal must still detect actual deletions")
|
||||
calls := fixture.calls.Load()
|
||||
items, _, err = connector.FetchIncremental(context.Background(), config, next)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, items)
|
||||
require.Equal(t, calls, fixture.calls.Load(), "unchanged page must not be fetched again")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotionFirstSyncRejectsBlockFailure(t *testing.T) {
|
||||
fixture, config := newBlockRetryFixture(t, "page")
|
||||
connector := NewConnector()
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, nil)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, items)
|
||||
require.Nil(t, next, "first sync must not substitute time.Now for a failed page")
|
||||
fixture.failed.Store(false)
|
||||
items, next, err = connector.FetchIncremental(context.Background(), config, nil)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.NotNil(t, next)
|
||||
}
|
||||
|
||||
func TestNotionFullSyncRejectsBlockFailure(t *testing.T) {
|
||||
_, config := newBlockRetryFixture(t, "child")
|
||||
config.ResourceIDs = []string{"healthy", "page"}
|
||||
items, err := NewConnector().FetchAll(context.Background(), config, config.ResourceIDs)
|
||||
require.Error(t, err)
|
||||
require.Nil(t, items, "discard earlier successful items when a later page fails")
|
||||
}
|
||||
|
||||
func TestNotionEmptyPageStillSucceeds(t *testing.T) {
|
||||
_, config := newBlockRetryFixture(t, "empty")
|
||||
previous := buildCursor(map[string]time.Time{"page": {}})
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, previous)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "page", items[0].ExternalID)
|
||||
require.False(t, items[0].IsDeleted)
|
||||
require.Equal(t, "# "+defaultUntitledName+"\n", string(items[0].Content))
|
||||
require.NotNil(t, next)
|
||||
}
|
||||
@@ -0,0 +1,826 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
// notionClient wraps the Notion API with rate limiting and retry logic.
|
||||
type notionClient struct {
|
||||
token string
|
||||
httpClient *http.Client
|
||||
limiter *rate.Limiter
|
||||
baseURL string
|
||||
// jsonLimit caps each API response body; a field so tests can lower it
|
||||
// without materialising the production limit.
|
||||
jsonLimit int64
|
||||
}
|
||||
|
||||
// maxJSONResponseBytes bounds every API response body. Page and block payloads
|
||||
// are small; a larger body means a broken or hostile server.
|
||||
const maxJSONResponseBytes = 16 << 20
|
||||
|
||||
// errResponseTooLarge marks a body over the cap. It is deterministic: the same
|
||||
// request returns the same oversized body, so callers must not retry it.
|
||||
var errResponseTooLarge = errors.New("response exceeds maximum size")
|
||||
|
||||
// readCapped reads a response body, refusing anything larger than limit instead
|
||||
// of buffering it. Oversized payloads are reported as an error: a truncated
|
||||
// body would be indexed as if it were the whole document. A non-positive limit
|
||||
// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.
|
||||
func readCapped(body io.Reader, limit int64) ([]byte, error) {
|
||||
if limit <= 0 {
|
||||
limit = maxJSONResponseBytes
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(body, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// newClient creates a new Notion API client.
|
||||
func newClient(token, baseURL string) (*notionClient, error) {
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultBaseURL
|
||||
}
|
||||
if err := datasource.ValidateConnectorBaseURL(baseURL); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ¬ionClient{
|
||||
token: token,
|
||||
httpClient: datasource.NewConnectorHTTPClient(30 * time.Second),
|
||||
limiter: rate.NewLimiter(rate.Limit(3), 3),
|
||||
baseURL: baseURL,
|
||||
jsonLimit: maxJSONResponseBytes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
const maxRetries = 3
|
||||
|
||||
// sleepWithContext pauses for the given duration, returning early if ctx is cancelled.
|
||||
func sleepWithContext(ctx context.Context, d time.Duration) error {
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-t.C:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// doRequest performs an authenticated, rate-limited HTTP request to the Notion API.
|
||||
func (c *notionClient) doRequest(ctx context.Context, method, path string, body interface{}) ([]byte, error) {
|
||||
if err := c.limiter.Wait(ctx); err != nil {
|
||||
return nil, fmt.Errorf("rate limiter: %w", err)
|
||||
}
|
||||
|
||||
var bodyReader io.Reader
|
||||
if body != nil {
|
||||
bodyBytes, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("marshal request body: %w", err)
|
||||
}
|
||||
bodyReader = bytes.NewReader(bodyBytes)
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, bodyReader)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||||
req.Header.Set("Notion-Version", NotionAPIVersion)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
if attempt > 0 {
|
||||
if body != nil {
|
||||
bodyBytes, _ := json.Marshal(body)
|
||||
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepWithContext(ctx, time.Duration(1<<attempt)*time.Second); sErr != nil {
|
||||
return nil, sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
respBody, err := readCapped(resp.Body, c.jsonLimit)
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case resp.StatusCode >= 200 && resp.StatusCode < 300:
|
||||
return respBody, nil
|
||||
|
||||
case resp.StatusCode == 401 || resp.StatusCode == 403:
|
||||
return nil, fmt.Errorf("%w: %s", datasource.ErrInvalidCredentials, string(respBody))
|
||||
|
||||
case resp.StatusCode == 404:
|
||||
return nil, fmt.Errorf("%w: %s", datasource.ErrResourceNotFound, path)
|
||||
|
||||
case resp.StatusCode == 429:
|
||||
retryAfter := resp.Header.Get("Retry-After")
|
||||
wait := 1 * time.Second
|
||||
if secs, err := strconv.ParseFloat(retryAfter, 64); err == nil && secs > 0 {
|
||||
wait = time.Duration(secs * float64(time.Second))
|
||||
}
|
||||
logger.Warnf(ctx, "[Notion] rate limited, retry after %v (attempt %d/%d)", wait, attempt+1, maxRetries)
|
||||
lastErr = fmt.Errorf("rate limited: %s", string(respBody))
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepWithContext(ctx, wait); sErr != nil {
|
||||
return nil, sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
case resp.StatusCode >= 500:
|
||||
lastErr = fmt.Errorf("server error %d: %s", resp.StatusCode, string(respBody))
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepWithContext(ctx, time.Duration(1<<attempt)*time.Second); sErr != nil {
|
||||
return nil, sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
}
|
||||
|
||||
if lastErr != nil {
|
||||
return nil, fmt.Errorf("%w: %v", datasource.ErrFetchFailed, lastErr)
|
||||
}
|
||||
return nil, datasource.ErrFetchFailed
|
||||
}
|
||||
|
||||
// Ping verifies the API token is valid by calling GET /v1/users/me.
|
||||
func (c *notionClient) Ping(ctx context.Context) error {
|
||||
_, err := c.doRequest(ctx, http.MethodGet, "/v1/users/me", nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// SearchPages returns all pages and databases accessible to the integration.
|
||||
func (c *notionClient) SearchPages(ctx context.Context) ([]notionPage, error) {
|
||||
return c.paginatePages(ctx, http.MethodPost, "/v1/search")
|
||||
}
|
||||
|
||||
// GetPage retrieves a single page by ID.
|
||||
func (c *notionClient) GetPage(ctx context.Context, pageID string) (*notionPage, error) {
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, "/v1/pages/"+pageID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var page notionPage
|
||||
if err := json.Unmarshal(respBody, &page); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal page: %w", err)
|
||||
}
|
||||
page.Title = extractTitle(&page)
|
||||
return &page, nil
|
||||
}
|
||||
|
||||
// databaseInfo holds both the metadata and the data source ID from a single API call.
|
||||
type databaseInfo struct {
|
||||
Page notionPage
|
||||
DataSourceID string
|
||||
}
|
||||
|
||||
// GetDatabaseInfo retrieves a database container by ID, returning both
|
||||
// the page metadata and the primary data source ID in a single API call.
|
||||
func (c *notionClient) GetDatabaseInfo(ctx context.Context, dbID string) (*databaseInfo, error) {
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, "/v1/databases/"+dbID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var db notionPage
|
||||
if err := json.Unmarshal(respBody, &db); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal database: %w", err)
|
||||
}
|
||||
db.Title = extractTitle(&db)
|
||||
|
||||
var dsResult struct {
|
||||
DataSources []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"data_sources"`
|
||||
}
|
||||
if err := json.Unmarshal(respBody, &dsResult); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal data_sources: %w", err)
|
||||
}
|
||||
|
||||
dsID := ""
|
||||
if len(dsResult.DataSources) > 0 {
|
||||
dsID = dsResult.DataSources[0].ID
|
||||
}
|
||||
|
||||
return &databaseInfo{Page: db, DataSourceID: dsID}, nil
|
||||
}
|
||||
|
||||
// GetDataSourceInfo retrieves a data source by ID, returning its metadata.
|
||||
// In API 2025-09-03+, data_source objects hold the schema/properties and are
|
||||
// the target for record queries. The response includes database_parent to
|
||||
// locate the database in the workspace hierarchy.
|
||||
func (c *notionClient) GetDataSourceInfo(ctx context.Context, dsID string) (*notionPage, error) {
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, "/v1/data_sources/"+dsID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var ds notionPage
|
||||
if err := json.Unmarshal(respBody, &ds); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal data_source: %w", err)
|
||||
}
|
||||
ds.Title = extractTitle(&ds)
|
||||
return &ds, nil
|
||||
}
|
||||
|
||||
// GetBlockChildrenFlat fetches only the direct children of a block (no recursion).
|
||||
// Used by discoverPages to quickly scan for child_page/child_database without
|
||||
// fetching the full block tree content.
|
||||
func (c *notionClient) GetBlockChildrenFlat(ctx context.Context, blockID string) ([]notionBlock, error) {
|
||||
var allBlocks []notionBlock
|
||||
var startCursor string
|
||||
seenCursors := make(map[string]struct{})
|
||||
|
||||
for page := 1; ; page++ {
|
||||
path := fmt.Sprintf("/v1/blocks/%s/children", blockID)
|
||||
if startCursor != "" {
|
||||
path += "?start_cursor=" + startCursor
|
||||
}
|
||||
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get block children for %s: %w", blockID, err)
|
||||
}
|
||||
|
||||
var resp paginatedResponse
|
||||
if err := json.Unmarshal(respBody, &resp); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal block children response: %w", err)
|
||||
}
|
||||
|
||||
var blocks []notionBlock
|
||||
if err := json.Unmarshal(resp.Results, &blocks); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal blocks: %w", err)
|
||||
}
|
||||
|
||||
allBlocks = append(allBlocks, blocks...)
|
||||
|
||||
if !resp.HasMore || resp.NextCursor == "" {
|
||||
break
|
||||
}
|
||||
next, err := advancePaginationCursor(ctx, seenCursors, resp.NextCursor, page)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get block children for %s: %w", blockID, err)
|
||||
}
|
||||
startCursor = next
|
||||
}
|
||||
|
||||
return allBlocks, nil
|
||||
}
|
||||
|
||||
const maxBlockDepth = 5 // Limit recursion depth — deeper content has diminishing value for knowledge bases
|
||||
const maxBlocksPerPage = 1000 // Limit total blocks fetched per page to prevent runaway API calls
|
||||
|
||||
// blocksTruncated reports whether the maxBlocksPerPage cap stopped pagination
|
||||
// while the API still offered another page — i.e. whether content was actually
|
||||
// dropped. Hitting the cap on the last page of a document is not truncation,
|
||||
// so the caller can warn without a false positive.
|
||||
//
|
||||
// hasMore alone decides that: the Notion contract only clears it together with
|
||||
// next_cursor, so requiring a non-empty cursor here would let the anomalous
|
||||
// "has_more=true, next_cursor empty" response drop content in silence. That
|
||||
// anomaly is reported separately by the caller.
|
||||
func blocksTruncated(currentCount int, hasMore bool) bool {
|
||||
return currentCount >= maxBlocksPerPage && hasMore
|
||||
}
|
||||
|
||||
// GetBlockChildrenAll recursively fetches all blocks under a given block ID,
|
||||
// building a tree structure with Children populated for blocks with has_children=true.
|
||||
// child_page and child_database blocks are NOT recursed into (handled by connector layer).
|
||||
// Recursion is limited to maxBlockDepth to prevent excessive API calls on complex pages.
|
||||
func (c *notionClient) GetBlockChildrenAll(ctx context.Context, blockID string) ([]notionBlock, error) {
|
||||
return c.getBlockChildrenRecursive(ctx, blockID, 0)
|
||||
}
|
||||
|
||||
func (c *notionClient) getBlockChildrenRecursive(ctx context.Context, blockID string, depth int) ([]notionBlock, error) {
|
||||
var allBlocks []notionBlock
|
||||
var startCursor string
|
||||
seenCursors := make(map[string]struct{})
|
||||
|
||||
for page := 1; ; page++ {
|
||||
path := fmt.Sprintf("/v1/blocks/%s/children", blockID)
|
||||
if startCursor != "" {
|
||||
path += "?start_cursor=" + startCursor
|
||||
}
|
||||
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, path, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get block children for %s: %w", blockID, err)
|
||||
}
|
||||
|
||||
var resp paginatedResponse
|
||||
if err := json.Unmarshal(respBody, &resp); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal block children response: %w", err)
|
||||
}
|
||||
|
||||
var blocks []notionBlock
|
||||
if err := json.Unmarshal(resp.Results, &blocks); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal blocks: %w", err)
|
||||
}
|
||||
|
||||
allBlocks = append(allBlocks, blocks...)
|
||||
|
||||
// The cap below stops pagination unconditionally; without this warning
|
||||
// the dropped blocks (and any child_page/child_database they contain,
|
||||
// which the connector layer never visits) vanish silently.
|
||||
if blocksTruncated(len(allBlocks), resp.HasMore) {
|
||||
logger.Warnf(ctx, "[Notion] block %s exceeded %d blocks; truncating, remaining blocks are not synced",
|
||||
blockID, maxBlocksPerPage)
|
||||
}
|
||||
|
||||
// has_more promises another page, but an empty next_cursor means there is
|
||||
// no way to ask for it: pagination stops right here even below the cap,
|
||||
// so everything after this page would be dropped without a trace.
|
||||
if resp.HasMore && resp.NextCursor == "" {
|
||||
logger.Warnf(ctx, "[Notion] block %s returned has_more=true without a next_cursor after %d blocks; "+
|
||||
"cannot fetch further pages, remaining blocks are not synced", blockID, len(allBlocks))
|
||||
}
|
||||
|
||||
if len(allBlocks) >= maxBlocksPerPage || !resp.HasMore || resp.NextCursor == "" {
|
||||
break
|
||||
}
|
||||
// maxBlocksPerPage counts appended blocks, so an empty page carrying
|
||||
// has_more=true never reaches it. Guard the cursor itself as well: a
|
||||
// repeated one would otherwise be requested forever.
|
||||
next, err := advancePaginationCursor(ctx, seenCursors, resp.NextCursor, page)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get block children for %s: %w", blockID, err)
|
||||
}
|
||||
startCursor = next
|
||||
}
|
||||
|
||||
if depth >= maxBlockDepth {
|
||||
return allBlocks, nil
|
||||
}
|
||||
|
||||
for i := range allBlocks {
|
||||
if !allBlocks[i].HasChildren {
|
||||
continue
|
||||
}
|
||||
// Skip block types that don't contribute useful content
|
||||
switch allBlocks[i].Type {
|
||||
case "child_page", "child_database", "unsupported", "template", "breadcrumb", "table_of_contents":
|
||||
continue
|
||||
}
|
||||
children, err := c.getBlockChildrenRecursive(ctx, allBlocks[i].ID, depth+1)
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Notion] failed to get children for block %s (depth %d): %v", allBlocks[i].ID, depth, err)
|
||||
continue
|
||||
}
|
||||
allBlocks[i].Children = children
|
||||
}
|
||||
|
||||
return allBlocks, nil
|
||||
}
|
||||
|
||||
// QueryDatabaseAll retrieves all records from a database via POST /v1/data_sources/{id}/query.
|
||||
// Accepts either a data_source_id (from search) or a database_id (from child_database blocks).
|
||||
// For database_ids, resolves to data_source_id via GET /v1/databases/{id}.
|
||||
// The record set is read through created_time windows, so a data source holding
|
||||
// more rows than one vendor query can return is still read in full.
|
||||
func (c *notionClient) QueryDatabaseAll(ctx context.Context, id string) ([]notionPage, error) {
|
||||
// Try as data_source_id directly
|
||||
records, err := c.queryDataSourceAll(ctx, fmt.Sprintf("/v1/data_sources/%s/query", id))
|
||||
if err == nil {
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// An incomplete walk reached the data source successfully. Resolving the ID as
|
||||
// a database container would only repeat the same capped query and would bury
|
||||
// the truncation error behind a misleading lookup failure, so surface it here
|
||||
// together with the rows fetched so far.
|
||||
if errors.Is(err, errQueryResultTruncated) {
|
||||
return records, err
|
||||
}
|
||||
|
||||
// If 404, id might be a database container ID — resolve to data_source_id
|
||||
info, dbErr := c.GetDatabaseInfo(ctx, id)
|
||||
if dbErr != nil {
|
||||
return nil, fmt.Errorf("query database %s: not a data_source (%v) and not a database (%v)", id, err, dbErr)
|
||||
}
|
||||
if info.DataSourceID == "" {
|
||||
return nil, fmt.Errorf("database %s has no data sources", id)
|
||||
}
|
||||
return c.queryDataSourceAll(ctx, fmt.Sprintf("/v1/data_sources/%s/query", info.DataSourceID))
|
||||
}
|
||||
|
||||
// ResolveBlock re-fetches a single block to resolve file_upload URLs.
|
||||
// When a block contains a file_upload type, re-fetching it returns the resolved
|
||||
// download URL (temporary S3 signed URL, 1-hour expiry).
|
||||
func (c *notionClient) ResolveBlock(ctx context.Context, blockID string) (*notionBlock, error) {
|
||||
respBody, err := c.doRequest(ctx, http.MethodGet, "/v1/blocks/"+blockID, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var block notionBlock
|
||||
if err := json.Unmarshal(respBody, &block); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal block: %w", err)
|
||||
}
|
||||
return &block, nil
|
||||
}
|
||||
|
||||
const maxDownloadSize = 100 * 1024 * 1024 // 100MB — prevent OOM from oversized files
|
||||
|
||||
// DownloadFile downloads a file from the given URL (typically an S3 signed URL).
|
||||
// Does not go through the rate limiter since it's not a Notion API call.
|
||||
func (c *notionClient) DownloadFile(ctx context.Context, fileURL string) ([]byte, error) {
|
||||
if err := utils.ValidateURLForSSRF(fileURL); err != nil {
|
||||
return nil, fmt.Errorf("attachment URL rejected: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create download request: %w", err)
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for attempt := 0; attempt <= maxRetries; attempt++ {
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if attempt < maxRetries {
|
||||
if sErr := sleepWithContext(ctx, time.Duration(1<<attempt)*time.Second); sErr != nil {
|
||||
return nil, sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
resp.Body.Close()
|
||||
lastErr = fmt.Errorf("download failed with status %d", resp.StatusCode)
|
||||
if resp.StatusCode >= 500 && attempt < maxRetries {
|
||||
if sErr := sleepWithContext(ctx, time.Duration(1<<attempt)*time.Second); sErr != nil {
|
||||
return nil, sErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, maxDownloadSize+1))
|
||||
resp.Body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > maxDownloadSize {
|
||||
return nil, fmt.Errorf("file exceeds maximum download size (%d MB)", maxDownloadSize/(1024*1024))
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("download file: %w", lastErr)
|
||||
}
|
||||
|
||||
// --- Shared pagination helper ---
|
||||
|
||||
// maxPaginationHops bounds every cursor-paginated loop in this file. A vendor
|
||||
// (or gateway) that keeps answering has_more=true would otherwise keep the
|
||||
// client paging until the sync task hits its deadline; the value mirrors the
|
||||
// guard Confluence and DingTalk already carry.
|
||||
const maxPaginationHops = 10000
|
||||
|
||||
// advancePaginationCursor validates the progress of a cursor-paginated loop
|
||||
// after page `page` (1-based) has been fetched: a cursor handed back twice
|
||||
// means the vendor is repeating a page, and page >= maxPaginationHops means
|
||||
// the listing is unbounded. Both are reported instead of being followed
|
||||
// forever, and the hop cap is also logged because it is the one failure that
|
||||
// looks like a healthy, still-running sync from the outside.
|
||||
func advancePaginationCursor(
|
||||
ctx context.Context, seen map[string]struct{}, cursor string, page int,
|
||||
) (string, error) {
|
||||
if page >= maxPaginationHops {
|
||||
logger.Warnf(ctx, "[Notion] pagination exceeded %d pages; aborting", maxPaginationHops)
|
||||
return "", fmt.Errorf("pagination exceeded %d pages", maxPaginationHops)
|
||||
}
|
||||
if _, exists := seen[cursor]; exists {
|
||||
return "", fmt.Errorf("pagination repeated next_cursor %q", cursor)
|
||||
}
|
||||
seen[cursor] = struct{}{}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
// errQueryResultTruncated reports that a paginated response was cut short by a
|
||||
// vendor-side limit, so the rows collected so far are a prefix of the result set
|
||||
// rather than all of it. Notion signals this with has_more=false plus
|
||||
// request_status.type="incomplete" (for a data source query at the 10,000-row
|
||||
// limit: incomplete_reason="query_result_limit_reached"), which without this
|
||||
// check is indistinguishable from a complete result set. Callers must not treat
|
||||
// rows missing from such a result as deleted at source.
|
||||
var errQueryResultTruncated = errors.New("notion paginated response incomplete: vendor limit reached")
|
||||
|
||||
// paginatePages fetches all pages from a cursor-paginated Notion API endpoint
|
||||
// (POST /v1/search). Endpoints that can return more rows than a single query
|
||||
// allows — data source queries — go through queryDataSourceAll instead, which
|
||||
// splits the walk into created_time windows when the vendor caps a query.
|
||||
func (c *notionClient) paginatePages(ctx context.Context, method, path string) ([]notionPage, error) {
|
||||
var allPages []notionPage
|
||||
var startCursor string
|
||||
seenCursors := make(map[string]struct{})
|
||||
|
||||
for page := 1; ; page++ {
|
||||
body := map[string]interface{}{
|
||||
"page_size": 100,
|
||||
}
|
||||
if startCursor != "" {
|
||||
body["start_cursor"] = startCursor
|
||||
}
|
||||
|
||||
var respBody []byte
|
||||
var err error
|
||||
if method == http.MethodPost {
|
||||
respBody, err = c.doRequest(ctx, method, path, body)
|
||||
} else {
|
||||
p := path
|
||||
if startCursor != "" {
|
||||
p += "?start_cursor=" + startCursor + "&page_size=100"
|
||||
}
|
||||
respBody, err = c.doRequest(ctx, method, p, nil)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("paginate %s: %w", path, err)
|
||||
}
|
||||
|
||||
var resp paginatedResponse
|
||||
if err := json.Unmarshal(respBody, &resp); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal paginated response: %w", err)
|
||||
}
|
||||
|
||||
var pages []notionPage
|
||||
if err := json.Unmarshal(resp.Results, &pages); err != nil {
|
||||
return nil, fmt.Errorf("unmarshal page results: %w", err)
|
||||
}
|
||||
|
||||
for i := range pages {
|
||||
pages[i].Title = extractTitle(&pages[i])
|
||||
}
|
||||
|
||||
allPages = append(allPages, pages...)
|
||||
|
||||
// The vendor marks a capped page as incomplete while still reporting
|
||||
// has_more=false, so this per-page check is the only way to tell "cut
|
||||
// short" from "read to the end". Keep the rows this page did return, then
|
||||
// surface the sentinel so callers can use the partial data without reading
|
||||
// absence from it as a source-side deletion.
|
||||
if resp.isIncomplete() {
|
||||
return allPages, fmt.Errorf("%w: %s (path %s, %d records fetched)",
|
||||
errQueryResultTruncated, resp.RequestStatus.IncompleteReason, path, len(allPages))
|
||||
}
|
||||
|
||||
if !resp.HasMore || resp.NextCursor == "" {
|
||||
break
|
||||
}
|
||||
next, err := advancePaginationCursor(ctx, seenCursors, resp.NextCursor, page)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("paginate %s: %w", path, err)
|
||||
}
|
||||
startCursor = next
|
||||
}
|
||||
|
||||
return allPages, nil
|
||||
}
|
||||
|
||||
// --- Data source query: read past the per-query result limit ---
|
||||
|
||||
// dataSourceQueryPageSize is the page size requested for every data source query page.
|
||||
const dataSourceQueryPageSize = 100
|
||||
|
||||
// errWindowNotAdvancing reports that an incomplete window could not be followed
|
||||
// by a later one: no returned row carried a created_time, or every row in the
|
||||
// window shares the timestamp the window started at. Both mean the remaining
|
||||
// rows cannot be reached by moving the created_time boundary, so the walk stops
|
||||
// instead of re-querying the same window forever.
|
||||
var errWindowNotAdvancing = errors.New("created_time window cannot advance")
|
||||
|
||||
// queryDataSourceAll reads every row of a data source query, splitting the walk
|
||||
// into created_time windows whenever the vendor caps a query at its per-query
|
||||
// result limit.
|
||||
//
|
||||
// A capped query answers has_more=false together with
|
||||
// request_status.type="incomplete", so a caller that only follows next_cursor
|
||||
// stops at the limit without noticing. The vendor's recipe for reading past it is
|
||||
// to sort by created_time ascending and, each time a window comes back
|
||||
// incomplete, to re-query with filter.created_time.on_or_after set to the
|
||||
// created_time of the last row seen; rows sitting exactly on that boundary are
|
||||
// returned by both windows and are de-duplicated here by row ID. created_time is
|
||||
// used deliberately instead of last_edited_time: it never changes, so a window
|
||||
// boundary stays valid while the walk is in progress, whereas last_edited_time
|
||||
// moves rows between windows as they are edited.
|
||||
// See https://developers.notion.com/guides/data-apis/query-large-data-sources
|
||||
//
|
||||
// When a window cannot advance, the walk stops and the rows collected so far are
|
||||
// returned together with errQueryResultTruncated, so callers still learn that the
|
||||
// result set is incomplete instead of reading absence from it as deletion.
|
||||
func (c *notionClient) queryDataSourceAll(ctx context.Context, path string) ([]notionPage, error) {
|
||||
var allRows []notionPage
|
||||
seen := make(map[string]bool, dataSourceQueryPageSize)
|
||||
var windowStart *time.Time
|
||||
|
||||
for {
|
||||
rows, lastCreatedTime, incompleteReason, err := c.queryDataSourceWindow(ctx, path, windowStart)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range rows {
|
||||
if id := rows[i].ID; id != "" {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
allRows = append(allRows, rows[i])
|
||||
}
|
||||
|
||||
if incompleteReason == "" {
|
||||
return allRows, nil
|
||||
}
|
||||
|
||||
// The vendor capped this window, so the rows past the limit are only
|
||||
// reachable from a later window. The next window must start strictly after
|
||||
// the current one, otherwise it would return the same rows again.
|
||||
if lastCreatedTime.IsZero() {
|
||||
logger.Warnf(ctx, "[Notion] query %s is incomplete (%s) but returned no row carrying created_time; "+
|
||||
"stopping with %d records instead of re-querying the same window",
|
||||
path, incompleteReason, len(allRows))
|
||||
return allRows, fmt.Errorf("%w: %s: %w: %s returned an incomplete window "+
|
||||
"without any created_time (%d records fetched)",
|
||||
errQueryResultTruncated, incompleteReason, errWindowNotAdvancing, path, len(allRows))
|
||||
}
|
||||
if windowStart != nil && !lastCreatedTime.After(*windowStart) {
|
||||
logger.Warnf(ctx, "[Notion] query %s is still incomplete (%s) at created_time %s, which does not advance "+
|
||||
"the window start; stopping with %d records: more rows than the vendor per-query limit share "+
|
||||
"one created_time", path, incompleteReason,
|
||||
lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows))
|
||||
return allRows, fmt.Errorf("%w: %s: %w: %s did not advance past created_time %s (%d records fetched)",
|
||||
errQueryResultTruncated, incompleteReason, errWindowNotAdvancing, path,
|
||||
lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows))
|
||||
}
|
||||
|
||||
// Keep the truncation visible: the first window hit the vendor limit, and
|
||||
// the log line records where the next window starts.
|
||||
logger.Warnf(ctx, "[Notion] query %s hit the vendor per-query result limit (%s); "+
|
||||
"continuing from created_time %s (%d records fetched so far)", path, incompleteReason,
|
||||
lastCreatedTime.UTC().Format(time.RFC3339Nano), len(allRows))
|
||||
start := lastCreatedTime
|
||||
windowStart = &start
|
||||
}
|
||||
}
|
||||
|
||||
// queryDataSourceWindow drains one created_time window: it follows next_cursor
|
||||
// until the window is exhausted, and reports the created_time of the last row it
|
||||
// saw plus the vendor's incomplete_reason when any page of the window was marked
|
||||
// incomplete (an empty reason means the window was read to the end).
|
||||
// A nil windowStart reads the first, unfiltered window.
|
||||
func (c *notionClient) queryDataSourceWindow(
|
||||
ctx context.Context, path string, windowStart *time.Time,
|
||||
) (rows []notionPage, lastCreatedTime time.Time, incompleteReason string, err error) {
|
||||
var startCursor string
|
||||
seenCursors := make(map[string]struct{})
|
||||
|
||||
for page := 1; ; page++ {
|
||||
body := map[string]interface{}{
|
||||
"page_size": dataSourceQueryPageSize,
|
||||
"sorts": []map[string]string{
|
||||
{"timestamp": "created_time", "direction": "ascending"},
|
||||
},
|
||||
}
|
||||
if windowStart != nil {
|
||||
body["filter"] = map[string]interface{}{
|
||||
"timestamp": "created_time",
|
||||
"created_time": map[string]string{
|
||||
"on_or_after": windowStart.UTC().Format(time.RFC3339Nano),
|
||||
},
|
||||
}
|
||||
}
|
||||
if startCursor != "" {
|
||||
body["start_cursor"] = startCursor
|
||||
}
|
||||
|
||||
respBody, doErr := c.doRequest(ctx, http.MethodPost, path, body)
|
||||
if doErr != nil {
|
||||
return nil, time.Time{}, "", fmt.Errorf("paginate %s: %w", path, doErr)
|
||||
}
|
||||
|
||||
var resp paginatedResponse
|
||||
if unmarshalErr := json.Unmarshal(respBody, &resp); unmarshalErr != nil {
|
||||
return nil, time.Time{}, "", fmt.Errorf("unmarshal paginated response: %w", unmarshalErr)
|
||||
}
|
||||
|
||||
var pageRows []notionPage
|
||||
if unmarshalErr := json.Unmarshal(resp.Results, &pageRows); unmarshalErr != nil {
|
||||
return nil, time.Time{}, "", fmt.Errorf("unmarshal page results: %w", unmarshalErr)
|
||||
}
|
||||
for i := range pageRows {
|
||||
pageRows[i].Title = extractTitle(&pageRows[i])
|
||||
// Rows arrive sorted by created_time ascending, so the last row
|
||||
// carrying a timestamp is this window's boundary.
|
||||
if !pageRows[i].CreatedTime.IsZero() {
|
||||
lastCreatedTime = pageRows[i].CreatedTime
|
||||
}
|
||||
}
|
||||
rows = append(rows, pageRows...)
|
||||
|
||||
// The marker is latched for the whole window: it can appear on any page
|
||||
// of a capped query, including before the last page received.
|
||||
if resp.isIncomplete() {
|
||||
incompleteReason = resp.RequestStatus.IncompleteReason
|
||||
if incompleteReason == "" {
|
||||
incompleteReason = "incomplete"
|
||||
}
|
||||
}
|
||||
|
||||
if !resp.HasMore || resp.NextCursor == "" {
|
||||
return rows, lastCreatedTime, incompleteReason, nil
|
||||
}
|
||||
next, cursorErr := advancePaginationCursor(ctx, seenCursors, resp.NextCursor, page)
|
||||
if cursorErr != nil {
|
||||
return nil, time.Time{}, "", fmt.Errorf("paginate %s: %w", path, cursorErr)
|
||||
}
|
||||
startCursor = next
|
||||
}
|
||||
}
|
||||
|
||||
// --- Title extraction helpers ---
|
||||
|
||||
func extractTitle(page *notionPage) string {
|
||||
// Try extracting from properties (works for pages)
|
||||
if page.RawProperties != nil {
|
||||
var props map[string]json.RawMessage
|
||||
if err := json.Unmarshal(page.RawProperties, &props); err == nil {
|
||||
for _, propRaw := range props {
|
||||
var prop struct {
|
||||
Type string `json:"type"`
|
||||
Title []struct {
|
||||
PlainText string `json:"plain_text"`
|
||||
} `json:"title"`
|
||||
}
|
||||
if err := json.Unmarshal(propRaw, &prop); err != nil {
|
||||
continue
|
||||
}
|
||||
if prop.Type == "title" && len(prop.Title) > 0 {
|
||||
return joinPlainText(prop.Title)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: top-level title array (works for databases)
|
||||
if page.RawTitle != nil {
|
||||
var titleSegments []struct {
|
||||
PlainText string `json:"plain_text"`
|
||||
}
|
||||
if err := json.Unmarshal(page.RawTitle, &titleSegments); err == nil && len(titleSegments) > 0 {
|
||||
return joinPlainText(titleSegments)
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func joinPlainText(segments []struct {
|
||||
PlainText string `json:"plain_text"`
|
||||
}) string {
|
||||
var sb strings.Builder
|
||||
for _, s := range segments {
|
||||
sb.WriteString(s.PlainText)
|
||||
}
|
||||
return sb.String()
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
func mustTestClient(t *testing.T, token, baseURL string) *notionClient {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
|
||||
client, err := newClient(token, baseURL)
|
||||
if err != nil {
|
||||
t.Fatalf("newClient: %v", err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
// fakeNotion builds an httptest.Server that emulates relevant Notion API endpoints.
|
||||
func fakeNotion() (*httptest.Server, *Config) {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// GET /v1/users/me — auth check
|
||||
mux.HandleFunc("/v1/users/me", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer test-token" {
|
||||
w.WriteHeader(401)
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"status": 401,
|
||||
"code": "unauthorized",
|
||||
"message": "API token is invalid.",
|
||||
})
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "user",
|
||||
"id": "bot-user-id",
|
||||
"type": "bot",
|
||||
"name": "Test Integration",
|
||||
})
|
||||
})
|
||||
|
||||
// POST /v1/search — return pages and databases
|
||||
mux.HandleFunc("/v1/search", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list",
|
||||
"results": []interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "page-1",
|
||||
"object": "page",
|
||||
"url": "https://notion.so/Page-1",
|
||||
"last_edited_time": "2026-01-15T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "workspace", "workspace": true},
|
||||
"properties": map[string]interface{}{
|
||||
"title": map[string]interface{}{
|
||||
"type": "title",
|
||||
"title": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Test Page"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
map[string]interface{}{
|
||||
"id": "db-1",
|
||||
"object": "data_source",
|
||||
"url": "https://notion.so/DB-1",
|
||||
"last_edited_time": "2026-01-16T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "workspace", "workspace": true},
|
||||
"title": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Test Database"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"has_more": false,
|
||||
"next_cursor": nil,
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/blocks/{id}/children — return blocks
|
||||
mux.HandleFunc("/v1/blocks/page-1/children", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list",
|
||||
"results": []interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "blk-1",
|
||||
"type": "paragraph",
|
||||
"has_children": false,
|
||||
"paragraph": map[string]interface{}{
|
||||
"rich_text": []interface{}{
|
||||
map[string]interface{}{
|
||||
"type": "text",
|
||||
"plain_text": "Hello world",
|
||||
"text": map[string]interface{}{"content": "Hello world"},
|
||||
"annotations": map[string]interface{}{
|
||||
"bold": false, "italic": false, "strikethrough": false,
|
||||
"underline": false, "code": false, "color": "default",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
map[string]interface{}{
|
||||
"id": "blk-2",
|
||||
"type": "child_page",
|
||||
"has_children": true,
|
||||
"child_page": map[string]interface{}{"title": "Sub Page"},
|
||||
},
|
||||
},
|
||||
"has_more": false,
|
||||
"next_cursor": nil,
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/pages/{id}
|
||||
mux.HandleFunc("/v1/pages/page-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": "page-1",
|
||||
"object": "page",
|
||||
"url": "https://notion.so/Page-1",
|
||||
"last_edited_time": "2026-01-15T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "workspace", "workspace": true},
|
||||
"properties": map[string]interface{}{
|
||||
"title": map[string]interface{}{
|
||||
"type": "title",
|
||||
"title": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Test Page"},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/databases/{id} — returns container with data_sources array (2025-09-03+)
|
||||
mux.HandleFunc("/v1/databases/db-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": "db-1",
|
||||
"object": "database",
|
||||
"url": "https://notion.so/DB-1",
|
||||
"last_edited_time": "2026-01-16T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "workspace", "workspace": true},
|
||||
"title": []interface{}{map[string]interface{}{"plain_text": "Test Database"}},
|
||||
"data_sources": []interface{}{
|
||||
map[string]interface{}{"id": "ds-1", "name": "Default"},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/data_sources/{id} — returns schema/properties
|
||||
mux.HandleFunc("/v1/data_sources/ds-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": "ds-1",
|
||||
"object": "data_source",
|
||||
"properties": map[string]interface{}{
|
||||
"Name": map[string]interface{}{"type": "title", "title": map[string]interface{}{}},
|
||||
"Status": map[string]interface{}{"type": "select", "select": map[string]interface{}{}},
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
})
|
||||
|
||||
// POST /v1/data_sources/{id}/query — return database records (2025-09-03+)
|
||||
mux.HandleFunc("/v1/data_sources/ds-1/query", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list",
|
||||
"results": []interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "record-1",
|
||||
"object": "page",
|
||||
"url": "https://notion.so/Record-1",
|
||||
"last_edited_time": "2026-01-17T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "data_source_id", "data_source_id": "ds-1"},
|
||||
"properties": map[string]interface{}{
|
||||
"Name": map[string]interface{}{
|
||||
"type": "title",
|
||||
"title": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Record One"},
|
||||
},
|
||||
},
|
||||
"Status": map[string]interface{}{
|
||||
"type": "select",
|
||||
"select": map[string]interface{}{"name": "Done"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
"has_more": false,
|
||||
"next_cursor": nil,
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/pages/record-1 — direct fetch of a database row (single-select case).
|
||||
// fetchPage must recognize both database_id (older responses) and
|
||||
// data_source_id (2025-09-03+) as a record and route to buildRecordItem.
|
||||
mux.HandleFunc("/v1/pages/record-1", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": "record-1",
|
||||
"object": "page",
|
||||
"url": "https://notion.so/Record-1",
|
||||
"last_edited_time": "2026-01-17T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "data_source_id", "data_source_id": "ds-1"},
|
||||
"properties": map[string]interface{}{
|
||||
"Name": map[string]interface{}{
|
||||
"type": "title",
|
||||
"title": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Record One"},
|
||||
},
|
||||
},
|
||||
"Status": map[string]interface{}{
|
||||
"type": "select",
|
||||
"select": map[string]interface{}{"name": "Done"},
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
// GET /v1/blocks/record-1/children — empty blocks for database record
|
||||
mux.HandleFunc("/v1/blocks/record-1/children", func(w http.ResponseWriter, r *http.Request) {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list",
|
||||
"results": []interface{}{},
|
||||
"has_more": false,
|
||||
"next_cursor": nil,
|
||||
})
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(mux)
|
||||
cfg := &Config{APIKey: "test-token"}
|
||||
return ts, cfg
|
||||
}
|
||||
|
||||
func TestClientPing(t *testing.T) {
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, cfg.APIKey, ts.URL)
|
||||
if err := client.Ping(context.Background()); err != nil {
|
||||
t.Fatalf("Ping() error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientPing_InvalidToken(t *testing.T) {
|
||||
ts, _ := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, "wrong-token", ts.URL)
|
||||
err := client.Ping(context.Background())
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSearchPages(t *testing.T) {
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, cfg.APIKey, ts.URL)
|
||||
pages, err := client.SearchPages(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("SearchPages() error: %v", err)
|
||||
}
|
||||
if len(pages) != 2 {
|
||||
t.Fatalf("expected 2 pages, got %d", len(pages))
|
||||
}
|
||||
// First result is a page
|
||||
if pages[0].Object != "page" || pages[0].ID != "page-1" {
|
||||
t.Errorf("page[0] = %+v", pages[0])
|
||||
}
|
||||
// Second result is a data_source (databases are returned as object="data_source"
|
||||
// in API 2025-09-03+ which is what the mock simulates)
|
||||
if pages[1].Object != "data_source" || pages[1].ID != "db-1" {
|
||||
t.Errorf("page[1] = %+v", pages[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetBlockChildrenAll(t *testing.T) {
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, cfg.APIKey, ts.URL)
|
||||
blocks, err := client.GetBlockChildrenAll(context.Background(), "page-1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockChildrenAll() error: %v", err)
|
||||
}
|
||||
if len(blocks) != 2 {
|
||||
t.Fatalf("expected 2 blocks, got %d", len(blocks))
|
||||
}
|
||||
if blocks[0].Type != "paragraph" {
|
||||
t.Errorf("block[0].Type = %q", blocks[0].Type)
|
||||
}
|
||||
if blocks[1].Type != "child_page" {
|
||||
t.Errorf("block[1].Type = %q", blocks[1].Type)
|
||||
}
|
||||
// child_page should NOT have its children recursed
|
||||
if blocks[1].Children != nil {
|
||||
t.Error("child_page children should not be recursed by client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGetPage(t *testing.T) {
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, cfg.APIKey, ts.URL)
|
||||
page, err := client.GetPage(context.Background(), "page-1")
|
||||
if err != nil {
|
||||
t.Fatalf("GetPage() error: %v", err)
|
||||
}
|
||||
if page.ID != "page-1" {
|
||||
t.Errorf("ID = %q", page.ID)
|
||||
}
|
||||
if page.Title != "Test Page" {
|
||||
t.Errorf("Title = %q, want %q", page.Title, "Test Page")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientQueryDatabaseAll(t *testing.T) {
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
client := mustTestClient(t, cfg.APIKey, ts.URL)
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "db-1")
|
||||
if err != nil {
|
||||
t.Fatalf("QueryDatabaseAll() error: %v", err)
|
||||
}
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("expected 1 record, got %d", len(records))
|
||||
}
|
||||
if records[0].ID != "record-1" {
|
||||
t.Errorf("record ID = %q", records[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure time import is used (referenced by fakeNotion indirectly via time.Time in types).
|
||||
var _ = time.Now
|
||||
|
||||
func TestDownloadFile_RejectsLoopbackURL(t *testing.T) {
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
|
||||
client, err := newClient("test-token", "https://api.notion.com")
|
||||
if err != nil {
|
||||
t.Fatalf("newClient: %v", err)
|
||||
}
|
||||
_, err = client.DownloadFile(context.Background(), "http://127.0.0.1/secret")
|
||||
if err == nil {
|
||||
t.Fatal("expected loopback attachment URL to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoRequest_RejectsOversizedResponse(t *testing.T) {
|
||||
var hits atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
hits.Add(1)
|
||||
_, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := mustTestClient(t, "token", server.URL)
|
||||
c.jsonLimit = 1 << 20
|
||||
_, err := c.doRequest(context.Background(), http.MethodGet, "/v1/users/me", nil)
|
||||
if err == nil {
|
||||
t.Fatal("doRequest accepted a response larger than the cap, want error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "exceeds maximum size") {
|
||||
t.Fatalf("error = %v, want an explicit over-limit error", err)
|
||||
}
|
||||
if got := hits.Load(); got != 1 {
|
||||
t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,301 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
secutils "github.com/Tencent/WeKnora/internal/utils"
|
||||
)
|
||||
|
||||
func allowNotionTestServer(t *testing.T) {
|
||||
t.Helper()
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
|
||||
secutils.ResetSSRFWhitelistForTest()
|
||||
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
|
||||
}
|
||||
|
||||
func makeNotionConfig(cfg *Config, baseURL string, resourceIDs []string) *types.DataSourceConfig {
|
||||
return &types.DataSourceConfig{
|
||||
Type: types.ConnectorTypeNotion,
|
||||
Credentials: map[string]interface{}{
|
||||
"api_key": cfg.APIKey,
|
||||
},
|
||||
ResourceIDs: resourceIDs,
|
||||
Settings: map[string]interface{}{
|
||||
"base_url": baseURL,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorType(t *testing.T) {
|
||||
c := NewConnector()
|
||||
if c.Type() != types.ConnectorTypeNotion {
|
||||
t.Errorf("Type() = %q, want %q", c.Type(), types.ConnectorTypeNotion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidate(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
err := c.Validate(context.Background(), makeNotionConfig(cfg, ts.URL, nil))
|
||||
if err != nil {
|
||||
t.Fatalf("Validate() error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorValidate_BadToken(t *testing.T) {
|
||||
ts, _ := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
err := c.Validate(context.Background(), makeNotionConfig(
|
||||
&Config{APIKey: "bad-token"}, ts.URL, nil,
|
||||
))
|
||||
if err == nil {
|
||||
t.Fatal("expected error for bad token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorListResources(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
resources, err := c.ListResources(context.Background(), makeNotionConfig(cfg, ts.URL, nil), "")
|
||||
if err != nil {
|
||||
t.Fatalf("ListResources() error: %v", err)
|
||||
}
|
||||
|
||||
if len(resources) != 2 {
|
||||
t.Fatalf("expected 2 resources, got %d", len(resources))
|
||||
}
|
||||
if resources[0].ExternalID != "page-1" || resources[0].Type != "page" || resources[0].Name != "Test Page" {
|
||||
t.Errorf("resource[0] = %+v", resources[0])
|
||||
}
|
||||
if resources[1].ExternalID != "db-1" || resources[1].Type != "database" || resources[1].Name != "Test Database" {
|
||||
t.Errorf("resource[1] = %+v, want Name=%q", resources[1], "Test Database")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorFetchAll(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
items, err := c.FetchAll(context.Background(), makeNotionConfig(cfg, ts.URL, []string{"page-1"}), []string{"page-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error: %v", err)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
t.Fatal("expected at least 1 item")
|
||||
}
|
||||
|
||||
// First item should be the page with markdown content
|
||||
found := false
|
||||
for _, item := range items {
|
||||
if item.ExternalID == "page-1" {
|
||||
found = true
|
||||
if item.ContentType != "text/markdown" {
|
||||
t.Errorf("ContentType = %q", item.ContentType)
|
||||
}
|
||||
if item.Metadata["channel"] != "notion" {
|
||||
t.Errorf("channel = %q", item.Metadata["channel"])
|
||||
}
|
||||
if len(item.Content) == 0 {
|
||||
t.Error("expected non-empty content")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("page-1 not found in items")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorFetchAll_Database(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
items, err := c.FetchAll(context.Background(), makeNotionConfig(cfg, ts.URL, []string{"db-1"}), []string{"db-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error: %v", err)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
t.Fatal("expected at least 1 item")
|
||||
}
|
||||
|
||||
// The entire database should be synced as a single table knowledge item
|
||||
found := false
|
||||
for _, item := range items {
|
||||
if item.ExternalID == "db-1" {
|
||||
found = true
|
||||
if item.Metadata["object_type"] != "database" {
|
||||
t.Errorf("object_type = %q, want %q", item.Metadata["object_type"], "database")
|
||||
}
|
||||
if item.ContentType != "text/markdown" {
|
||||
t.Errorf("ContentType = %q", item.ContentType)
|
||||
}
|
||||
if len(item.Content) == 0 {
|
||||
t.Error("expected non-empty content")
|
||||
}
|
||||
// Verify it contains table headers
|
||||
contentStr := string(item.Content)
|
||||
if !strings.Contains(contentStr, "| Title |") {
|
||||
t.Errorf("expected table header in content, got: %s", contentStr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("db-1 not found in items")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConnectorFetchAll_SingleRecord verifies that selecting a single database
|
||||
// row by ID routes through fetchPage's record-detection branch and produces an
|
||||
// item via buildRecordItem (instead of being silently dropped as an empty page).
|
||||
func TestConnectorFetchAll_SingleRecord(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
items, err := c.FetchAll(context.Background(), makeNotionConfig(cfg, ts.URL, []string{"record-1"}), []string{"record-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("expected 1 item, got %d", len(items))
|
||||
}
|
||||
if items[0].ExternalID != "record-1" {
|
||||
t.Errorf("ExternalID = %q, want record-1", items[0].ExternalID)
|
||||
}
|
||||
if items[0].Metadata["object_type"] != "page" {
|
||||
t.Errorf("object_type = %q, want page", items[0].Metadata["object_type"])
|
||||
}
|
||||
if len(items[0].Content) == 0 {
|
||||
t.Error("expected non-empty content from buildRecordItem")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectorFetchIncremental_NoChanges(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
ts, cfg := fakeNotion()
|
||||
defer ts.Close()
|
||||
|
||||
c := NewConnector()
|
||||
config := makeNotionConfig(cfg, ts.URL, []string{"page-1"})
|
||||
|
||||
// First: full fetch to establish baseline
|
||||
_, err := c.FetchAll(context.Background(), config, []string{"page-1"})
|
||||
if err != nil {
|
||||
t.Fatalf("FetchAll() error: %v", err)
|
||||
}
|
||||
|
||||
// Build a cursor that matches current state
|
||||
cursor := &types.SyncCursor{
|
||||
ConnectorCursor: map[string]interface{}{
|
||||
"page_edit_times": map[string]interface{}{
|
||||
"page-1": "2026-01-15T10:00:00Z",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
items, newCursor, err := c.FetchIncremental(context.Background(), config, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("FetchIncremental() error: %v", err)
|
||||
}
|
||||
|
||||
// No changes expected (timestamps match)
|
||||
if len(items) != 0 {
|
||||
t.Errorf("expected 0 items for no changes, got %d", len(items))
|
||||
}
|
||||
if newCursor == nil {
|
||||
t.Fatal("expected non-nil cursor")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPropertyToString(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value map[string]interface{}
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "select",
|
||||
value: map[string]interface{}{
|
||||
"type": "select",
|
||||
"select": map[string]interface{}{"name": "Done"},
|
||||
},
|
||||
expected: "Done",
|
||||
},
|
||||
{
|
||||
name: "rich_text",
|
||||
value: map[string]interface{}{
|
||||
"type": "rich_text",
|
||||
"rich_text": []interface{}{
|
||||
map[string]interface{}{"plain_text": "Hello"},
|
||||
},
|
||||
},
|
||||
expected: "Hello",
|
||||
},
|
||||
{
|
||||
name: "number",
|
||||
value: map[string]interface{}{
|
||||
"type": "number",
|
||||
"number": 42.0,
|
||||
},
|
||||
expected: "42",
|
||||
},
|
||||
{
|
||||
name: "checkbox true",
|
||||
value: map[string]interface{}{
|
||||
"type": "checkbox",
|
||||
"checkbox": true,
|
||||
},
|
||||
expected: "true",
|
||||
},
|
||||
{
|
||||
name: "date",
|
||||
value: map[string]interface{}{
|
||||
"type": "date",
|
||||
"date": map[string]interface{}{"start": "2026-01-15", "end": "2026-01-20"},
|
||||
},
|
||||
expected: "2026-01-15 ~ 2026-01-20",
|
||||
},
|
||||
{
|
||||
name: "multi_select",
|
||||
value: map[string]interface{}{
|
||||
"type": "multi_select",
|
||||
"multi_select": []interface{}{
|
||||
map[string]interface{}{"name": "Tag1"},
|
||||
map[string]interface{}{"name": "Tag2"},
|
||||
},
|
||||
},
|
||||
expected: "Tag1, Tag2",
|
||||
},
|
||||
{
|
||||
name: "nil value",
|
||||
value: map[string]interface{}{"type": "rich_text", "rich_text": nil},
|
||||
expected: "",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := propertyToString(tt.value)
|
||||
if got != tt.expected {
|
||||
t.Errorf("propertyToString() = %q, want %q", got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
)
|
||||
|
||||
func TestFetchIncrementalSearchFailure(t *testing.T) {
|
||||
for _, failPage := range []int{1, 2} {
|
||||
t.Run("page_"+strconv.Itoa(failPage), func(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
requests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.URL.Path != "/v1/search" {
|
||||
t.Errorf("unexpected path: %s", r.URL.Path)
|
||||
}
|
||||
if requests == failPage {
|
||||
http.Error(w, "access revoked", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"results": []interface{}{}, "has_more": true, "next_cursor": "second-page",
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page-1"})
|
||||
cursor := buildCursor(map[string]time.Time{"page-1": time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC)})
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, cursor)
|
||||
if !errors.Is(err, datasource.ErrInvalidCredentials) {
|
||||
t.Errorf("expected credential error, got %v", err)
|
||||
}
|
||||
if len(items) != 0 || next != nil {
|
||||
t.Errorf("failed discovery must return no items or cursor, got items=%+v cursor=%+v", items, next)
|
||||
}
|
||||
if requests != failPage {
|
||||
t.Errorf("expected %d requests, got %d", failPage, requests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchIncrementalSuccessfulEmptySearch(t *testing.T) {
|
||||
allowNotionTestServer(t)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"results": []interface{}{}, "has_more": false,
|
||||
})
|
||||
}))
|
||||
defer server.Close()
|
||||
config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page-1"})
|
||||
cursor := buildCursor(map[string]time.Time{"page-1": time.Date(2026, 1, 15, 10, 0, 0, 0, time.UTC)})
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, cursor)
|
||||
if err != nil {
|
||||
t.Fatalf("expected successful discovery, got %v", err)
|
||||
}
|
||||
if len(items) != 1 || items[0].ExternalID != "page-1" || !items[0].IsDeleted {
|
||||
t.Fatalf("expected deletion of absent page-1, got %+v", items)
|
||||
}
|
||||
if next == nil {
|
||||
t.Fatal("expected updated cursor after successful discovery")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func emptyPageConfig(t *testing.T, blocks, title string) *types.DataSourceConfig {
|
||||
t.Helper()
|
||||
allowNotionTestServer(t)
|
||||
titleJSON, err := json.Marshal(title)
|
||||
require.NoError(t, err)
|
||||
page := `{"id":"page","object":"page","url":"https://notion.so/page",` +
|
||||
`"last_edited_time":"2026-09-26T10:00:00Z","parent":{"type":"workspace"},` +
|
||||
`"properties":{"title":{"type":"title","title":[{"plain_text":` + string(titleJSON) + `}]}}}`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/v1/pages/page":
|
||||
_, _ = fmt.Fprint(w, page)
|
||||
case "/v1/search":
|
||||
_, _ = fmt.Fprint(w, `{"results":[`+page+`],"has_more":false}`)
|
||||
case "/v1/blocks/page/children":
|
||||
if blocks == "later_failure" && r.URL.Query().Get("start_cursor") == "" {
|
||||
_, _ = fmt.Fprint(w, `{"results":[],"has_more":true,"next_cursor":"later"}`)
|
||||
return
|
||||
}
|
||||
if blocks == "unauthorized" || blocks == "later_failure" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
_, _ = fmt.Fprint(w, `{"results":`+blocks+`,"has_more":false}`)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"page"})
|
||||
}
|
||||
|
||||
func TestClearedPageEmitsReplacement(t *testing.T) {
|
||||
config := emptyPageConfig(t, `[]`, "Retained title")
|
||||
previous := buildCursor(map[string]time.Time{"page": time.Date(2026, 9, 25, 10, 0, 0, 0, time.UTC)})
|
||||
connector := NewConnector()
|
||||
items, next, err := connector.FetchIncremental(context.Background(), config, previous)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1, "an empty source page must replace previously indexed content")
|
||||
require.Equal(t, "page", items[0].ExternalID)
|
||||
require.Equal(t, "# Retained title\n", string(items[0].Content))
|
||||
require.Equal(t, "Retained title.md", items[0].FileName)
|
||||
require.False(t, items[0].IsDeleted, "the source page still exists")
|
||||
require.Equal(t, "page", items[0].Metadata["object_type"])
|
||||
items, _, err = connector.FetchIncremental(context.Background(), config, next)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, items, "unchanged empty pages must not be ingested repeatedly")
|
||||
}
|
||||
|
||||
func TestFullSyncIncludesEmptyPageTitle(t *testing.T) {
|
||||
config := emptyPageConfig(t, `[]`, "Retained title")
|
||||
items, err := NewConnector().FetchAll(context.Background(), config, config.ResourceIDs)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "# Retained title\n", string(items[0].Content))
|
||||
}
|
||||
|
||||
func TestEmptyPageFallbackDoesNotMaskUnreadableContent(t *testing.T) {
|
||||
for _, blocks := range []string{
|
||||
`[{"id":"unknown","type":"unsupported","unsupported":{}}]`, "unauthorized", "later_failure",
|
||||
} {
|
||||
t.Run(blocks, func(t *testing.T) {
|
||||
config := emptyPageConfig(t, blocks, "Retained title")
|
||||
items, _ := NewConnector().FetchAll(context.Background(), config, config.ResourceIDs)
|
||||
require.Empty(t, items, "unreadable content must not be replaced with a title-only document")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyPageUsesUntitledFallback(t *testing.T) {
|
||||
for _, title := range []string{"", " "} {
|
||||
config := emptyPageConfig(t, `[]`, title)
|
||||
items, err := NewConnector().FetchAll(context.Background(), config, config.ResourceIDs)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "# "+defaultUntitledName+"\n", string(items[0].Content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentPageKeepsRenderedContent(t *testing.T) {
|
||||
blocks := []map[string]interface{}{{"id": "file", "type": "file", "file": map[string]interface{}{
|
||||
"type": "external", "name": "reference.pdf", "external": map[string]string{"url": ""},
|
||||
}}}
|
||||
data, err := json.Marshal(blocks)
|
||||
require.NoError(t, err)
|
||||
config := emptyPageConfig(t, string(data), "Retained title")
|
||||
items, err := NewConnector().FetchAll(context.Background(), config, config.ResourceIDs)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, items, 1)
|
||||
require.Contains(t, string(items[0].Content), "[reference.pdf]")
|
||||
require.NotContains(t, string(items[0].Content), "# Retained title")
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BlocksToMarkdown converts a tree of Notion blocks into Markdown text,
|
||||
// and collects attachment references (image, file, pdf, video, audio).
|
||||
func BlocksToMarkdown(blocks []notionBlock) (string, []attachment) {
|
||||
var b strings.Builder
|
||||
var attachments []attachment
|
||||
renderBlocks(&b, blocks, 0, &attachments)
|
||||
// Collapse 3+ consecutive newlines into 2 (avoids excessive blank lines from empty paragraphs)
|
||||
result := b.String()
|
||||
for strings.Contains(result, "\n\n\n") {
|
||||
result = strings.ReplaceAll(result, "\n\n\n", "\n\n")
|
||||
}
|
||||
return strings.TrimSpace(result) + "\n", attachments
|
||||
}
|
||||
|
||||
// renderBlocks renders a list of blocks at the given indentation depth.
|
||||
func renderBlocks(b *strings.Builder, blocks []notionBlock, depth int, attachments *[]attachment) {
|
||||
inList := false
|
||||
|
||||
for i, block := range blocks {
|
||||
isList := block.Type == "bulleted_list_item" || block.Type == "numbered_list_item" || block.Type == "to_do"
|
||||
|
||||
// End list spacing: if previous was list and current is not
|
||||
if inList && !isList {
|
||||
b.WriteString("\n")
|
||||
inList = false
|
||||
}
|
||||
|
||||
renderBlock(b, block, depth, attachments, i, blocks)
|
||||
|
||||
if isList {
|
||||
inList = true
|
||||
}
|
||||
}
|
||||
|
||||
// Close trailing list
|
||||
if inList {
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
// renderBlock renders a single block to Markdown.
|
||||
func renderBlock(b *strings.Builder, block notionBlock, depth int, attachments *[]attachment, index int, siblings []notionBlock) {
|
||||
indent := strings.Repeat(" ", depth)
|
||||
|
||||
switch block.Type {
|
||||
case "paragraph":
|
||||
rt := extractRichText(block.RawContent)
|
||||
text := renderRichText(rt)
|
||||
b.WriteString(indent + text + "\n\n")
|
||||
|
||||
case "heading_1", "heading_2", "heading_3", "heading_4":
|
||||
level := int(block.Type[len(block.Type)-1] - '0')
|
||||
rt := extractRichText(block.RawContent)
|
||||
b.WriteString(strings.Repeat("#", level) + " " + renderRichText(rt) + "\n\n")
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "bulleted_list_item":
|
||||
rt := extractRichText(block.RawContent)
|
||||
b.WriteString(indent + "- " + renderRichText(rt) + "\n")
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth+1, attachments)
|
||||
}
|
||||
|
||||
case "numbered_list_item":
|
||||
rt := extractRichText(block.RawContent)
|
||||
// Find position among consecutive numbered_list_items
|
||||
num := 1
|
||||
for j := index - 1; j >= 0 && siblings[j].Type == "numbered_list_item"; j-- {
|
||||
num++
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("%s%d. %s\n", indent, num, renderRichText(rt)))
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth+1, attachments)
|
||||
}
|
||||
|
||||
case "to_do":
|
||||
rt := extractRichText(block.RawContent)
|
||||
checked := extractBool(block.RawContent, "checked")
|
||||
checkbox := "[ ]"
|
||||
if checked {
|
||||
checkbox = "[x]"
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("%s- %s %s\n", indent, checkbox, renderRichText(rt)))
|
||||
|
||||
case "toggle":
|
||||
rt := extractRichText(block.RawContent)
|
||||
b.WriteString(fmt.Sprintf("<details><summary>%s</summary>\n\n", renderRichText(rt)))
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
b.WriteString("</details>\n\n")
|
||||
|
||||
case "code":
|
||||
rt := extractRichText(block.RawContent)
|
||||
lang := extractString(block.RawContent, "language")
|
||||
b.WriteString(fmt.Sprintf("```%s\n%s\n```\n\n", lang, renderRichText(rt)))
|
||||
|
||||
case "quote", "meeting_notes":
|
||||
rt := extractRichText(block.RawContent)
|
||||
text := renderRichText(rt)
|
||||
for _, line := range strings.Split(text, "\n") {
|
||||
b.WriteString("> " + line + "\n")
|
||||
}
|
||||
b.WriteString("\n")
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "callout":
|
||||
rt := extractRichText(block.RawContent)
|
||||
icon := extractIcon(block.RawContent)
|
||||
prefix := ""
|
||||
if icon != "" {
|
||||
prefix = icon + " "
|
||||
}
|
||||
b.WriteString("> " + prefix + renderRichText(rt) + "\n\n")
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "divider":
|
||||
b.WriteString("---\n\n")
|
||||
|
||||
case "equation":
|
||||
expr := extractString(block.RawContent, "expression")
|
||||
b.WriteString("$$" + expr + "$$\n\n")
|
||||
|
||||
case "table":
|
||||
renderTable(b, block)
|
||||
|
||||
case "image":
|
||||
file, caption := extractFileAndCaption(block.RawContent)
|
||||
url := file.GetURL()
|
||||
b.WriteString(fmt.Sprintf("\n\n", caption, url))
|
||||
if url != "" {
|
||||
*attachments = append(*attachments, attachment{
|
||||
URL: url,
|
||||
FileName: fileNameFromURL(url, "image"),
|
||||
Type: "image",
|
||||
})
|
||||
}
|
||||
|
||||
case "file", "pdf", "video", "audio":
|
||||
renderMediaBlock(b, block, attachments)
|
||||
|
||||
case "bookmark", "link_preview":
|
||||
url := extractString(block.RawContent, "url")
|
||||
caption := ""
|
||||
if rt := extractCaptionText(block.RawContent); rt != "" {
|
||||
caption = rt
|
||||
} else {
|
||||
caption = url
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("[%s](%s)\n\n", caption, url))
|
||||
|
||||
case "embed":
|
||||
url := extractString(block.RawContent, "url")
|
||||
b.WriteString(fmt.Sprintf("[%s](%s)\n\n", url, url))
|
||||
|
||||
case "link_to_page":
|
||||
// Render as a link; the actual page title is not available in block data
|
||||
pageID := extractLinkToPageID(block.RawContent)
|
||||
b.WriteString(fmt.Sprintf("[Page %s](https://notion.so/%s)\n\n", pageID, strings.ReplaceAll(pageID, "-", "")))
|
||||
|
||||
case "synced_block":
|
||||
// Render children (the synced content)
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "column_list":
|
||||
// Render each column sequentially
|
||||
if len(block.Children) > 0 {
|
||||
for _, col := range block.Children {
|
||||
if len(col.Children) > 0 {
|
||||
renderBlocks(b, col.Children, depth, attachments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case "column":
|
||||
// Handled by column_list
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "tab_list":
|
||||
// Render each tab's content sequentially (similar to column_list)
|
||||
if len(block.Children) > 0 {
|
||||
for _, tab := range block.Children {
|
||||
if len(tab.Children) > 0 {
|
||||
renderBlocks(b, tab.Children, depth, attachments)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case "tab":
|
||||
// Render tab content sequentially
|
||||
if len(block.Children) > 0 {
|
||||
renderBlocks(b, block.Children, depth, attachments)
|
||||
}
|
||||
|
||||
case "child_page":
|
||||
// Render as a link in the parent page so it's not empty.
|
||||
// The child page itself is fetched as a separate knowledge item by connector layer.
|
||||
title := extractString(block.RawContent, "title")
|
||||
if title == "" {
|
||||
title = "Untitled"
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("- [%s](https://notion.so/%s)\n", title, strings.ReplaceAll(block.ID, "-", "")))
|
||||
|
||||
case "child_database":
|
||||
title := extractString(block.RawContent, "title")
|
||||
if title == "" {
|
||||
title = "Database"
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("- [%s](https://notion.so/%s)\n", title, strings.ReplaceAll(block.ID, "-", "")))
|
||||
|
||||
case "table_of_contents", "breadcrumb", "template", "table_row", "unsupported":
|
||||
// Skip — no meaningful content
|
||||
|
||||
default:
|
||||
// Unknown block type — skip silently for forward compatibility
|
||||
}
|
||||
}
|
||||
|
||||
// renderMediaBlock renders a file/pdf/video/audio block as a Markdown link and collects the attachment.
|
||||
func renderMediaBlock(b *strings.Builder, block notionBlock, attachments *[]attachment) {
|
||||
file, _ := extractFileAndCaption(block.RawContent)
|
||||
url := file.GetURL()
|
||||
name := file.Name
|
||||
if name == "" {
|
||||
name = fileNameFromURL(url, block.Type)
|
||||
}
|
||||
b.WriteString(fmt.Sprintf("[%s](%s)\n\n", name, url))
|
||||
if url != "" {
|
||||
*attachments = append(*attachments, attachment{
|
||||
URL: url,
|
||||
FileName: name,
|
||||
Type: block.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// renderTable converts a table block (with table_row children) to Markdown.
|
||||
func renderTable(b *strings.Builder, block notionBlock) {
|
||||
if len(block.Children) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
for i, row := range block.Children {
|
||||
cells := extractTableCells(row.RawContent)
|
||||
var parts []string
|
||||
for _, cell := range cells {
|
||||
parts = append(parts, strings.ReplaceAll(renderRichText(cell), "|", "\\|"))
|
||||
}
|
||||
b.WriteString("| " + strings.Join(parts, " | ") + " |\n")
|
||||
|
||||
// Markdown tables always need a separator after the first row
|
||||
if i == 0 {
|
||||
var sep []string
|
||||
for range parts {
|
||||
sep = append(sep, "---")
|
||||
}
|
||||
b.WriteString("| " + strings.Join(sep, " | ") + " |\n")
|
||||
}
|
||||
}
|
||||
b.WriteString("\n")
|
||||
}
|
||||
|
||||
// --- Rich text rendering ---
|
||||
|
||||
// renderRichText converts a slice of rich text elements to Markdown.
|
||||
func renderRichText(texts []notionRichText) string {
|
||||
var b strings.Builder
|
||||
for _, rt := range texts {
|
||||
text := richTextToString(rt)
|
||||
text = applyAnnotations(text, rt.Annotations)
|
||||
if rt.Href != "" && !rt.Annotations.Code {
|
||||
text = fmt.Sprintf("[%s](%s)", text, rt.Href)
|
||||
}
|
||||
b.WriteString(text)
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// richTextToString extracts the base text from a rich text element.
|
||||
func richTextToString(rt notionRichText) string {
|
||||
switch rt.Type {
|
||||
case "text":
|
||||
if rt.Text != nil {
|
||||
return rt.Text.Content
|
||||
}
|
||||
return rt.PlainText
|
||||
|
||||
case "mention":
|
||||
if rt.Mention == nil {
|
||||
return rt.PlainText
|
||||
}
|
||||
switch rt.Mention.Type {
|
||||
case "date":
|
||||
if rt.Mention.Date != nil {
|
||||
if rt.Mention.Date.End != "" {
|
||||
return rt.Mention.Date.Start + " \u2192 " + rt.Mention.Date.End
|
||||
}
|
||||
return rt.Mention.Date.Start
|
||||
}
|
||||
case "page":
|
||||
if rt.Mention.Page != nil {
|
||||
return rt.PlainText // Notion fills PlainText with page title
|
||||
}
|
||||
case "database", "data_source":
|
||||
if rt.Mention.Database != nil {
|
||||
return rt.PlainText
|
||||
}
|
||||
case "link_preview":
|
||||
if rt.Mention.LinkPreview != nil {
|
||||
return rt.Mention.LinkPreview.URL
|
||||
}
|
||||
}
|
||||
return rt.PlainText
|
||||
|
||||
case "equation":
|
||||
if rt.Equation != nil {
|
||||
return "$" + rt.Equation.Expression + "$"
|
||||
}
|
||||
return rt.PlainText
|
||||
|
||||
default:
|
||||
return rt.PlainText
|
||||
}
|
||||
}
|
||||
|
||||
// applyAnnotations wraps text with Markdown formatting based on annotations.
|
||||
func applyAnnotations(text string, ann notionAnnotations) string {
|
||||
if text == "" {
|
||||
return text
|
||||
}
|
||||
if ann.Code {
|
||||
text = "`" + text + "`"
|
||||
}
|
||||
if ann.Bold && ann.Italic {
|
||||
text = "***" + text + "***"
|
||||
} else if ann.Bold {
|
||||
text = "**" + text + "**"
|
||||
} else if ann.Italic {
|
||||
text = "*" + text + "*"
|
||||
}
|
||||
if ann.Strikethrough {
|
||||
text = "~~" + text + "~~"
|
||||
}
|
||||
if ann.Underline {
|
||||
text = "<u>" + text + "</u>"
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// --- Raw content extraction helpers ---
|
||||
|
||||
func extractRichText(raw json.RawMessage) []notionRichText {
|
||||
if raw == nil {
|
||||
return nil
|
||||
}
|
||||
var content struct {
|
||||
RichText []notionRichText `json:"rich_text"`
|
||||
}
|
||||
json.Unmarshal(raw, &content)
|
||||
return content.RichText
|
||||
}
|
||||
|
||||
func extractString(raw json.RawMessage, key string) string {
|
||||
if raw == nil {
|
||||
return ""
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return ""
|
||||
}
|
||||
val, ok := m[key]
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
var s string
|
||||
json.Unmarshal(val, &s)
|
||||
return s
|
||||
}
|
||||
|
||||
func extractBool(raw json.RawMessage, key string) bool {
|
||||
if raw == nil {
|
||||
return false
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return false
|
||||
}
|
||||
val, ok := m[key]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
var b bool
|
||||
json.Unmarshal(val, &b)
|
||||
return b
|
||||
}
|
||||
|
||||
func extractIcon(raw json.RawMessage) string {
|
||||
if raw == nil {
|
||||
return ""
|
||||
}
|
||||
var content struct {
|
||||
Icon *struct {
|
||||
Type string `json:"type"`
|
||||
Emoji string `json:"emoji,omitempty"`
|
||||
} `json:"icon"`
|
||||
}
|
||||
json.Unmarshal(raw, &content)
|
||||
if content.Icon != nil && content.Icon.Type == "emoji" {
|
||||
return content.Icon.Emoji
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractFileAndCaption(raw json.RawMessage) (notionFile, string) {
|
||||
var file notionFile
|
||||
if raw != nil {
|
||||
json.Unmarshal(raw, &file)
|
||||
}
|
||||
captionText := ""
|
||||
if len(file.Caption) > 0 {
|
||||
captionText = renderRichText(file.Caption)
|
||||
}
|
||||
return file, captionText
|
||||
}
|
||||
|
||||
func extractCaptionText(raw json.RawMessage) string {
|
||||
if raw == nil {
|
||||
return ""
|
||||
}
|
||||
var content struct {
|
||||
Caption []notionRichText `json:"caption"`
|
||||
}
|
||||
json.Unmarshal(raw, &content)
|
||||
if len(content.Caption) > 0 {
|
||||
return renderRichText(content.Caption)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractTableCells(raw json.RawMessage) [][]notionRichText {
|
||||
if raw == nil {
|
||||
return nil
|
||||
}
|
||||
var content struct {
|
||||
Cells [][]notionRichText `json:"cells"`
|
||||
}
|
||||
json.Unmarshal(raw, &content)
|
||||
return content.Cells
|
||||
}
|
||||
|
||||
func extractLinkToPageID(raw json.RawMessage) string {
|
||||
if raw == nil {
|
||||
return ""
|
||||
}
|
||||
var content struct {
|
||||
Type string `json:"type"`
|
||||
PageID string `json:"page_id,omitempty"`
|
||||
}
|
||||
json.Unmarshal(raw, &content)
|
||||
return content.PageID
|
||||
}
|
||||
|
||||
func fileNameFromURL(url, fallbackType string) string {
|
||||
if url == "" {
|
||||
return fallbackType
|
||||
}
|
||||
// Extract filename from URL path (before query params)
|
||||
path := url
|
||||
if idx := strings.Index(path, "?"); idx >= 0 {
|
||||
path = path[:idx]
|
||||
}
|
||||
if idx := strings.LastIndex(path, "/"); idx >= 0 {
|
||||
name := path[idx+1:]
|
||||
if name != "" {
|
||||
return name
|
||||
}
|
||||
}
|
||||
return fallbackType
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRenderRichText(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
texts []notionRichText
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "plain text",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "hello", Text: ¬ionTextContent{Content: "hello"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
expected: "hello",
|
||||
},
|
||||
{
|
||||
name: "bold text",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "bold", Text: ¬ionTextContent{Content: "bold"}, Annotations: notionAnnotations{Bold: true}},
|
||||
},
|
||||
expected: "**bold**",
|
||||
},
|
||||
{
|
||||
name: "italic text",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "italic", Text: ¬ionTextContent{Content: "italic"}, Annotations: notionAnnotations{Italic: true}},
|
||||
},
|
||||
expected: "*italic*",
|
||||
},
|
||||
{
|
||||
name: "code text",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "code", Text: ¬ionTextContent{Content: "code"}, Annotations: notionAnnotations{Code: true}},
|
||||
},
|
||||
expected: "`code`",
|
||||
},
|
||||
{
|
||||
name: "strikethrough",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "del", Text: ¬ionTextContent{Content: "del"}, Annotations: notionAnnotations{Strikethrough: true}},
|
||||
},
|
||||
expected: "~~del~~",
|
||||
},
|
||||
{
|
||||
name: "underline",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "ul", Text: ¬ionTextContent{Content: "ul"}, Annotations: notionAnnotations{Underline: true}},
|
||||
},
|
||||
expected: "<u>ul</u>",
|
||||
},
|
||||
{
|
||||
name: "bold italic combo",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "bi", Text: ¬ionTextContent{Content: "bi"}, Annotations: notionAnnotations{Bold: true, Italic: true}},
|
||||
},
|
||||
expected: "***bi***",
|
||||
},
|
||||
{
|
||||
name: "text with link",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "click", Href: "https://example.com", Text: ¬ionTextContent{Content: "click"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
expected: "[click](https://example.com)",
|
||||
},
|
||||
{
|
||||
name: "equation",
|
||||
texts: []notionRichText{
|
||||
{Type: "equation", PlainText: "E=mc^2", Equation: ¬ionEquation{Expression: "E=mc^2"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
expected: "$E=mc^2$",
|
||||
},
|
||||
{
|
||||
name: "date mention",
|
||||
texts: []notionRichText{
|
||||
{Type: "mention", PlainText: "2026-01-15", Mention: ¬ionMention{
|
||||
Type: "date", Date: ¬ionDateMention{Start: "2026-01-15"},
|
||||
}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
expected: "2026-01-15",
|
||||
},
|
||||
{
|
||||
name: "date mention with end",
|
||||
texts: []notionRichText{
|
||||
{Type: "mention", PlainText: "range", Mention: ¬ionMention{
|
||||
Type: "date", Date: ¬ionDateMention{Start: "2026-01-15", End: "2026-01-20"},
|
||||
}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
expected: "2026-01-15 \u2192 2026-01-20",
|
||||
},
|
||||
{
|
||||
name: "multiple segments",
|
||||
texts: []notionRichText{
|
||||
{Type: "text", PlainText: "hello ", Text: ¬ionTextContent{Content: "hello "}, Annotations: notionAnnotations{}},
|
||||
{Type: "text", PlainText: "world", Text: ¬ionTextContent{Content: "world"}, Annotations: notionAnnotations{Bold: true}},
|
||||
},
|
||||
expected: "hello **world**",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := renderRichText(tt.texts)
|
||||
if got != tt.expected {
|
||||
t.Errorf("renderRichText() = %q, want %q", got, tt.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func makeBlock(t *testing.T, blockType string, content interface{}) notionBlock {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(content)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal block content: %v", err)
|
||||
}
|
||||
return notionBlock{
|
||||
ID: "blk-test",
|
||||
Type: blockType,
|
||||
RawContent: raw,
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Paragraph(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "paragraph", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Hello world", Text: ¬ionTextContent{Content: "Hello world"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, attachments := BlocksToMarkdown(blocks)
|
||||
if md != "Hello world\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
if len(attachments) != 0 {
|
||||
t.Errorf("expected 0 attachments, got %d", len(attachments))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Headings(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "heading_1", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "H1", Text: ¬ionTextContent{Content: "H1"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
makeBlock(t, "heading_2", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "H2", Text: ¬ionTextContent{Content: "H2"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
makeBlock(t, "heading_3", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "H3", Text: ¬ionTextContent{Content: "H3"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "# H1\n\n## H2\n\n### H3\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Code(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "code", map[string]interface{}{
|
||||
"language": "go",
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "fmt.Println()", Text: ¬ionTextContent{Content: "fmt.Println()"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "```go\nfmt.Println()\n```\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_List(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "bulleted_list_item", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Item 1", Text: ¬ionTextContent{Content: "Item 1"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
makeBlock(t, "bulleted_list_item", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Item 2", Text: ¬ionTextContent{Content: "Item 2"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "- Item 1\n- Item 2\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_ToDo(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "to_do", map[string]interface{}{
|
||||
"checked": false,
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Unchecked", Text: ¬ionTextContent{Content: "Unchecked"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
makeBlock(t, "to_do", map[string]interface{}{
|
||||
"checked": true,
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Checked", Text: ¬ionTextContent{Content: "Checked"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "- [ ] Unchecked\n- [x] Checked\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Quote(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "quote", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "A wise quote", Text: ¬ionTextContent{Content: "A wise quote"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "> A wise quote\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Divider(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
{ID: "blk-div", Type: "divider"},
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
if md != "---\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Equation(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "equation", map[string]interface{}{
|
||||
"expression": "E = mc^2",
|
||||
}),
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
expected := "$$E = mc^2$$\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Image(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
makeBlock(t, "image", map[string]interface{}{
|
||||
"type": "file",
|
||||
"file": map[string]interface{}{
|
||||
"url": "https://s3.example.com/img.png",
|
||||
"expiry_time": "2026-01-15T11:00:00.000Z",
|
||||
},
|
||||
"caption": []notionRichText{
|
||||
{Type: "text", PlainText: "A photo", Text: ¬ionTextContent{Content: "A photo"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
md, attachments := BlocksToMarkdown(blocks)
|
||||
if md != "\n" {
|
||||
t.Errorf("markdown = %q", md)
|
||||
}
|
||||
if len(attachments) != 1 {
|
||||
t.Fatalf("expected 1 attachment, got %d", len(attachments))
|
||||
}
|
||||
if attachments[0].URL != "https://s3.example.com/img.png" {
|
||||
t.Errorf("attachment URL = %q", attachments[0].URL)
|
||||
}
|
||||
if attachments[0].Type != "image" {
|
||||
t.Errorf("attachment Type = %q", attachments[0].Type)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_UnknownType(t *testing.T) {
|
||||
blocks := []notionBlock{
|
||||
{ID: "blk-unknown", Type: "future_block_type"},
|
||||
}
|
||||
md, _ := BlocksToMarkdown(blocks)
|
||||
if md != "\n" {
|
||||
t.Errorf("unknown block should produce empty output, got %q", md)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_Table(t *testing.T) {
|
||||
tableBlock := notionBlock{
|
||||
ID: "blk-table",
|
||||
Type: "table",
|
||||
HasChildren: true,
|
||||
RawContent: json.RawMessage(`{"table_width": 2, "has_column_header": true}`),
|
||||
Children: []notionBlock{
|
||||
makeBlock(t, "table_row", map[string]interface{}{
|
||||
"cells": [][]notionRichText{
|
||||
{{Type: "text", PlainText: "Name", Text: ¬ionTextContent{Content: "Name"}, Annotations: notionAnnotations{}}},
|
||||
{{Type: "text", PlainText: "Age", Text: ¬ionTextContent{Content: "Age"}, Annotations: notionAnnotations{}}},
|
||||
},
|
||||
}),
|
||||
makeBlock(t, "table_row", map[string]interface{}{
|
||||
"cells": [][]notionRichText{
|
||||
{{Type: "text", PlainText: "Alice", Text: ¬ionTextContent{Content: "Alice"}, Annotations: notionAnnotations{}}},
|
||||
{{Type: "text", PlainText: "30", Text: ¬ionTextContent{Content: "30"}, Annotations: notionAnnotations{}}},
|
||||
},
|
||||
}),
|
||||
},
|
||||
}
|
||||
md, _ := BlocksToMarkdown([]notionBlock{tableBlock})
|
||||
expected := "| Name | Age |\n| --- | --- |\n| Alice | 30 |\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksToMarkdown_NestedList(t *testing.T) {
|
||||
parent := makeBlock(t, "bulleted_list_item", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Parent", Text: ¬ionTextContent{Content: "Parent"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
})
|
||||
parent.HasChildren = true
|
||||
parent.Children = []notionBlock{
|
||||
makeBlock(t, "bulleted_list_item", map[string]interface{}{
|
||||
"rich_text": []notionRichText{
|
||||
{Type: "text", PlainText: "Child", Text: ¬ionTextContent{Content: "Child"}, Annotations: notionAnnotations{}},
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
md, _ := BlocksToMarkdown([]notionBlock{parent})
|
||||
expected := "- Parent\n - Child\n"
|
||||
if md != expected {
|
||||
t.Errorf("markdown = %q, want %q", md, expected)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/time/rate"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// paginationHopCap mirrors maxPaginationHops in client.go. It is spelled as a
|
||||
// literal so this file also compiles — and then fails on behaviour — against a
|
||||
// tree that has no guard at all.
|
||||
const paginationHopCap = 10000
|
||||
|
||||
// fakeLoopBudget bounds an unguarded run a little above the guard's own cap:
|
||||
// the fake answers 400 once the budget is gone, so a regression fails with the
|
||||
// wrong error instead of paging until the test times out.
|
||||
const fakeLoopBudget = paginationHopCap + 5
|
||||
|
||||
// paginationTestClient returns a client pointed at the fake server. The
|
||||
// production 3 req/s limiter would turn a 10000-hop regression into 55 minutes
|
||||
// of waiting, so it is replaced with an unlimited one: this test is about the
|
||||
// loop's exit conditions, not its pacing.
|
||||
func paginationTestClient(t *testing.T, server *httptest.Server) *notionClient {
|
||||
t.Helper()
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
client.limiter = rate.NewLimiter(rate.Inf, 1)
|
||||
return client
|
||||
}
|
||||
|
||||
func writeListPage(w http.ResponseWriter, results string, hasMore bool, nextCursor string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = fmt.Fprintf(w, `{"object":"list","results":%s,"has_more":%t,"next_cursor":%q}`,
|
||||
results, hasMore, nextCursor)
|
||||
}
|
||||
|
||||
// Notion can answer has_more=true with a next_cursor it already returned. The
|
||||
// loop used to follow it forever; it must now stop as soon as a cursor repeats.
|
||||
func TestPaginatePagesRejectsRepeatedCursor(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if requests.Add(1) > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, "same-cursor")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).paginatePages(ctx, http.MethodPost, "/v1/search")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(2), requests.Load(),
|
||||
"the guard must reject the repeated cursor on the second page; err=%v", err)
|
||||
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
|
||||
}
|
||||
|
||||
// A vendor that invents a new cursor for every page never repeats one, so the
|
||||
// repeat guard cannot stop it: the hop cap must, and it must log why.
|
||||
func TestPaginatePagesStopsAtPaginationCap(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
n := requests.Add(1)
|
||||
if n > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, fmt.Sprintf("cursor-%d", n))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
var logs bytes.Buffer
|
||||
logger.SetOutput(&logs)
|
||||
defer logger.SetOutput(os.Stdout)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).paginatePages(ctx, http.MethodPost, "/v1/search")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "pagination exceeded 10000 pages")
|
||||
require.Equal(t, int64(paginationHopCap), requests.Load())
|
||||
require.Contains(t, logs.String(), "pagination exceeded 10000 pages",
|
||||
"hitting the hop cap must be visible in the log")
|
||||
}
|
||||
|
||||
// The guard must not truncate a listing that genuinely spans several pages.
|
||||
func TestPaginatePagesMergesRealPages(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var req map[string]interface{}
|
||||
_ = json.Unmarshal(body, &req)
|
||||
if cursor, _ := req["start_cursor"].(string); cursor == "" {
|
||||
writeListPage(w, `[{"id":"page-1","object":"page"}]`, true, "cursor-2")
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[{"id":"page-2","object":"page"}]`, false, "")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pages, err := paginationTestClient(t, server).paginatePages(ctx, http.MethodPost, "/v1/search")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, pages, 2)
|
||||
require.Equal(t, "page-1", pages[0].ID)
|
||||
require.Equal(t, "page-2", pages[1].ID)
|
||||
require.Equal(t, int64(2), requests.Load())
|
||||
}
|
||||
|
||||
// GetBlockChildrenFlat is the same cursor loop on the block endpoint and used
|
||||
// to spin the same way during resource discovery.
|
||||
func TestGetBlockChildrenFlatRejectsRepeatedCursor(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if requests.Add(1) > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, "same-cursor")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).GetBlockChildrenFlat(ctx, "block-1")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(2), requests.Load(),
|
||||
"the guard must reject the repeated cursor on the second page; err=%v", err)
|
||||
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
|
||||
}
|
||||
|
||||
// GetBlockChildrenAll is the recursive sibling of GetBlockChildrenFlat and
|
||||
// carried the same unbounded cursor loop. Its own maxBlocksPerPage fallback
|
||||
// counts blocks already appended, so a vendor answering empty results with
|
||||
// has_more=true keeps that counter at zero forever and the loop never exits.
|
||||
func TestGetBlockChildrenAllRejectsRepeatedCursor(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if requests.Add(1) > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, "same-cursor")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).GetBlockChildrenAll(ctx, "block-1")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(2), requests.Load(),
|
||||
"the guard must reject the repeated cursor on the second page; err=%v", err)
|
||||
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
|
||||
}
|
||||
|
||||
// A vendor that mints a fresh cursor for every empty page never repeats one, so
|
||||
// only the hop cap can end the recursive walk.
|
||||
func TestGetBlockChildrenAllStopsAtPaginationCap(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
n := requests.Add(1)
|
||||
if n > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, fmt.Sprintf("cursor-%d", n))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).GetBlockChildrenAll(ctx, "block-1")
|
||||
require.Error(t, err)
|
||||
require.Contains(t, err.Error(), "pagination exceeded 10000 pages")
|
||||
require.Equal(t, int64(paginationHopCap), requests.Load())
|
||||
}
|
||||
|
||||
// The recursive walk must still merge a genuinely multi-page listing.
|
||||
func TestGetBlockChildrenAllMergesRealPages(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
if r.URL.Query().Get("start_cursor") == "" {
|
||||
writeListPage(w, `[{"id":"block-1","type":"paragraph",`+
|
||||
`"paragraph":{"rich_text":[{"type":"text","text":{"content":"one"},"plain_text":"one"}]}}]`,
|
||||
true, "cursor-2")
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[{"id":"block-2","type":"paragraph",`+
|
||||
`"paragraph":{"rich_text":[{"type":"text","text":{"content":"two"},"plain_text":"two"}]}}]`,
|
||||
false, "")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
blocks, err := paginationTestClient(t, server).GetBlockChildrenAll(ctx, "block-1")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, blocks, 2)
|
||||
require.Equal(t, "block-1", blocks[0].ID)
|
||||
require.Equal(t, "block-2", blocks[1].ID)
|
||||
require.Equal(t, int64(2), requests.Load())
|
||||
}
|
||||
|
||||
// Data source queries page through queryDataSourceWindow since #3845, so the
|
||||
// repeated-cursor guard has to cover that loop too.
|
||||
func TestQueryDataSourceAllRejectsRepeatedCursor(t *testing.T) {
|
||||
var requests atomic.Int64
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
if requests.Add(1) > fakeLoopBudget {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
writeListPage(w, `[]`, true, "same-cursor")
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, err := paginationTestClient(t, server).queryDataSourceAll(ctx, "/v1/data_sources/ds-1/query")
|
||||
require.Error(t, err)
|
||||
require.Equal(t, int64(2), requests.Load(),
|
||||
"the guard must reject the repeated cursor on the second page; err=%v", err)
|
||||
require.Contains(t, err.Error(), `repeated next_cursor "same-cursor"`)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A Notion data source query stops at 10,000 results and reports has_more=false
|
||||
// together with request_status.type="incomplete". A capped query is no longer the
|
||||
// end of the read: the client continues in created_time windows (see
|
||||
// query_windows_test.go). These tests pin down what a window that cannot advance
|
||||
// does instead — stop, stay visible, and never drive deletions.
|
||||
// See https://developers.notion.com/guides/data-apis/query-large-data-sources
|
||||
|
||||
const truncationReason = "query_result_limit_reached"
|
||||
|
||||
func truncationIncomplete() map[string]interface{} {
|
||||
return map[string]interface{}{"type": "incomplete", "incomplete_reason": truncationReason}
|
||||
}
|
||||
|
||||
func truncationRecord(id string) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"id": id,
|
||||
"object": "page",
|
||||
"url": "https://notion.so/" + id,
|
||||
"last_edited_time": "2026-01-02T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "data_source_id", "data_source_id": "ds-1"},
|
||||
"properties": map[string]interface{}{
|
||||
"Name": map[string]interface{}{
|
||||
"type": "title",
|
||||
"title": []interface{}{map[string]interface{}{"plain_text": "Row " + id}},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func truncationDataSourceRow() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"id": "ds-1",
|
||||
"object": "data_source",
|
||||
"url": "https://notion.so/ds-1",
|
||||
"last_edited_time": "2026-01-02T10:00:00.000Z",
|
||||
"in_trash": false,
|
||||
"parent": map[string]interface{}{"type": "workspace", "workspace": true},
|
||||
"title": []interface{}{map[string]interface{}{"plain_text": "Large Database"}},
|
||||
}
|
||||
}
|
||||
|
||||
func truncationPrevCursor() *types.SyncCursor {
|
||||
jan1 := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC)
|
||||
return buildCursor(map[string]time.Time{
|
||||
"ds-1": jan1,
|
||||
"r1": jan1,
|
||||
"r2": jan1,
|
||||
"r3": jan1,
|
||||
"r4": jan1,
|
||||
})
|
||||
}
|
||||
|
||||
func TestPaginatedResponseParsesRequestStatus(t *testing.T) {
|
||||
t.Run("incomplete", func(t *testing.T) {
|
||||
var resp paginatedResponse
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"object":"list","results":[],"has_more":false,`+
|
||||
`"next_cursor":null,"request_status":{"type":"incomplete",`+
|
||||
`"incomplete_reason":"`+truncationReason+`"}}`), &resp))
|
||||
require.True(t, resp.isIncomplete())
|
||||
require.Equal(t, truncationReason, resp.RequestStatus.IncompleteReason)
|
||||
})
|
||||
|
||||
t.Run("absent", func(t *testing.T) {
|
||||
var resp paginatedResponse
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"object":"list","results":[],"has_more":false}`), &resp))
|
||||
require.False(t, resp.isIncomplete())
|
||||
require.Nil(t, resp.RequestStatus)
|
||||
})
|
||||
|
||||
t.Run("explicit complete", func(t *testing.T) {
|
||||
var resp paginatedResponse
|
||||
require.NoError(t, json.Unmarshal([]byte(`{"results":[],"has_more":false,`+
|
||||
`"request_status":{"type":"complete"}}`), &resp))
|
||||
require.False(t, resp.isIncomplete())
|
||||
})
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllStopsWhenWindowCannotAdvance(t *testing.T) {
|
||||
logs := captureNotionLogs(t)
|
||||
// More rows than one query returns share a single created_time, so the second
|
||||
// window starts where the first one did and would return the same rows again.
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: []windowTestRow{
|
||||
{id: "r1", createdTime: "2026-01-01T10:00:00Z"},
|
||||
{id: "r2", createdTime: "2026-01-01T10:00:00Z"},
|
||||
},
|
||||
queryLimit: 1,
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.ErrorIs(t, err, errQueryResultTruncated, "an unwalkable window must still surface the truncation")
|
||||
require.ErrorIs(t, err, errWindowNotAdvancing)
|
||||
require.Contains(t, err.Error(), truncationReason)
|
||||
require.Equal(t, []string{"r1"}, recordIDs(records), "rows already read stay available to the caller")
|
||||
require.Equal(t, int32(2), server.queryCalls(),
|
||||
"the walk must stop as soon as the window stops advancing instead of repeating the same query")
|
||||
require.Contains(t, logs.String(), "does not advance", "the stop must be explained in a warning")
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllStopsWhenRowsCarryNoCreatedTime(t *testing.T) {
|
||||
logs := captureNotionLogs(t)
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: []windowTestRow{{id: "r1"}, {id: "r2"}},
|
||||
queryLimit: 1,
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.ErrorIs(t, err, errQueryResultTruncated)
|
||||
require.ErrorIs(t, err, errWindowNotAdvancing)
|
||||
require.Equal(t, []string{"r1"}, recordIDs(records))
|
||||
require.Equal(t, int32(1), server.queryCalls(),
|
||||
"a window without any created_time cannot start another one")
|
||||
require.Contains(t, logs.String(), "no row carrying created_time")
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllStopsOnEmptyIncompleteWindow(t *testing.T) {
|
||||
logs := captureNotionLogs(t)
|
||||
server := newWindowQueryServer(t, windowQueryFake{alwaysIncomplete: true})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.ErrorIs(t, err, errQueryResultTruncated)
|
||||
require.ErrorIs(t, err, errWindowNotAdvancing)
|
||||
require.Empty(t, recordIDs(records))
|
||||
require.Equal(t, int32(1), server.queryCalls(), "an empty incomplete window must not be re-queried")
|
||||
require.Contains(t, logs.String(), "no row carrying created_time")
|
||||
}
|
||||
|
||||
func TestFetchIncrementalTruncatedQuerySkipsDeletions(t *testing.T) {
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
searchResults: []interface{}{truncationDataSourceRow()},
|
||||
rows: []windowTestRow{
|
||||
{id: "r1", createdTime: "2026-01-01T10:00:00Z"},
|
||||
{id: "r2", createdTime: "2026-01-01T10:00:00Z"},
|
||||
},
|
||||
queryLimit: 1,
|
||||
})
|
||||
config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"})
|
||||
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor())
|
||||
require.NoError(t, err, "a truncated round is a partial success, not a failed sync")
|
||||
require.NotNil(t, next, "a truncated round still returns a cursor")
|
||||
require.Len(t, items, 1)
|
||||
require.Equal(t, "ds-1", items[0].ExternalID)
|
||||
require.False(t, items[0].IsDeleted)
|
||||
for _, item := range items {
|
||||
require.False(t, item.IsDeleted,
|
||||
"row %s was missing only because the query was capped and must not be deleted", item.ExternalID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchIncrementalCompleteQueryStillDetectsDeletions(t *testing.T) {
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
searchResults: []interface{}{truncationDataSourceRow()},
|
||||
rows: createdTimeRows("r1", "r2"),
|
||||
})
|
||||
config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"})
|
||||
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor())
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, next)
|
||||
|
||||
deleted := map[string]bool{}
|
||||
for _, item := range items {
|
||||
if item.IsDeleted {
|
||||
deleted[item.ExternalID] = true
|
||||
}
|
||||
}
|
||||
require.Equal(t, map[string]bool{"r3": true, "r4": true}, deleted,
|
||||
"a complete result set must keep reporting genuinely absent rows as deleted")
|
||||
}
|
||||
|
||||
func TestFetchIncrementalWindowedQueryKeepsDeletionDetection(t *testing.T) {
|
||||
// The data source holds more rows than one query returns, but every window
|
||||
// advances, so the round ends complete: r4 is genuinely gone and must still be
|
||||
// reported as deleted. This guards against "never delete anything as soon as
|
||||
// windowing is involved".
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
searchResults: []interface{}{truncationDataSourceRow()},
|
||||
rows: createdTimeRows("r1", "r2", "r3"),
|
||||
queryLimit: 2,
|
||||
pageSize: 2,
|
||||
})
|
||||
config := makeNotionConfig(&Config{APIKey: "test-token"}, server.URL, []string{"ds-1"})
|
||||
|
||||
items, next, err := NewConnector().FetchIncremental(context.Background(), config, truncationPrevCursor())
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, next)
|
||||
|
||||
deleted := map[string]bool{}
|
||||
for _, item := range items {
|
||||
if item.IsDeleted {
|
||||
deleted[item.ExternalID] = true
|
||||
}
|
||||
}
|
||||
require.Equal(t, map[string]bool{"r4": true}, deleted,
|
||||
"rows read across windows prove the rows that are absent at source are deleted")
|
||||
}
|
||||
|
||||
func TestFetchPagePropagatesTruncationFromChildDatabase(t *testing.T) {
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: []windowTestRow{
|
||||
{id: "r1", createdTime: "2026-01-01T10:00:00Z"},
|
||||
{id: "r2", createdTime: "2026-01-01T10:00:00Z"},
|
||||
},
|
||||
queryLimit: 1,
|
||||
blocks: map[string][]interface{}{
|
||||
"page-1": {map[string]interface{}{
|
||||
"id": "ds-1", "type": "child_database", "has_children": true,
|
||||
"child_database": map[string]interface{}{"title": "Embedded Database"},
|
||||
}},
|
||||
},
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
page := ¬ionPage{
|
||||
ID: "page-1",
|
||||
Object: "page",
|
||||
Parent: notionParent{Type: parentTypeWorkspace},
|
||||
}
|
||||
|
||||
_, truncated, err := NewConnector().fetchPage(context.Background(), client, page, map[string]bool{})
|
||||
require.NoError(t, err)
|
||||
require.True(t, truncated, "a capped child database query must reach the incremental round")
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A single data source query returns at most 10,000 rows; the vendor's recipe for
|
||||
// reading a larger data source is to sort by created_time ascending and to start a
|
||||
// new window (filter created_time.on_or_after = the last row of the previous
|
||||
// window) every time a query comes back with request_status.type="incomplete",
|
||||
// de-duplicating rows by ID.
|
||||
// See https://developers.notion.com/guides/data-apis/query-large-data-sources
|
||||
//
|
||||
// The fake server below answers queries that way, with the vendor's per-query
|
||||
// limit, the page size and the window boundaries scaled down to test size, and it
|
||||
// records every request body so tests can assert on the window filter and on the
|
||||
// created_time sort.
|
||||
|
||||
type windowTestRow struct {
|
||||
id string
|
||||
createdTime string // RFC3339; empty emulates a row without created_time
|
||||
}
|
||||
|
||||
// createdTimeRows builds rows one minute apart, in created_time ascending order.
|
||||
func createdTimeRows(ids ...string) []windowTestRow {
|
||||
rows := make([]windowTestRow, 0, len(ids))
|
||||
base := time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC)
|
||||
for i, id := range ids {
|
||||
createdTime := base.Add(time.Duration(i) * time.Minute).Format(time.RFC3339)
|
||||
rows = append(rows, windowTestRow{id: id, createdTime: createdTime})
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
type windowQueryFake struct {
|
||||
// rows is the whole data source, in created_time ascending order.
|
||||
rows []windowTestRow
|
||||
// queryLimit is how many rows one query returns before the vendor marks it
|
||||
// incomplete; 0 means every query returns all matching rows.
|
||||
queryLimit int
|
||||
// pageSize is how many rows one page of a query holds; 0 means 100.
|
||||
pageSize int
|
||||
// markerFirstPageOnly models the vendor caveat that the incomplete marker can
|
||||
// appear before the last page received for a capped query instead of on it.
|
||||
markerFirstPageOnly bool
|
||||
// alwaysIncomplete marks every query incomplete, even one that matched nothing.
|
||||
alwaysIncomplete bool
|
||||
// omitCompleteMarker answers a complete window without request_status at all.
|
||||
omitCompleteMarker bool
|
||||
|
||||
// searchResults is served from POST /v1/search when set.
|
||||
searchResults []interface{}
|
||||
// blocks is served from GET /v1/blocks/{id}/children when set.
|
||||
blocks map[string][]interface{}
|
||||
}
|
||||
|
||||
type windowQueryServer struct {
|
||||
*httptest.Server
|
||||
|
||||
mu sync.Mutex
|
||||
requests []map[string]interface{}
|
||||
calls int32
|
||||
}
|
||||
|
||||
func (s *windowQueryServer) queryCalls() int32 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.calls
|
||||
}
|
||||
|
||||
// queryRequests returns the decoded body of every data source query served so far.
|
||||
func (s *windowQueryServer) queryRequests() []map[string]interface{} {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]map[string]interface{}(nil), s.requests...)
|
||||
}
|
||||
|
||||
func (s *windowQueryServer) serveQuery(w http.ResponseWriter, r *http.Request, fake windowQueryFake) {
|
||||
raw, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "read query request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request map[string]interface{}
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
http.Error(w, "unmarshal query request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.calls++
|
||||
s.requests = append(s.requests, request)
|
||||
s.mu.Unlock()
|
||||
|
||||
response, errText := fake.answer(request)
|
||||
if errText != "" {
|
||||
http.Error(w, errText, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// answer builds the response the vendor would send for one query request. The
|
||||
// second result is a non-empty error text when the request cannot be served.
|
||||
func (f windowQueryFake) answer(request map[string]interface{}) (map[string]interface{}, string) {
|
||||
lower, errText := requestWindowStart(request)
|
||||
if errText != "" {
|
||||
return nil, errText
|
||||
}
|
||||
|
||||
// The filter is applied before the per-query limit is.
|
||||
var matching []windowTestRow
|
||||
for _, row := range f.rows {
|
||||
if lower.IsZero() {
|
||||
matching = append(matching, row)
|
||||
continue
|
||||
}
|
||||
created, err := time.Parse(time.RFC3339, row.createdTime)
|
||||
if err != nil {
|
||||
return nil, "test row " + row.id + " has no parsable created_time"
|
||||
}
|
||||
if !created.Before(lower) {
|
||||
matching = append(matching, row)
|
||||
}
|
||||
}
|
||||
|
||||
// A capped query ends the window with has_more=false even though the data
|
||||
// source holds more rows.
|
||||
window := matching
|
||||
capped := f.alwaysIncomplete
|
||||
if f.queryLimit > 0 && len(window) > f.queryLimit {
|
||||
window = window[:f.queryLimit]
|
||||
capped = true
|
||||
}
|
||||
|
||||
offset, errText := requestCursorOffset(request)
|
||||
if errText != "" {
|
||||
return nil, errText
|
||||
}
|
||||
if offset > len(window) {
|
||||
return nil, "start_cursor points past the end of the window"
|
||||
}
|
||||
size := f.pageSize
|
||||
if requested, ok := request["page_size"].(float64); ok && int(requested) < size {
|
||||
size = int(requested)
|
||||
}
|
||||
end := offset + size
|
||||
if end > len(window) {
|
||||
end = len(window)
|
||||
}
|
||||
page := window[offset:end]
|
||||
|
||||
results := make([]interface{}, 0, len(page))
|
||||
for _, row := range page {
|
||||
results = append(results, windowRecord(row))
|
||||
}
|
||||
|
||||
hasMore := end < len(window)
|
||||
response := map[string]interface{}{
|
||||
"object": "list", "results": results, "has_more": hasMore, "next_cursor": nil,
|
||||
}
|
||||
if hasMore {
|
||||
response["next_cursor"] = strconv.Itoa(end)
|
||||
}
|
||||
switch {
|
||||
case capped && (!f.markerFirstPageOnly || offset == 0):
|
||||
response["request_status"] = truncationIncomplete()
|
||||
case !capped && !f.omitCompleteMarker:
|
||||
response["request_status"] = map[string]interface{}{"type": "complete"}
|
||||
}
|
||||
return response, ""
|
||||
}
|
||||
|
||||
func requestWindowStart(request map[string]interface{}) (time.Time, string) {
|
||||
filter, _ := request["filter"].(map[string]interface{})
|
||||
if filter == nil {
|
||||
return time.Time{}, ""
|
||||
}
|
||||
created, _ := filter["created_time"].(map[string]interface{})
|
||||
if created == nil {
|
||||
return time.Time{}, "query filter is missing created_time"
|
||||
}
|
||||
raw, _ := created["on_or_after"].(string)
|
||||
if raw == "" {
|
||||
return time.Time{}, "query filter is missing created_time.on_or_after"
|
||||
}
|
||||
start, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return time.Time{}, "unparsable created_time.on_or_after: " + raw
|
||||
}
|
||||
return start, ""
|
||||
}
|
||||
|
||||
func requestCursorOffset(request map[string]interface{}) (int, string) {
|
||||
raw, _ := request["start_cursor"].(string)
|
||||
if raw == "" {
|
||||
return 0, ""
|
||||
}
|
||||
offset, err := strconv.Atoi(raw)
|
||||
if err != nil {
|
||||
return 0, "unparsable start_cursor: " + raw
|
||||
}
|
||||
return offset, ""
|
||||
}
|
||||
|
||||
func windowRecord(row windowTestRow) map[string]interface{} {
|
||||
record := truncationRecord(row.id)
|
||||
if row.createdTime != "" {
|
||||
record["created_time"] = row.createdTime
|
||||
}
|
||||
return record
|
||||
}
|
||||
|
||||
func windowDataSourceInfo() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"id": "ds-1", "object": "data_source",
|
||||
"title": []interface{}{map[string]interface{}{"plain_text": "Large Database"}},
|
||||
}
|
||||
}
|
||||
|
||||
func newWindowQueryServer(t *testing.T, fake windowQueryFake) *windowQueryServer {
|
||||
t.Helper()
|
||||
if fake.pageSize <= 0 {
|
||||
fake.pageSize = 100
|
||||
}
|
||||
server := &windowQueryServer{}
|
||||
server.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch {
|
||||
case r.URL.Path == "/v1/search":
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list", "results": fake.searchResults, "has_more": false, "next_cursor": nil,
|
||||
})
|
||||
case r.URL.Path == "/v1/data_sources/ds-1" && r.Method == http.MethodGet:
|
||||
_ = json.NewEncoder(w).Encode(windowDataSourceInfo())
|
||||
case r.URL.Path == "/v1/data_sources/ds-1/query":
|
||||
server.serveQuery(w, r, fake)
|
||||
case strings.HasPrefix(r.URL.Path, "/v1/blocks/"):
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/v1/blocks/"), "/children")
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list", "results": fake.blocks[id], "has_more": false, "next_cursor": nil,
|
||||
})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
return server
|
||||
}
|
||||
|
||||
// --- Assertions on recorded requests ---
|
||||
|
||||
func recordIDs(records []notionPage) []string {
|
||||
ids := make([]string, 0, len(records))
|
||||
for _, record := range records {
|
||||
ids = append(ids, record.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// assertCreatedTimeSort pins the recipe's first step: every query sorts by
|
||||
// created_time ascending, which is what gives each window a stable order.
|
||||
func assertCreatedTimeSort(t *testing.T, request map[string]interface{}) {
|
||||
t.Helper()
|
||||
require.Equal(t, []interface{}{
|
||||
map[string]interface{}{"timestamp": "created_time", "direction": "ascending"},
|
||||
}, request["sorts"], "every query must sort by created_time ascending")
|
||||
}
|
||||
|
||||
// windowFilterStart returns filter.created_time.on_or_after from a recorded
|
||||
// request, or "" when the request carries no window filter (the first window).
|
||||
func windowFilterStart(t *testing.T, request map[string]interface{}) string {
|
||||
t.Helper()
|
||||
filter, ok := request["filter"].(map[string]interface{})
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
require.Equal(t, "created_time", filter["timestamp"], "the window filter must be a created_time filter")
|
||||
created, ok := filter["created_time"].(map[string]interface{})
|
||||
require.True(t, ok, "the window filter must carry a created_time object")
|
||||
start, ok := created["on_or_after"].(string)
|
||||
require.True(t, ok, "the window filter must carry created_time.on_or_after")
|
||||
return start
|
||||
}
|
||||
|
||||
// --- Log capture ---
|
||||
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
buf strings.Builder
|
||||
}
|
||||
|
||||
func (b *syncBuffer) Write(p []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.Write(p)
|
||||
}
|
||||
|
||||
func (b *syncBuffer) String() string {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.buf.String()
|
||||
}
|
||||
|
||||
// captureNotionLogs redirects the logger into a buffer for the duration of the
|
||||
// test so warnings about capped queries can be asserted on.
|
||||
func captureNotionLogs(t *testing.T) *syncBuffer {
|
||||
t.Helper()
|
||||
buffer := &syncBuffer{}
|
||||
logger.SetOutput(buffer)
|
||||
t.Cleanup(func() { logger.SetOutput(os.Stdout) })
|
||||
return buffer
|
||||
}
|
||||
|
||||
// --- Tests ---
|
||||
|
||||
func TestQueryDatabaseAllReadsPastTheLimitInCreatedTimeWindows(t *testing.T) {
|
||||
logs := captureNotionLogs(t)
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: createdTimeRows("r1", "r2", "r3", "r4", "r5"),
|
||||
queryLimit: 2,
|
||||
pageSize: 2,
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.NoError(t, err, "a data source larger than one query must still be read in full")
|
||||
require.Equal(t, []string{"r1", "r2", "r3", "r4", "r5"}, recordIDs(records),
|
||||
"boundary rows are returned by two windows and must be kept once, in created_time order")
|
||||
require.Equal(t, int32(4), server.queryCalls(), "every capped window must start a new query")
|
||||
|
||||
requests := server.queryRequests()
|
||||
require.Len(t, requests, 4)
|
||||
for _, request := range requests {
|
||||
assertCreatedTimeSort(t, request)
|
||||
}
|
||||
require.Empty(t, windowFilterStart(t, requests[0]), "the first window is read without a filter")
|
||||
for i, want := range []string{"2026-01-01T10:01:00Z", "2026-01-01T10:02:00Z", "2026-01-01T10:03:00Z"} {
|
||||
require.Equal(t, want, windowFilterStart(t, requests[i+1]),
|
||||
"window %d must continue from the last row of the previous window", i+2)
|
||||
}
|
||||
require.Contains(t, logs.String(), "hit the vendor per-query result limit",
|
||||
"continuing past the limit must stay visible in the logs")
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllDeduplicatesRowsByID(t *testing.T) {
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: []windowTestRow{
|
||||
{id: "r1", createdTime: "2026-01-01T10:00:00Z"},
|
||||
{id: "r1", createdTime: "2026-01-01T10:00:00Z"},
|
||||
{id: "r2", createdTime: "2026-01-01T10:01:00Z"},
|
||||
},
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"r1", "r2"}, recordIDs(records), "a row returned twice must be kept once")
|
||||
require.Equal(t, int32(1), server.queryCalls())
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllIncompleteMarkerBeforeLastPageStartsNextWindow(t *testing.T) {
|
||||
server := newWindowQueryServer(t, windowQueryFake{
|
||||
rows: createdTimeRows("r1", "r2", "r3", "r4"),
|
||||
queryLimit: 2,
|
||||
pageSize: 1,
|
||||
markerFirstPageOnly: true,
|
||||
})
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{"r1", "r2", "r3", "r4"}, recordIDs(records))
|
||||
require.Equal(t, int32(6), server.queryCalls(),
|
||||
"a marker seen on a non-final page makes the whole window incomplete, so the walk must continue")
|
||||
}
|
||||
|
||||
func TestQueryDatabaseAllCompleteWindowUnchanged(t *testing.T) {
|
||||
cases := map[string]windowQueryFake{
|
||||
"request_status complete": {rows: createdTimeRows("r1", "r2", "r3")},
|
||||
"no request_status": {rows: createdTimeRows("r1", "r2", "r3"), omitCompleteMarker: true},
|
||||
}
|
||||
for name, fake := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
server := newWindowQueryServer(t, fake)
|
||||
client := mustTestClient(t, "test-token", server.URL)
|
||||
|
||||
records, err := client.QueryDatabaseAll(context.Background(), "ds-1")
|
||||
require.NoError(t, err, "a result set that fits in one query must not start a second window")
|
||||
require.Equal(t, []string{"r1", "r2", "r3"}, recordIDs(records))
|
||||
require.Equal(t, int32(1), server.queryCalls())
|
||||
|
||||
requests := server.queryRequests()
|
||||
require.Len(t, requests, 1)
|
||||
require.Empty(t, windowFilterStart(t, requests[0]), "the first window is read without a filter")
|
||||
assertCreatedTimeSort(t, requests[0])
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
)
|
||||
|
||||
// childrenPageFunc decides, for the page covering [offset, end), whether the
|
||||
// response claims another page and which cursor it carries.
|
||||
type childrenPageFunc func(offset, end int) (hasMore bool, nextCursor interface{})
|
||||
|
||||
// fakeChildrenPages serves GET /v1/blocks/{blockID}/children in pages of
|
||||
// pageSize blocks, emulating Notion's pagination contract. The client does not
|
||||
// pass page_size, so the real API defaults to 100 — the same default used here.
|
||||
// It returns the number of children requests it saw via the second result.
|
||||
func fakeChildrenPages(t *testing.T, blockID string, total, pageSize int) (*httptest.Server, *int32) {
|
||||
t.Helper()
|
||||
return fakeChildrenPagesShape(t, blockID, total, pageSize, func(_, end int) (bool, interface{}) {
|
||||
if end < total {
|
||||
return true, fmt.Sprintf("cursor-%d", end)
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
}
|
||||
|
||||
// fakeChildrenPagesShape is fakeChildrenPages with per-page control over
|
||||
// has_more/next_cursor, so a test can reproduce responses the documented
|
||||
// contract does not promise (e.g. has_more=true with an empty cursor).
|
||||
func fakeChildrenPagesShape(t *testing.T, blockID string, total, pageSize int,
|
||||
page childrenPageFunc,
|
||||
) (*httptest.Server, *int32) {
|
||||
t.Helper()
|
||||
|
||||
var requests int32
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/v1/blocks/"+blockID+"/children", func(w http.ResponseWriter, r *http.Request) {
|
||||
atomic.AddInt32(&requests, 1)
|
||||
|
||||
offset := 0
|
||||
if cursor := r.URL.Query().Get("start_cursor"); cursor != "" {
|
||||
n, err := strconv.Atoi(strings.TrimPrefix(cursor, "cursor-"))
|
||||
if err != nil {
|
||||
http.Error(w, "malformed start_cursor: "+cursor, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
offset = n
|
||||
}
|
||||
|
||||
end := offset + pageSize
|
||||
if end > total {
|
||||
end = total
|
||||
}
|
||||
results := make([]map[string]interface{}, 0, end-offset)
|
||||
for i := offset; i < end; i++ {
|
||||
results = append(results, map[string]interface{}{
|
||||
"object": "block",
|
||||
"id": fmt.Sprintf("blk-%d", i+1),
|
||||
"type": "paragraph",
|
||||
"has_children": false,
|
||||
"paragraph": map[string]interface{}{"rich_text": []interface{}{}},
|
||||
})
|
||||
}
|
||||
|
||||
hasMore, nextCursor := page(offset, end)
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"object": "list",
|
||||
"results": results,
|
||||
"has_more": hasMore,
|
||||
"next_cursor": nextCursor,
|
||||
})
|
||||
})
|
||||
|
||||
ts := httptest.NewServer(mux)
|
||||
t.Cleanup(ts.Close)
|
||||
return ts, &requests
|
||||
}
|
||||
|
||||
// captureBlockCapLogs redirects the project logger into a buffer for the duration
|
||||
// of the test. ConfigureFromEnv in cleanup restores output and level.
|
||||
func captureBlockCapLogs(t *testing.T) *bytes.Buffer {
|
||||
t.Helper()
|
||||
|
||||
var buf bytes.Buffer
|
||||
logger.SetLogLevel(logger.LevelDebug)
|
||||
logger.SetOutput(&buf)
|
||||
t.Cleanup(func() { logger.ConfigureFromEnv() })
|
||||
return &buf
|
||||
}
|
||||
|
||||
// TestBlockCapWarnsOnTruncation drives the real paging loop against a fake
|
||||
// children endpoint holding 1001 blocks. The cap must still stop at 1000
|
||||
// (behavior unchanged), the 1001st block must never be requested, and the
|
||||
// truncation must be reported instead of happening silently.
|
||||
func TestBlockCapWarnsOnTruncation(t *testing.T) {
|
||||
ts, requests := fakeChildrenPages(t, "big-page", 1001, 100)
|
||||
buf := captureBlockCapLogs(t)
|
||||
|
||||
client := mustTestClient(t, "test-token", ts.URL)
|
||||
blocks, err := client.GetBlockChildrenAll(context.Background(), "big-page")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockChildrenAll() error: %v", err)
|
||||
}
|
||||
if len(blocks) != maxBlocksPerPage {
|
||||
t.Fatalf("blocks = %d, want %d (the cap itself must not change)", len(blocks), maxBlocksPerPage)
|
||||
}
|
||||
if got := atomic.LoadInt32(requests); got != 10 {
|
||||
t.Errorf("children requests = %d, want 10 (no page may be requested past the cap)", got)
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "WARN") {
|
||||
t.Fatalf("expected a Warn log entry, got:\n%s", out)
|
||||
}
|
||||
for _, want := range []string{"[Notion]", "big-page", "exceeded 1000 blocks", "truncating"} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("truncation warning missing %q, got:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, "without a next_cursor") {
|
||||
t.Errorf("well-formed pagination must not trigger the cursor warning, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockCapWarnsWhenHasMoreHasNoCursor covers the response the documented
|
||||
// contract does not promise: the page that reaches the cap claims has_more=true
|
||||
// but carries no next_cursor, so pagination cannot continue. Both facts must be
|
||||
// reported — the cap hit and the unusable cursor. This is the exact cell that
|
||||
// used to be silent: the old predicate required a non-empty cursor, so the cap
|
||||
// warning was skipped and the dropped tail left no trace at all.
|
||||
func TestBlockCapWarnsWhenHasMoreHasNoCursor(t *testing.T) {
|
||||
const total = maxBlocksPerPage + 1
|
||||
ts, requests := fakeChildrenPagesShape(t, "odd-page", total, 100, func(_, end int) (bool, interface{}) {
|
||||
if end == maxBlocksPerPage {
|
||||
return true, nil // has_more=true with no usable cursor
|
||||
}
|
||||
if end < total {
|
||||
return true, fmt.Sprintf("cursor-%d", end)
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
buf := captureBlockCapLogs(t)
|
||||
|
||||
client := mustTestClient(t, "test-token", ts.URL)
|
||||
blocks, err := client.GetBlockChildrenAll(context.Background(), "odd-page")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockChildrenAll() error: %v", err)
|
||||
}
|
||||
if len(blocks) != maxBlocksPerPage {
|
||||
t.Fatalf("blocks = %d, want %d (the cap itself must not change)", len(blocks), maxBlocksPerPage)
|
||||
}
|
||||
if got := atomic.LoadInt32(requests); got != 10 {
|
||||
t.Errorf("children requests = %d, want 10 (an empty cursor must stop pagination)", got)
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "WARN") {
|
||||
t.Fatalf("expected a Warn log entry, got:\n%s", out)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"[Notion]", "odd-page", "exceeded 1000 blocks",
|
||||
"has_more=true", "without a next_cursor", "remaining blocks are not synced",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("warning missing %q, got:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHasMoreWithoutCursorWarnsBelowTheCap pins the other half of the anomaly:
|
||||
// has_more=true with an empty cursor stops pagination no matter how far below
|
||||
// the cap the client is, so a dropped tail must be reported there as well — the
|
||||
// cap warning is not what makes this case observable.
|
||||
func TestHasMoreWithoutCursorWarnsBelowTheCap(t *testing.T) {
|
||||
const total = 500
|
||||
ts, requests := fakeChildrenPagesShape(t, "odd-small-page", total, 100, func(_, end int) (bool, interface{}) {
|
||||
if end == 300 {
|
||||
return true, nil // has_more=true with no usable cursor
|
||||
}
|
||||
if end < total {
|
||||
return true, fmt.Sprintf("cursor-%d", end)
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
buf := captureBlockCapLogs(t)
|
||||
|
||||
client := mustTestClient(t, "test-token", ts.URL)
|
||||
blocks, err := client.GetBlockChildrenAll(context.Background(), "odd-small-page")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockChildrenAll() error: %v", err)
|
||||
}
|
||||
if len(blocks) != 300 {
|
||||
t.Fatalf("blocks = %d, want 300 (pagination stops at the cursorless page)", len(blocks))
|
||||
}
|
||||
if got := atomic.LoadInt32(requests); got != 3 {
|
||||
t.Errorf("children requests = %d, want 3 (no page may be requested without a cursor)", got)
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "WARN") {
|
||||
t.Fatalf("expected a Warn log entry, got:\n%s", out)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"[Notion]", "odd-small-page", "has_more=true", "without a next_cursor",
|
||||
"after 300 blocks", "remaining blocks are not synced",
|
||||
} {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Errorf("cursor warning missing %q, got:\n%s", want, out)
|
||||
}
|
||||
}
|
||||
if strings.Contains(out, "exceeded 1000 blocks") {
|
||||
t.Errorf("below the cap there is no truncation to report, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlockCapExactlyAtLimitDoesNotWarn guards the off-by-one at the cap: a
|
||||
// document whose last page ends exactly at maxBlocksPerPage has dropped
|
||||
// nothing, so no truncation warning may be emitted.
|
||||
func TestBlockCapExactlyAtLimitDoesNotWarn(t *testing.T) {
|
||||
ts, _ := fakeChildrenPages(t, "exact-page", maxBlocksPerPage, 100)
|
||||
buf := captureBlockCapLogs(t)
|
||||
|
||||
client := mustTestClient(t, "test-token", ts.URL)
|
||||
blocks, err := client.GetBlockChildrenAll(context.Background(), "exact-page")
|
||||
if err != nil {
|
||||
t.Fatalf("GetBlockChildrenAll() error: %v", err)
|
||||
}
|
||||
if len(blocks) != maxBlocksPerPage {
|
||||
t.Fatalf("blocks = %d, want %d", len(blocks), maxBlocksPerPage)
|
||||
}
|
||||
if out := buf.String(); strings.Contains(out, "truncating") {
|
||||
t.Errorf("exactly %d blocks is not truncation, got:\n%s", maxBlocksPerPage, out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocksTruncated(t *testing.T) {
|
||||
// has_more is the only signal consulted: "cap hit while has_more=true but
|
||||
// next_cursor empty" is no longer classified as "not truncated" here — the
|
||||
// paging loop warns about it unconditionally (see
|
||||
// TestBlockCapWarnsWhenHasMoreHasNoCursor and
|
||||
// TestHasMoreWithoutCursorWarnsBelowTheCap).
|
||||
cases := []struct {
|
||||
name string
|
||||
currentCount int
|
||||
hasMore bool
|
||||
want bool
|
||||
}{
|
||||
{"cap reached with a next page", 1000, true, true},
|
||||
{"cap overshot by a partial page", 1050, true, true},
|
||||
{"cap reached on the final page", 1000, false, false},
|
||||
{"cap overshot on the final page", 1050, false, false},
|
||||
{"below the cap", 999, true, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := blocksTruncated(tc.currentCount, tc.hasMore); got != tc.want {
|
||||
t.Errorf("blocksTruncated(%d, %v) = %v, want %v",
|
||||
tc.currentCount, tc.hasMore, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
// Package notion implements the Notion data source connector for WeKnora.
|
||||
//
|
||||
// It syncs pages, databases, and attachments from Notion workspaces into WeKnora knowledge bases.
|
||||
//
|
||||
// Notion API docs:
|
||||
// - Authentication: https://developers.notion.com/docs/authorization
|
||||
// - Search: https://developers.notion.com/reference/post-search
|
||||
// - Pages: https://developers.notion.com/reference/retrieve-a-page
|
||||
// - Blocks: https://developers.notion.com/reference/retrieve-a-block
|
||||
// - Databases: https://developers.notion.com/reference/retrieve-a-database
|
||||
package notion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/datasource"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// NotionAPIVersion is the Notion API version used by this connector.
|
||||
const NotionAPIVersion = "2026-03-11"
|
||||
|
||||
// DefaultBaseURL is the Notion API base URL.
|
||||
const DefaultBaseURL = "https://api.notion.com"
|
||||
|
||||
// Config holds Notion-specific configuration for the data source connector.
|
||||
type Config struct {
|
||||
APIKey string `json:"api_key"` // Internal Integration Token
|
||||
}
|
||||
|
||||
// parseNotionConfig extracts and validates Notion config from DataSourceConfig.
|
||||
func parseNotionConfig(config *types.DataSourceConfig) (*Config, error) {
|
||||
if config == nil {
|
||||
return nil, datasource.ErrInvalidConfig
|
||||
}
|
||||
|
||||
tokenVal, ok := config.Credentials["api_key"]
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%w: missing api_key", datasource.ErrInvalidCredentials)
|
||||
}
|
||||
token, ok := tokenVal.(string)
|
||||
if !ok || token == "" {
|
||||
return nil, fmt.Errorf("%w: api_key must be a non-empty string", datasource.ErrInvalidCredentials)
|
||||
}
|
||||
|
||||
return &Config{APIKey: token}, nil
|
||||
}
|
||||
|
||||
// --- API response types ---
|
||||
|
||||
// notionPage represents a Notion page or database object.
|
||||
type notionPage struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"` // "page" | "database" | "data_source" (2025-09-03+)
|
||||
Parent notionParent `json:"parent"`
|
||||
URL string `json:"url"`
|
||||
LastEditedTime time.Time `json:"last_edited_time"`
|
||||
InTrash bool `json:"in_trash"`
|
||||
// Title is extracted from properties after unmarshaling; not directly from JSON.
|
||||
Title string `json:"-"`
|
||||
// RawTitle holds the top-level title array (used by database objects).
|
||||
RawTitle json.RawMessage `json:"title,omitempty"`
|
||||
// RawProperties holds the raw JSON for property extraction.
|
||||
RawProperties json.RawMessage `json:"properties"`
|
||||
// DatabaseParent indicates where the database lives in the workspace hierarchy.
|
||||
// Only present on data_source objects (API 2025-09-03+). For example, if a database
|
||||
// is inside a page, this will be {type: "page_id", page_id: "..."}.
|
||||
DatabaseParent *notionParent `json:"database_parent,omitempty"`
|
||||
|
||||
// CreatedTime is the vendor's immutable creation timestamp for a row
|
||||
// (created_time). Data source queries sort and window by it, so unlike
|
||||
// LastEditedTime it never moves when the row is edited.
|
||||
CreatedTime time.Time `json:"created_time"`
|
||||
}
|
||||
|
||||
// Parent type constants for notionParent.Type
|
||||
const (
|
||||
parentTypeWorkspace = "workspace"
|
||||
parentTypePageID = "page_id"
|
||||
parentTypeDatabaseID = "database_id"
|
||||
parentTypeDataSourceID = "data_source_id"
|
||||
parentTypeBlockID = "block_id"
|
||||
)
|
||||
|
||||
// notionParent represents the parent relationship of a page/database.
|
||||
type notionParent struct {
|
||||
Type string `json:"type"`
|
||||
PageID string `json:"page_id,omitempty"`
|
||||
DatabaseID string `json:"database_id,omitempty"`
|
||||
DataSourceID string `json:"data_source_id,omitempty"`
|
||||
BlockID string `json:"block_id,omitempty"`
|
||||
}
|
||||
|
||||
// GetParentID returns the effective parent ID regardless of parent type.
|
||||
func (p *notionParent) GetParentID() string {
|
||||
switch p.Type {
|
||||
case parentTypePageID:
|
||||
return p.PageID
|
||||
case parentTypeDatabaseID:
|
||||
return p.DatabaseID
|
||||
case parentTypeDataSourceID:
|
||||
return p.DataSourceID
|
||||
case parentTypeBlockID:
|
||||
return p.BlockID
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// isDatabase returns true if the notionPage represents a database or data source.
|
||||
func (p *notionPage) isDatabase() bool {
|
||||
return p.Object == "database" || p.Object == "data_source"
|
||||
}
|
||||
|
||||
// notionBlock represents a single content block in a Notion page.
|
||||
// Requires custom UnmarshalJSON to extract the type-specific content.
|
||||
type notionBlock struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
HasChildren bool `json:"has_children"`
|
||||
RawContent json.RawMessage `json:"-"` // Extracted from the type-named field (e.g., "paragraph")
|
||||
Children []notionBlock `json:"-"` // Populated by client.GetBlockChildrenAll, not from API directly
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements custom JSON unmarshaling for notionBlock.
|
||||
// It extracts the dynamic type-keyed field (e.g., {"type":"paragraph","paragraph":{...}})
|
||||
// into RawContent.
|
||||
func (b *notionBlock) UnmarshalJSON(data []byte) error {
|
||||
// Use a helper struct to avoid infinite recursion
|
||||
type blockAlias struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
HasChildren bool `json:"has_children"`
|
||||
}
|
||||
|
||||
var alias blockAlias
|
||||
if err := json.Unmarshal(data, &alias); err != nil {
|
||||
return err
|
||||
}
|
||||
b.ID = alias.ID
|
||||
b.Type = alias.Type
|
||||
b.HasChildren = alias.HasChildren
|
||||
|
||||
// Extract the type-named field into RawContent
|
||||
if alias.Type != "" {
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return err
|
||||
}
|
||||
if content, ok := raw[alias.Type]; ok {
|
||||
b.RawContent = content
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// notionRichText represents a rich text element in Notion.
|
||||
type notionRichText struct {
|
||||
Type string `json:"type"` // "text" | "mention" | "equation"
|
||||
PlainText string `json:"plain_text"`
|
||||
Href string `json:"href,omitempty"`
|
||||
Annotations notionAnnotations `json:"annotations"`
|
||||
Text *notionTextContent `json:"text,omitempty"`
|
||||
Mention *notionMention `json:"mention,omitempty"`
|
||||
Equation *notionEquation `json:"equation,omitempty"`
|
||||
}
|
||||
|
||||
// notionAnnotations holds text style information.
|
||||
type notionAnnotations struct {
|
||||
Bold bool `json:"bold"`
|
||||
Italic bool `json:"italic"`
|
||||
Strikethrough bool `json:"strikethrough"`
|
||||
Underline bool `json:"underline"`
|
||||
Code bool `json:"code"`
|
||||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
// notionTextContent holds the content for "text" type rich text.
|
||||
type notionTextContent struct {
|
||||
Content string `json:"content"`
|
||||
Link *struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
// notionMention holds the content for "mention" type rich text.
|
||||
type notionMention struct {
|
||||
Type string `json:"type"` // "page" | "database" | "date" | "user" | "link_preview"
|
||||
Page *struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"page,omitempty"`
|
||||
Database *struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"database,omitempty"`
|
||||
Date *notionDateMention `json:"date,omitempty"`
|
||||
LinkPreview *struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"link_preview,omitempty"`
|
||||
}
|
||||
|
||||
// notionDateMention holds date information for a mention.
|
||||
type notionDateMention struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end,omitempty"`
|
||||
}
|
||||
|
||||
// notionEquation holds the content for "equation" type rich text.
|
||||
type notionEquation struct {
|
||||
Expression string `json:"expression"`
|
||||
}
|
||||
|
||||
// notionFile represents a file object in Notion (used by image, file, pdf blocks).
|
||||
type notionFile struct {
|
||||
Type string `json:"type"` // "file" | "external" | "file_upload"
|
||||
File *struct {
|
||||
URL string `json:"url"`
|
||||
ExpiryTime time.Time `json:"expiry_time"`
|
||||
} `json:"file,omitempty"`
|
||||
External *struct {
|
||||
URL string `json:"url"`
|
||||
} `json:"external,omitempty"`
|
||||
FileUpload *struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"file_upload,omitempty"`
|
||||
Caption []notionRichText `json:"caption,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
// GetURL returns the file URL regardless of type (hosted or external).
|
||||
// For file_upload type, returns empty — caller must resolve via client.GetFileUploadURL().
|
||||
func (f *notionFile) GetURL() string {
|
||||
if f.File != nil {
|
||||
return f.File.URL
|
||||
}
|
||||
if f.External != nil {
|
||||
return f.External.URL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// GetFileUploadID returns the file upload ID for file_upload type, empty otherwise.
|
||||
func (f *notionFile) GetFileUploadID() string {
|
||||
if f.FileUpload != nil {
|
||||
return f.FileUpload.ID
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// --- Cursor ---
|
||||
|
||||
// notionCursor tracks state for incremental sync.
|
||||
// Only PageEditTimes is used for diffing; LastSyncTime lives on types.SyncCursor.
|
||||
type notionCursor struct {
|
||||
PageEditTimes map[string]time.Time `json:"page_edit_times"` // page_id → last_edited_time
|
||||
}
|
||||
|
||||
// --- Attachment ---
|
||||
|
||||
// attachment represents a file to be downloaded from a Notion page.
|
||||
type attachment struct {
|
||||
URL string // Notion S3 signed URL (expires in 1 hour)
|
||||
FileName string
|
||||
Type string // "image" | "file" | "pdf" | "video" | "audio"
|
||||
}
|
||||
|
||||
// --- Pagination ---
|
||||
|
||||
// notionRequestStatus is the vendor's completeness marker on a paginated response.
|
||||
// Notion sets Type to "incomplete" when it capped the returned set for a vendor-side
|
||||
// reason — for example IncompleteReason "query_result_limit_reached" once a data
|
||||
// source query reaches the 10,000-row per-query limit — and still reports
|
||||
// has_more=false, so a capped page is otherwise indistinguishable from the last one.
|
||||
// See https://developers.notion.com/guides/data-apis/query-large-data-sources
|
||||
type notionRequestStatus struct {
|
||||
Type string `json:"type"` // "complete" | "incomplete"
|
||||
IncompleteReason string `json:"incomplete_reason"` // set when Type is "incomplete"
|
||||
}
|
||||
|
||||
// paginatedResponse is the common response wrapper for paginated Notion API responses.
|
||||
type paginatedResponse struct {
|
||||
Object string `json:"object"` // "list"
|
||||
Results json.RawMessage `json:"results"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor,omitempty"`
|
||||
RequestStatus *notionRequestStatus `json:"request_status,omitempty"`
|
||||
}
|
||||
|
||||
// isIncomplete reports whether the vendor marked this page as cut short.
|
||||
// It must be checked on every page, not only the last one: the marker can show up
|
||||
// before pagination stops.
|
||||
func (r *paginatedResponse) isIncomplete() bool {
|
||||
return r.RequestStatus != nil && r.RequestStatus.Type == "incomplete"
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
package notion
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestParseNotionConfig(t *testing.T) {
|
||||
t.Run("valid", func(t *testing.T) {
|
||||
cfg, err := parseNotionConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{
|
||||
"api_key": "ntn_test123",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cfg.APIKey != "ntn_test123" {
|
||||
t.Errorf("APIKey = %q, want %q", cfg.APIKey, "ntn_test123")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("nil config", func(t *testing.T) {
|
||||
_, err := parseNotionConfig(nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil config")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing api_key", func(t *testing.T) {
|
||||
_, err := parseNotionConfig(&types.DataSourceConfig{
|
||||
Credentials: map[string]interface{}{},
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing api_key")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotionBlockUnmarshalJSON(t *testing.T) {
|
||||
t.Run("paragraph block", func(t *testing.T) {
|
||||
data := []byte(`{
|
||||
"id": "block-1",
|
||||
"type": "paragraph",
|
||||
"has_children": false,
|
||||
"paragraph": {"rich_text": [{"type": "text", "plain_text": "hello"}]}
|
||||
}`)
|
||||
var block notionBlock
|
||||
if err := json.Unmarshal(data, &block); err != nil {
|
||||
t.Fatalf("unmarshal error: %v", err)
|
||||
}
|
||||
if block.ID != "block-1" {
|
||||
t.Errorf("ID = %q, want %q", block.ID, "block-1")
|
||||
}
|
||||
if block.Type != "paragraph" {
|
||||
t.Errorf("Type = %q, want %q", block.Type, "paragraph")
|
||||
}
|
||||
if block.HasChildren != false {
|
||||
t.Error("HasChildren should be false")
|
||||
}
|
||||
if block.RawContent == nil {
|
||||
t.Fatal("RawContent should not be nil")
|
||||
}
|
||||
// Verify RawContent contains the paragraph object
|
||||
var content struct {
|
||||
RichText []notionRichText `json:"rich_text"`
|
||||
}
|
||||
if err := json.Unmarshal(block.RawContent, &content); err != nil {
|
||||
t.Fatalf("unmarshal RawContent: %v", err)
|
||||
}
|
||||
if len(content.RichText) != 1 || content.RichText[0].PlainText != "hello" {
|
||||
t.Errorf("unexpected rich_text content: %+v", content.RichText)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("block with children flag", func(t *testing.T) {
|
||||
data := []byte(`{
|
||||
"id": "block-2",
|
||||
"type": "toggle",
|
||||
"has_children": true,
|
||||
"toggle": {"rich_text": [{"type": "text", "plain_text": "Details"}]}
|
||||
}`)
|
||||
var block notionBlock
|
||||
if err := json.Unmarshal(data, &block); err != nil {
|
||||
t.Fatalf("unmarshal error: %v", err)
|
||||
}
|
||||
if !block.HasChildren {
|
||||
t.Error("HasChildren should be true")
|
||||
}
|
||||
// Children is populated by client, not by unmarshal
|
||||
if block.Children != nil {
|
||||
t.Error("Children should be nil after unmarshal")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown block type", func(t *testing.T) {
|
||||
data := []byte(`{"id": "block-3", "type": "future_type", "has_children": false}`)
|
||||
var block notionBlock
|
||||
if err := json.Unmarshal(data, &block); err != nil {
|
||||
t.Fatalf("unmarshal error: %v", err)
|
||||
}
|
||||
if block.Type != "future_type" {
|
||||
t.Errorf("Type = %q", block.Type)
|
||||
}
|
||||
// RawContent may be nil for unknown types without matching field
|
||||
})
|
||||
}
|
||||
|
||||
func TestNotionFileGetURL(t *testing.T) {
|
||||
t.Run("hosted file", func(t *testing.T) {
|
||||
f := ¬ionFile{
|
||||
Type: "file",
|
||||
File: &struct {
|
||||
URL string `json:"url"`
|
||||
ExpiryTime time.Time `json:"expiry_time"`
|
||||
}{URL: "https://s3.example.com/file.pdf"},
|
||||
}
|
||||
if got := f.GetURL(); got != "https://s3.example.com/file.pdf" {
|
||||
t.Errorf("GetURL() = %q", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("external file", func(t *testing.T) {
|
||||
f := ¬ionFile{
|
||||
Type: "external",
|
||||
External: &struct {
|
||||
URL string `json:"url"`
|
||||
}{URL: "https://example.com/image.png"},
|
||||
}
|
||||
if got := f.GetURL(); got != "https://example.com/image.png" {
|
||||
t.Errorf("GetURL() = %q", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("empty file", func(t *testing.T) {
|
||||
f := ¬ionFile{Type: "file"}
|
||||
if got := f.GetURL(); got != "" {
|
||||
t.Errorf("GetURL() = %q, want empty", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user