generated from ConduitIO/conduit-connector-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
source.go
453 lines (393 loc) · 11.6 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright © 2022 Meroxa, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package notion
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"time"
notion "github.com/conduitio-labs/notionapi"
sdk "github.com/conduitio/conduit-connector-sdk"
)
type position struct {
ID string
LastEditedTime time.Time
}
func (p position) toSDKPosition() (sdk.Position, error) {
bytes, err := json.Marshal(p)
if err != nil {
return nil, fmt.Errorf("failed marshalling position: %w", err)
}
return bytes, nil
}
type recordPayload struct {
Plaintext string `json:"plaintext"`
Metadata map[string]string `json:"metadata"`
}
type Source struct {
sdk.UnimplementedSource
config Config
client *notion.Client
// lastMinuteRead is the last minute from which we
// processed all pages
lastMinuteRead time.Time
// fetchIDs contains IDs of pages which need to be fetched
fetchIDs []string
// lastPoll is the time at which we polled Notion the last time
lastPoll time.Time
}
func NewSource() sdk.Source {
return &Source{}
}
func (s *Source) Parameters() map[string]sdk.Parameter {
return map[string]sdk.Parameter{
Token: {
Default: "",
Description: "Internal integration token.",
Validations: []sdk.Validation{
sdk.ValidationRequired{},
},
},
PollInterval: {
Default: "1m",
Description: "Interval at which we poll Notion for changes. " +
"Must not be shorter than 1 minute. " +
"A Go duration string.",
},
}
}
func (s *Source) Configure(ctx context.Context, cfg map[string]string) error {
sdk.Logger(ctx).Info().Msg("Configuring a Source Connector...")
config, err := ParseConfig(cfg)
if err != nil {
return err
}
s.config = config
return nil
}
func (s *Source) Open(_ context.Context, pos sdk.Position) error {
s.client = notion.NewClient(notion.Token(s.config.token))
err := s.initPosition(pos)
if err != nil {
return fmt.Errorf("failed initializing position: %w", err)
}
return err
}
func (s *Source) initPosition(sdkPos sdk.Position) error {
if len(sdkPos) == 0 {
return nil
}
pos, err := s.fromSDKPosition(sdkPos)
if err != nil {
return err
}
s.lastMinuteRead = pos.LastEditedTime
return nil
}
func (s *Source) Read(ctx context.Context) (sdk.Record, error) {
err := s.populateIDs(ctx)
if err != nil {
return sdk.Record{}, fmt.Errorf("failed fetching page IDs: %w", err)
}
return s.nextPage(ctx)
}
func (s *Source) nextPage(ctx context.Context) (sdk.Record, error) {
if len(s.fetchIDs) == 0 {
return sdk.Record{}, sdk.ErrBackoffRetry
}
id := s.fetchIDs[0]
s.fetchIDs = s.fetchIDs[1:]
sdk.Logger(ctx).Debug().
Str("page_id", id).
Msg("fetching page")
// fetch the page
page, err := s.client.Page.Get(ctx, notion.PageID(id))
if err != nil {
// The search endpoint that we use to list all the pages
// can return stale results.
// It's also possible that a page has been deleted after
// we got the ID but before we actually read the whole page.
if s.notFound(err) {
sdk.Logger(ctx).Info().
Str("block_id", id).
Msg("the resource does not exist or the resource has not been shared with owner of the token")
return s.nextPage(ctx)
}
return sdk.Record{}, fmt.Errorf("failed fetching page %v: %w", id, err)
}
// fetch the page block and then all of its children
pageBlock, err := s.client.Block.Get(ctx, notion.BlockID(page.ID))
if err != nil {
// The search endpoint that we use to list all the pages
// can return stale results.
// It's also possible that a page has been deleted after
// we got the ID but before we actually read the whole page.
if s.notFound(err) {
sdk.Logger(ctx).Info().
Str("block_id", id).
Msg("the resource does not exist or the resource has not been shared with owner of the token")
return s.nextPage(ctx)
}
return sdk.Record{}, fmt.Errorf("failed fetching page block %v: %w", id, err)
}
children, err := s.getChildren(ctx, pageBlock)
if err != nil {
return sdk.Record{}, fmt.Errorf("failed fetching content for %v: %w", id, err)
}
record, err := s.pageToRecord(ctx, page, children)
if err != nil {
return sdk.Record{}, fmt.Errorf("failed transforming page %v to record: %w", id, err)
}
s.savePosition(page.LastEditedTime)
pos, err := s.getPosition(page)
if err != nil {
return sdk.Record{}, err
}
record.Position = pos
return record, nil
}
// getChildren gets all the child and grand-child blocks of the input block
func (s *Source) getChildren(ctx context.Context, block notion.Block) ([]notion.Block, error) {
if block.GetType() == notion.BlockTypeUnsupported {
// skip children of unsupported block types
sdk.Logger(ctx).Warn().
Str("block_type", block.GetType().String()).
Str("block_id", block.GetID().String()).
Msg("skipping children of unsupported block")
return []notion.Block{}, nil
}
var children []notion.Block
fetch := true
var cursor notion.Cursor
for fetch {
resp, err := s.client.Block.GetChildren(
ctx,
block.GetID(),
¬ion.Pagination{
StartCursor: cursor,
},
)
if err != nil {
return nil, fmt.Errorf(
"failed getting children for block ID %v, cursor %v: %w",
block.GetID(),
cursor,
err,
)
}
// get grandchildren as well
for _, child := range resp.Results {
children = append(children, child)
// Skip children of unsupported block types
if child.GetType() == notion.BlockTypeUnsupported {
sdk.Logger(ctx).Warn().
Str("block_type", child.GetType().String()).
Str("block_id", child.GetID().String()).
Msg("skipping unsupported child block")
continue
}
grandChildren, err := s.getChildren(ctx, child)
if err != nil {
return nil, err
}
children = append(children, grandChildren...)
}
fetch = resp.HasMore
cursor = notion.Cursor(resp.NextCursor)
}
return children, nil
}
func (s *Source) Ack(context.Context, sdk.Position) error {
return nil
}
func (s *Source) Teardown(context.Context) error {
return nil
}
func (s *Source) populateIDs(ctx context.Context) error {
if len(s.fetchIDs) > 0 {
return nil
}
// We don't want to sleep before the first poll attempt
if !s.lastPoll.IsZero() {
sdk.Logger(ctx).Debug().
Dur("poll_interval", s.config.pollInterval).
Msg("sleeping before checking for changes")
time.Sleep(s.config.pollInterval)
}
s.lastPoll = time.Now()
sdk.Logger(ctx).Debug().Msg("populating IDs")
fetch := true
var cursor notion.Cursor
for fetch {
results, err := s.getPages(ctx, cursor)
if err != nil {
return fmt.Errorf("search failed: %w", err)
}
s.addToFetchIDs(ctx, results)
fetch = results.HasMore
cursor = results.NextCursor
}
sdk.Logger(ctx).Info().Msgf("fetched %v IDs", len(s.fetchIDs))
return nil
}
func (s *Source) addToFetchIDs(ctx context.Context, results *notion.SearchResponse) {
for _, result := range results.Results {
switch result.GetObject().String() {
case "page":
page := result.(*notion.Page)
sdk.Logger(ctx).Trace().
Str("page_id", page.ID.String()).
Time("last_edited_time", page.LastEditedTime).
Time("created_time", page.CreatedTime).
Msg("checking if page has changed")
if s.hasChanged(page) {
s.fetchIDs = append(s.fetchIDs, page.ID.String())
}
default:
sdk.Logger(ctx).Warn().
Str("object_type", result.GetObject().String()).
Msg("object type currently not supported")
}
}
}
func (s *Source) hasChanged(page *notion.Page) bool {
// see discussion in docs/cdc.md
lastTopMinute := time.Now().Truncate(time.Minute)
return page.LastEditedTime.After(s.lastMinuteRead) &&
page.LastEditedTime.Before(lastTopMinute)
}
func (s *Source) getPages(ctx context.Context, cursor notion.Cursor) (*notion.SearchResponse, error) {
req := ¬ion.SearchRequest{
StartCursor: cursor,
Sort: ¬ion.SortObject{
Direction: notion.SortOrderASC,
Timestamp: notion.TimestampLastEdited,
},
Filter: map[string]string{
"property": "object",
"value": "page",
},
}
return s.client.Search.Do(ctx, req)
}
func (s *Source) pageToRecord(ctx context.Context, page *notion.Page, children notion.Blocks) (sdk.Record, error) {
payload, err := s.getPayload(ctx, children, s.getMetadata(page))
if err != nil {
return sdk.Record{}, fmt.Errorf("failed getting payload: %w", err)
}
return sdk.Util.Source.NewRecordCreate(
nil,
nil,
sdk.RawData(page.ID),
payload,
), nil
}
func (s *Source) getPosition(page *notion.Page) (sdk.Position, error) {
if page == nil {
return nil, nil
}
return position{
ID: page.ID.String(),
LastEditedTime: s.lastMinuteRead,
}.toSDKPosition()
}
func (s *Source) fromSDKPosition(sdkPos sdk.Position) (position, error) {
pos := position{}
err := json.Unmarshal(sdkPos, &pos)
if err != nil {
return position{}, fmt.Errorf("failed unmarshalling position: %w", err)
}
return pos, nil
}
func (s *Source) getPayload(
ctx context.Context,
children notion.Blocks,
metadata map[string]string,
) (sdk.RawData, error) {
var plainText string
for _, c := range children {
text, err := extractText(c)
if errors.Is(err, errNoExtractor) {
sdk.Logger(ctx).Warn().
Str("block_type", c.GetType().String()).
Msg("no text extractor registered")
continue
}
if err != nil {
return nil, err
}
plainText += text + "\n"
}
payload := recordPayload{
Plaintext: plainText,
Metadata: metadata,
}
return json.Marshal(payload)
}
func (s *Source) getMetadata(page *notion.Page) map[string]string {
return map[string]string{
"notion.title": s.getPageTitle(page),
"notion.url": page.URL,
"notion.createdTime": page.CreatedTime.Format(time.RFC3339),
"notion.lastEditedTime": page.LastEditedTime.Format(time.RFC3339),
"notion.createdBy": s.toJSON(page.CreatedBy),
"notion.lastEditedBy": s.toJSON(page.LastEditedBy),
"notion.archived": strconv.FormatBool(page.Archived),
"notion.parent": s.toJSON(page.Parent),
}
}
// toJSON converts `v` into a JSON string.
// In case that's not possible, the function returns an empty string.
func (s *Source) toJSON(v any) string {
bytes, err := json.Marshal(v)
if err != nil {
return ""
}
return string(bytes)
}
// getPageTitle returns the input page's title.
// In case that's not possible, the function returns an empty string.
func (s *Source) getPageTitle(page *notion.Page) string {
if page == nil || len(page.Properties) == 0 {
return ""
}
tp, ok := page.Properties["title"].(*notion.TitleProperty)
if !ok || len(tp.Title) == 0 {
return ""
}
return tp.Title[0].PlainText
}
func (s *Source) notFound(err error) bool {
nErr, ok := err.(*notion.Error)
if !ok {
return false
}
return nErr.Status == http.StatusNotFound
}
// savePosition saves the position, if it's safe to do so.
func (s *Source) savePosition(t time.Time) {
// The precision of a page's last_edited_time field is in minutes.
// Hence, to save it as a position (from which we can safely resume
// reading new records), we need to be sure that all pages from
// that minute have been read.
// todo instead of check the queue of IDs to fetch
// we can check the respective pages' last_edited_times
// and make sure nothing is left from `lastMinuteRead`.
if t.Before(s.lastPoll) && len(s.fetchIDs) == 0 {
s.lastMinuteRead = t
}
}