Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,7 @@ doc({
autosave: 1000,
readOnly: false,
retryOnError: false,
maxWriteRetries: 3,
})

col({
Expand Down Expand Up @@ -506,6 +507,7 @@ const projectDoc = defineDocument<Project>({
readOnly: false, // Optional: prevent updates
retryOnError: false, // Optional: retry on listener errors
retryInterval: 5000, // Optional: retry interval (ms)
maxWriteRetries: 3, // Optional: max retries on transient write failures
schema: ProjectSchema, // Optional: Zod schema (validates set/add)
})
```
Expand Down
52 changes: 43 additions & 9 deletions src/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
queryConstraints: definitionConstraints,
retryOnError = false,
retryInterval = 5000,
maxWriteRetries = 3,
schema,
} = definition

Expand Down Expand Up @@ -182,6 +183,8 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
let autosaveTimeout: ReturnType<typeof setTimeout> | null = null
let minLoadTimeout: ReturnType<typeof setTimeout> | null = null
let retryTimeout: ReturnType<typeof setTimeout> | null = null
let writeRetryCount = 0
let writeRetryTimeout: ReturnType<typeof setTimeout> | null = null
let minLoadTimeElapsed = false
let loaded = false
// Cached handle — returns the same reference until notify() invalidates
Expand Down Expand Up @@ -279,7 +282,7 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
state.localState = newLocalState

notify()
scheduleAutosave()
scheduleAutosave(true)
}

// Overloaded: callers can pass (id, data, opts) or (data, opts). The
Expand Down Expand Up @@ -354,7 +357,7 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
state.localState = newLocalState

notify()
scheduleAutosave()
scheduleAutosave(true)

return id
}
Expand Down Expand Up @@ -392,13 +395,26 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
state.localState = newLocalState

notify()
scheduleAutosave()
scheduleAutosave(true)
}

const scheduleAutosave = () => {
// `fromMutation` is true when called from a user edit (updateState,
// addDocument, removeDocument). Only in that case do we cancel the
// pending write-retry timer and reset the counter — a new user edit
// supersedes the previous attempt and starts with a fresh retry budget.
// Snapshot-driven calls (handleSnapshot) must NOT reset the budget so a
// stray read from the listener doesn't silently swallow a retry.
const scheduleAutosave = (fromMutation = false) => {
if (autosaveTimeout) {
clearTimeout(autosaveTimeout)
}
if (fromMutation) {
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
writeRetryCount = 0
}
if (autosave > 0) {
autosaveTimeout = setTimeout(() => {
sync()
Expand Down Expand Up @@ -459,13 +475,22 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(

await batch.commit()
} catch (error) {
console.error('Collection sync failed:', error)
state.waitingForUpdate = false
state.inflightLocalState = undefined
// Surface to React: handle.error reflects the failure and the
// listener will keep state.localState so consumers can retry by
// calling sync(). Autosave is not automatically rescheduled to
// avoid retry loops on permission errors.
if (writeRetryCount < maxWriteRetries) {
writeRetryCount++
console.warn(`[firestate] Write failed (attempt ${writeRetryCount}/${maxWriteRetries}), retrying in ${retryInterval}ms:`, error)
writeRetryTimeout = setTimeout(() => {
writeRetryTimeout = null
sync()
}, retryInterval)
return
}
// All retries exhausted — surface the error to React and the
// onError handler. localState is preserved so the caller can
// inspect the pending change or call sync() to retry manually.
writeRetryCount = 0
console.error('Collection sync failed:', error)
state.error = error as Error
store.reportError(error as Error, {
type: 'collection',
Expand All @@ -488,6 +513,11 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(

if (state.waitingForUpdate) {
state.waitingForUpdate = false
writeRetryCount = 0
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
const inflightState = state.inflightLocalState
state.inflightLocalState = undefined
const currentLocal = state.localState
Expand Down Expand Up @@ -605,6 +635,10 @@ export const createCollectionSubscription = <TData extends FirestoreObject>(
clearTimeout(retryTimeout)
retryTimeout = null
}
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
if (unsubscribeListener) {
unsubscribeListener()
unsubscribeListener = null
Expand Down
70 changes: 59 additions & 11 deletions src/document.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
readOnly: definitionReadOnly,
retryOnError = false,
retryInterval = 5000,
maxWriteRetries = 3,
schema,
} = definition

Expand Down Expand Up @@ -184,6 +185,8 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
let autosaveTimeout: ReturnType<typeof setTimeout> | null = null
let retryTimeout: ReturnType<typeof setTimeout> | null = null
let minLoadTimeout: ReturnType<typeof setTimeout> | null = null
let writeRetryCount = 0
let writeRetryTimeout: ReturnType<typeof setTimeout> | null = null
let minLoadTimeElapsed = false
let loaded = false
// Cached handle — returns the same reference until notify() invalidates
Expand Down Expand Up @@ -276,7 +279,7 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
state.isSetOperation = false

notify()
scheduleAutosave()
scheduleAutosave(true)
}

const setData = (data: TData, undoOptions: UpdateOptions = {}) => {
Expand Down Expand Up @@ -324,7 +327,7 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
state.isSetOperation = true

notify()
scheduleAutosave()
scheduleAutosave(true)
}

const deleteDocument = (undoOptions: UpdateOptions = {}) => {
Expand Down Expand Up @@ -352,13 +355,26 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
state.isSetOperation = false

notify()
scheduleAutosave()
scheduleAutosave(true)
}

const scheduleAutosave = () => {
// `fromMutation` is true when called from a user edit (updateState,
// setData, deleteDocument). Only in that case do we cancel the pending
// write-retry timer and reset the counter — a new user edit supersedes
// the previous attempt and starts with a fresh retry budget.
// Snapshot-driven calls (handleSnapshot) must NOT reset the budget so a
// stray read from the listener doesn't silently swallow a retry.
const scheduleAutosave = (fromMutation = false) => {
if (autosaveTimeout) {
clearTimeout(autosaveTimeout)
}
if (fromMutation) {
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
writeRetryCount = 0
}
if (autosave > 0) {
autosaveTimeout = setTimeout(() => {
sync()
Expand All @@ -378,9 +394,19 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
try {
await deleteDoc(docRef)
} catch (error) {
console.error('Sync failed:', error)
state.waitingForUpdate = false
state.inflightLocalState = undefined
if (writeRetryCount < maxWriteRetries) {
writeRetryCount++
console.warn(`[firestate] Write failed (attempt ${writeRetryCount}/${maxWriteRetries}), retrying in ${retryInterval}ms:`, error)
writeRetryTimeout = setTimeout(() => {
writeRetryTimeout = null
sync()
}, retryInterval)
return
}
writeRetryCount = 0
console.error('Sync failed:', error)
state.error = error as Error
store.reportError(error as Error, {
type: 'document',
Expand Down Expand Up @@ -433,14 +459,22 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
await updateDoc(docRef, flatDiff)
}
} catch (error) {
console.error('Sync failed:', error)
state.waitingForUpdate = false
state.inflightLocalState = undefined
// Surface to React: handle.error reflects the failure and the
// listener will keep state.localState so consumers can retry by
// calling sync() or by issuing another update. Autosave is not
// automatically rescheduled to avoid retry loops on permission
// errors — that policy is left to the consumer.
if (writeRetryCount < maxWriteRetries) {
writeRetryCount++
console.warn(`[firestate] Write failed (attempt ${writeRetryCount}/${maxWriteRetries}), retrying in ${retryInterval}ms:`, error)
writeRetryTimeout = setTimeout(() => {
writeRetryTimeout = null
sync()
}, retryInterval)
return
}
// All retries exhausted — surface the error to React and the
// onError handler. localState is preserved so the caller can
// inspect the pending change or call sync() to retry manually.
writeRetryCount = 0
console.error('Sync failed:', error)
state.error = error as Error
store.reportError(error as Error, {
type: 'document',
Expand All @@ -458,6 +492,11 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(

if (state.waitingForUpdate) {
state.waitingForUpdate = false
writeRetryCount = 0
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
const inflightState = state.inflightLocalState
state.inflightLocalState = undefined
const currentLocal = state.localState
Expand Down Expand Up @@ -526,6 +565,11 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
if (state.waitingForUpdate) {
state.waitingForUpdate = false
state.inflightLocalState = undefined
writeRetryCount = 0
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
}
if (minLoadTimeElapsed) {
state.isLoading = false
Expand Down Expand Up @@ -598,6 +642,10 @@ export const createDocumentSubscription = <TData extends FirestoreObject>(
clearTimeout(retryTimeout)
retryTimeout = null
}
if (writeRetryTimeout) {
clearTimeout(writeRetryTimeout)
writeRetryTimeout = null
}
if (minLoadTimeout) {
clearTimeout(minLoadTimeout)
minLoadTimeout = null
Expand Down
Loading
Loading