@tearleads/client-sdk 0.1.211 → 0.1.214
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client/containerContents/documentDiscovery.js +2 -2
- package/client/containerContents/documentDiscovery.js.map +1 -1
- package/client/organizations/organizationReadModels.js +3 -3
- package/client/organizations/organizationReadModels.js.map +1 -1
- package/data/persistence/container-contents/containerContentsPersistence.js +2 -2
- package/data/persistence/container-contents/containerContentsPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js +2 -2
- package/data/persistence/container-contents/containerMetadataMutationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js +2 -2
- package/data/persistence/container-contents/containerMetadataPullContinuationPersistence.js.map +1 -1
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js +6 -6
- package/data/persistence/container-contents/containerPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.d.ts +11 -2
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +89 -77
- package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
- package/data/persistence/documents/internal/discardDocument.js +4 -4
- package/data/persistence/documents/internal/discardDocument.js.map +1 -1
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js +3 -3
- package/data/persistence/documents/internal/discoveredDocumentUpsert.js.map +1 -1
- package/data/persistence/documents/internal/documentDeletionPersistence.js +8 -8
- package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentMutationPersistence.js +4 -3
- package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js +2 -2
- package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
- package/data/persistence/documents/internal/rowQueryPersistence.js +3 -3
- package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
- package/data/persistence/documents/internal/syncQueuePersistence.js +12 -13
- package/data/persistence/documents/internal/syncQueuePersistence.js.map +1 -1
- package/data/persistence/documents/records/documentHistoryPersistence.d.ts +24 -20
- package/data/persistence/documents/records/documentHistoryPersistence.js +59 -90
- package/data/persistence/documents/records/documentHistoryPersistence.js.map +1 -1
- package/data/persistence/documents/records/documentPendingUpdatePersistence.d.ts +10 -25
- package/data/persistence/documents/records/documentPendingUpdatePersistence.js +19 -79
- package/data/persistence/documents/records/documentPendingUpdatePersistence.js.map +1 -1
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.d.ts +4 -14
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.js +27 -42
- package/data/persistence/documents/records/documentQueuedUpdateReplacement.js.map +1 -1
- package/data/persistence/documents/records/documentRecordPersistence.d.ts +5 -8
- package/data/persistence/documents/records/documentRecordPersistence.js +2 -55
- package/data/persistence/documents/records/documentRecordPersistence.js.map +1 -1
- package/data/persistence/documents/records/documentRecordRepository.d.ts +133 -0
- package/data/persistence/documents/records/documentRecordRepository.js +286 -0
- package/data/persistence/documents/records/documentRecordRepository.js.map +1 -0
- package/data/persistence/documents/records/documentSyncFailurePersistence.d.ts +9 -12
- package/data/persistence/documents/records/documentSyncFailurePersistence.js +19 -34
- package/data/persistence/documents/records/documentSyncFailurePersistence.js.map +1 -1
- package/data/persistence/documents/records/index.d.ts +4 -19
- package/data/persistence/documents/records/index.js +5 -29
- package/data/persistence/documents/records/index.js.map +1 -1
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js +0 -43
- package/data/persistence/organizations/organizationPresentationDenialPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelMemberLoad.d.ts +7 -2
- package/data/persistence/organizations/organizationReadModelMemberLoad.js +22 -27
- package/data/persistence/organizations/organizationReadModelMemberLoad.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPersistence.js +38 -81
- package/data/persistence/organizations/organizationReadModelPersistence.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelPurge.js +0 -38
- package/data/persistence/organizations/organizationReadModelPurge.js.map +1 -1
- package/data/persistence/organizations/organizationReadModelRepository.js +264 -0
- package/data/persistence/organizations/organizationReadModelRepository.js.map +1 -0
- package/package.json +1 -1
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js +2 -2
- package/stores/documents/documentStore/sync/attachmentUploadFailure.js.map +1 -1
- package/stores/documents/documentStore/sync/syncAttachments.js +2 -2
- package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
- package/stores/documents/documentStore/sync/syncShared.js +2 -2
- package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
- package/workflows/container-contents/documentDiscovery/documentDiscoveryEvidence.js.map +1 -1
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js +2 -2
- package/workflows/container-contents/metadata/metadataIncomingUpdateIsolation.js.map +1 -1
- package/workflows/container-contents/pendingWrites/index.js +4 -3
- package/workflows/container-contents/pendingWrites/index.js.map +1 -1
- package/workflows/container-contents/recovery/accessRestoration.js +2 -2
- package/workflows/container-contents/recovery/accessRestoration.js.map +1 -1
- package/workflows/documents/index.d.ts +1 -1
- package/workflows/documents/index.js +1 -1
- package/workflows/documents/index.js.map +1 -1
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js +3 -2
- package/workflows/documents/syncRekeys/syncRecoveryRekey.js.map +1 -1
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +6 -2
- package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
- package/workflows/organizations/index.d.ts +0 -1
- package/workflows/organizations/index.js +0 -1
- package/workflows/organizations/index.js.map +1 -1
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js +7 -4
- package/workflows/organizations/policyHistory/policyHistoryAccessDenial.js.map +1 -1
- package/workflows/organizations/readModel/dataUsageReadModel.js +2 -2
- package/workflows/organizations/readModel/dataUsageReadModel.js.map +1 -1
- package/workflows/organizations/readModel/listLocalOrganizations.js +6 -4
- package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
- package/workflows/organizations/readModel/localReadModelDetails.js +8 -9
- package/workflows/organizations/readModel/localReadModelDetails.js.map +1 -1
- package/workflows/organizations/readModel/organizationPresentationAccessState.js +2 -2
- package/workflows/organizations/readModel/organizationPresentationAccessState.js.map +1 -1
- package/workflows/organizations/readModel/readModelProjection.d.ts +1 -1
- package/workflows/organizations/readModel/readModelProjection.js +12 -13
- package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js +0 -49
- package/data/persistence/organizations/organizationAccessRevocationPersistence.js.map +0 -1
- package/data/persistence/organizations/organizationGroupNamePersistence.js +0 -33
- package/data/persistence/organizations/organizationGroupNamePersistence.js.map +0 -1
- package/data/persistence/organizations/organizationProfileDocumentPointers.js +0 -32
- package/data/persistence/organizations/organizationProfileDocumentPointers.js.map +0 -1
- package/data/persistence/organizations/organizationReadModelCursorPersistence.d.ts +0 -15
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js +0 -25
- package/data/persistence/organizations/organizationReadModelCursorPersistence.js.map +0 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { and, eq } from "drizzle-orm";
|
|
2
|
+
import { getOrCreatePrincipalPolicyCoordinator } from "../../principals/principalPolicyCoordinator.js";
|
|
3
|
+
import { organizationReadModelTables } from "../../sqlite/schema/index.js";
|
|
4
|
+
import { organizationDataUsageTables } from "../../sqlite/schema/organizationDataUsageSchema.js";
|
|
5
|
+
import { organizationPresentationDenials, organizationReadModelGroups, organizationReadModelRequesters, organizationReadModelState, } from "../../sqlite/schema/organizationReadModelSchema.js";
|
|
6
|
+
import { getClientSQLitePersistenceRuntime, } from "../../sqlite/sqlitePersistenceRuntime.js";
|
|
7
|
+
import { ensureSqlTables } from "../../sqlite/sqlSchema.js";
|
|
8
|
+
import { purgeOrganizationDataUsageProjectionInTransaction } from "./organizationDataUsagePersistence.js";
|
|
9
|
+
import { notifyOrganizationReadModelInvalidated } from "./organizationReadModelInvalidation.js";
|
|
10
|
+
import { loadRequesterOrganizationReadModelGroupMembersInTransaction, } from "./organizationReadModelMemberLoad.js";
|
|
11
|
+
import { applyOrganizationReadModelResponseInTransaction, } from "./organizationReadModelPersistence.js";
|
|
12
|
+
import { loadOrganizationReadModelProjectionInTransaction, } from "./organizationReadModelProjection.js";
|
|
13
|
+
import { OrganizationReadModelIntegrityError } from "./organizationReadModelProtocol.js";
|
|
14
|
+
import { purgeOrganizationReadModelProjectionInTransaction } from "./organizationReadModelPurge.js";
|
|
15
|
+
import { assertOrganizationReadModelResponse } from "./organizationReadModelResponseAssertions.js";
|
|
16
|
+
const organizationAccessProjectionTables = [
|
|
17
|
+
...organizationReadModelTables,
|
|
18
|
+
...organizationDataUsageTables,
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* The durable organization read-model projection, its group display names,
|
|
22
|
+
* and its presentation denial markers, over one database. Invalidation
|
|
23
|
+
* notices and recovery invalidation are keyed by the executor this
|
|
24
|
+
* repository was built from.
|
|
25
|
+
*/
|
|
26
|
+
export class OrganizationReadModelRepository {
|
|
27
|
+
execSql;
|
|
28
|
+
now;
|
|
29
|
+
constructor(execSql, now = () => new Date()) {
|
|
30
|
+
this.execSql = execSql;
|
|
31
|
+
this.now = now;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The ONE load shell for the durable read-model projection: run `load` in a
|
|
35
|
+
* transaction and, if a stored row fails integrity validation, purge the
|
|
36
|
+
* organization's projection and report null. The projection is a
|
|
37
|
+
* server-refetchable cache, so the next reconcile requests a cursorless
|
|
38
|
+
* snapshot instead of every read and repair pass failing on the same row.
|
|
39
|
+
*/
|
|
40
|
+
async loadWithOrganizationReadModelIntegrityPurge(input) {
|
|
41
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
42
|
+
let purgedInvalidRows = false;
|
|
43
|
+
const result = await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
44
|
+
try {
|
|
45
|
+
return await input.load(tx);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (!(error instanceof OrganizationReadModelIntegrityError)) {
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
52
|
+
organizationId: input.organizationId,
|
|
53
|
+
tx,
|
|
54
|
+
});
|
|
55
|
+
purgedInvalidRows = true;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
if (purgedInvalidRows) {
|
|
60
|
+
// Realtime consumers may hold a caught-up lease over rows that no longer
|
|
61
|
+
// exist; the notification lets them drop it and refetch authoritatively.
|
|
62
|
+
notifyOrganizationReadModelInvalidated(this.execSql, input.organizationId);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
async loadOrganizationReadModelProjection(organizationId, currentUserId) {
|
|
67
|
+
return this.loadWithOrganizationReadModelIntegrityPurge({
|
|
68
|
+
organizationId,
|
|
69
|
+
load: (tx) => loadOrganizationReadModelProjectionInTransaction({
|
|
70
|
+
currentUserId,
|
|
71
|
+
organizationId,
|
|
72
|
+
tx,
|
|
73
|
+
}),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async loadOrganizationReadModelGroupMembers(organizationId, groupId, currentUserId) {
|
|
77
|
+
return this.loadWithOrganizationReadModelIntegrityPurge({
|
|
78
|
+
organizationId,
|
|
79
|
+
load: (tx) => loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {
|
|
80
|
+
currentUserId,
|
|
81
|
+
groupId,
|
|
82
|
+
organizationId,
|
|
83
|
+
}),
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async applyOrganizationReadModelResponse(input) {
|
|
87
|
+
assertOrganizationReadModelResponse({
|
|
88
|
+
currentUserId: input.currentUserId,
|
|
89
|
+
response: input.response,
|
|
90
|
+
});
|
|
91
|
+
// The requester prune also retires pruned users' usage projections.
|
|
92
|
+
await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
|
|
93
|
+
const disposition = await getClientSQLitePersistenceRuntime(this.execSql).transaction((tx) => applyOrganizationReadModelResponseInTransaction(tx, {
|
|
94
|
+
currentUserId: input.currentUserId,
|
|
95
|
+
now: this.now,
|
|
96
|
+
requestedCursor: input.requestedCursor,
|
|
97
|
+
response: input.response,
|
|
98
|
+
}));
|
|
99
|
+
// An applied change follows an organization hint or mutation; in-flight
|
|
100
|
+
// operations recover the directory again instead of reusing their memo.
|
|
101
|
+
if (disposition === "applied")
|
|
102
|
+
getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.response.organizationId);
|
|
103
|
+
return disposition;
|
|
104
|
+
}
|
|
105
|
+
async purgeOrganizationReadModelProjection(organizationId, options = {}) {
|
|
106
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
107
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
108
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
109
|
+
onlyRequesterUserId: options.onlyRequesterUserId,
|
|
110
|
+
organizationId,
|
|
111
|
+
tx,
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Purge one requester's access to an organization's presentation projections
|
|
117
|
+
* after the server denied that requester. The denial is requester-scoped: the
|
|
118
|
+
* shared read-model rows stay while another local identity in the same
|
|
119
|
+
* database still holds a requester row, and organization-wide rows fall with
|
|
120
|
+
* the last requester.
|
|
121
|
+
*/
|
|
122
|
+
async purgeOrganizationAccessProjection(input) {
|
|
123
|
+
await ensureSqlTables(this.execSql, organizationAccessProjectionTables);
|
|
124
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
125
|
+
await tx
|
|
126
|
+
.delete(organizationReadModelRequesters)
|
|
127
|
+
.where(and(eq(organizationReadModelRequesters.organizationId, input.organizationId), eq(organizationReadModelRequesters.userId, input.requesterUserId)))
|
|
128
|
+
.run();
|
|
129
|
+
const [remainingRequester] = await tx
|
|
130
|
+
.select({ userId: organizationReadModelRequesters.userId })
|
|
131
|
+
.from(organizationReadModelRequesters)
|
|
132
|
+
.where(eq(organizationReadModelRequesters.organizationId, input.organizationId))
|
|
133
|
+
.limit(1);
|
|
134
|
+
if (!remainingRequester) {
|
|
135
|
+
await purgeOrganizationReadModelProjectionInTransaction({
|
|
136
|
+
organizationId: input.organizationId,
|
|
137
|
+
tx,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
await purgeOrganizationDataUsageProjectionInTransaction({
|
|
141
|
+
organizationId: input.organizationId,
|
|
142
|
+
requesterUserId: input.requesterUserId,
|
|
143
|
+
tx,
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
// A denial is a realtime-hinted access change: in-flight operations recover
|
|
147
|
+
// the organization's directory again instead of reusing their memo.
|
|
148
|
+
getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(input.organizationId);
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* The cursor this requester has applied, or null when it holds none. The
|
|
152
|
+
* organization row's cursor is shared: another identity on this device may
|
|
153
|
+
* have advanced it while this requester's own fields (for example
|
|
154
|
+
* `isOrgAdmin`) still reflect an older response. Only the requester's own
|
|
155
|
+
* applied cursor, while it is still the stored projection's cursor, proves
|
|
156
|
+
* this requester is current. Realtime hints compare against it so a hint for
|
|
157
|
+
* a cursor already applied costs no read.
|
|
158
|
+
*/
|
|
159
|
+
async loadAppliedOrganizationReadModelCursor(input) {
|
|
160
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
161
|
+
const [row] = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
162
|
+
.db.select({ cursor: organizationReadModelRequesters.appliedCursor })
|
|
163
|
+
.from(organizationReadModelRequesters)
|
|
164
|
+
.innerJoin(organizationReadModelState, and(eq(organizationReadModelState.organizationId, organizationReadModelRequesters.organizationId), eq(organizationReadModelState.cursor, organizationReadModelRequesters.appliedCursor)))
|
|
165
|
+
.where(and(eq(organizationReadModelRequesters.organizationId, input.organizationId), eq(organizationReadModelRequesters.userId, input.requesterUserId)))
|
|
166
|
+
.limit(1);
|
|
167
|
+
return row?.cursor ?? null;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Every locally projected organization's pointer to its organization_profile
|
|
171
|
+
* document, keyed by organization id.
|
|
172
|
+
*
|
|
173
|
+
* This is the only container-independent handle on that document. Callers
|
|
174
|
+
* that need an org's display name from local state cannot rely on where the
|
|
175
|
+
* document is linked: the provisioner writes it under a deterministic local
|
|
176
|
+
* alias into the organization-metadata container, while a device that only
|
|
177
|
+
* *synced* it (identity recovery, another member) keys it under the server
|
|
178
|
+
* documentId in whichever container the grant arrived through.
|
|
179
|
+
*
|
|
180
|
+
* The local schema stores only the current read-model contract, so every
|
|
181
|
+
* state row is eligible to provide its profile-document pointer.
|
|
182
|
+
*/
|
|
183
|
+
async loadOrganizationProfileDocumentIds() {
|
|
184
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
185
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
186
|
+
const rows = await db
|
|
187
|
+
.select({
|
|
188
|
+
organizationId: organizationReadModelState.organizationId,
|
|
189
|
+
profileDocumentId: organizationReadModelState.profileDocumentId,
|
|
190
|
+
})
|
|
191
|
+
.from(organizationReadModelState);
|
|
192
|
+
return new Map(rows.flatMap((row) => row.profileDocumentId
|
|
193
|
+
? [[row.organizationId, row.profileDocumentId]]
|
|
194
|
+
: []));
|
|
195
|
+
}
|
|
196
|
+
async loadOrganizationGroupDisplayNames(organizationId) {
|
|
197
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
198
|
+
const { db } = getClientSQLitePersistenceRuntime(this.execSql);
|
|
199
|
+
const rows = await db
|
|
200
|
+
.select({
|
|
201
|
+
groupId: organizationReadModelGroups.groupId,
|
|
202
|
+
name: organizationReadModelGroups.name,
|
|
203
|
+
})
|
|
204
|
+
.from(organizationReadModelGroups)
|
|
205
|
+
.where(eq(organizationReadModelGroups.organizationId, organizationId));
|
|
206
|
+
return new Map(rows
|
|
207
|
+
.filter((row) => row.name.length > 0)
|
|
208
|
+
.map((row) => [row.groupId, row.name]));
|
|
209
|
+
}
|
|
210
|
+
/** Local display cache only: these labels never enter a server request. */
|
|
211
|
+
async saveOrganizationGroupDisplayNames(input) {
|
|
212
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
213
|
+
await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(async (tx) => {
|
|
214
|
+
for (const group of input.names) {
|
|
215
|
+
await tx
|
|
216
|
+
.update(organizationReadModelGroups)
|
|
217
|
+
.set({ name: group.name })
|
|
218
|
+
.where(and(eq(organizationReadModelGroups.organizationId, input.organizationId), eq(organizationReadModelGroups.groupId, group.groupId), eq(organizationReadModelGroups.stateHash, group.stateHash)))
|
|
219
|
+
.run();
|
|
220
|
+
}
|
|
221
|
+
}, input.stillCurrent);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Durably record a server denial before the revoked projection rows are
|
|
225
|
+
* purged. The marker is what keeps a failed purge plus an offline restart
|
|
226
|
+
* from serving the revoked projection; it is cleared only when an
|
|
227
|
+
* authoritative reconcile stores fresh server state for the same scope.
|
|
228
|
+
*/
|
|
229
|
+
async recordOrganizationPresentationDenials(scope, projections) {
|
|
230
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
231
|
+
const deniedAt = this.now().toISOString();
|
|
232
|
+
await getClientSQLitePersistenceRuntime(this.execSql).transaction(async (tx) => {
|
|
233
|
+
for (const projection of new Set(projections)) {
|
|
234
|
+
await tx
|
|
235
|
+
.insert(organizationPresentationDenials)
|
|
236
|
+
.values({
|
|
237
|
+
organizationId: scope.organizationId,
|
|
238
|
+
requesterUserId: scope.requesterUserId,
|
|
239
|
+
projection,
|
|
240
|
+
deniedAt,
|
|
241
|
+
})
|
|
242
|
+
.onConflictDoUpdate({
|
|
243
|
+
target: [
|
|
244
|
+
organizationPresentationDenials.organizationId,
|
|
245
|
+
organizationPresentationDenials.requesterUserId,
|
|
246
|
+
organizationPresentationDenials.projection,
|
|
247
|
+
],
|
|
248
|
+
set: { deniedAt },
|
|
249
|
+
})
|
|
250
|
+
.run();
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
async hasOrganizationPresentationDenial(scope, projection) {
|
|
255
|
+
await ensureSqlTables(this.execSql, organizationReadModelTables);
|
|
256
|
+
const rows = await getClientSQLitePersistenceRuntime(this.execSql)
|
|
257
|
+
.db.select({ projection: organizationPresentationDenials.projection })
|
|
258
|
+
.from(organizationPresentationDenials)
|
|
259
|
+
.where(and(eq(organizationPresentationDenials.organizationId, scope.organizationId), eq(organizationPresentationDenials.requesterUserId, scope.requesterUserId), eq(organizationPresentationDenials.projection, projection)))
|
|
260
|
+
.limit(1);
|
|
261
|
+
return rows.length > 0;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
//# sourceMappingURL=organizationReadModelRepository.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"organizationReadModelRepository.js","sourceRoot":"","sources":["organizationReadModelRepository.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,qCAAqC,EAAE,MAAM,6CAA6C,CAAC;AACpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,EAAE,2BAA2B,EAAE,MAAM,iDAAiD,CAAC;AAC9F,OAAO,EACL,+BAA+B,EAC/B,2BAA2B,EAC3B,+BAA+B,EAC/B,0BAA0B,GAC3B,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAgB,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iDAAiD,EAAE,MAAM,oCAAoC,CAAC;AAKv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import type { OrganizationReadModelResponse } from \"@tearleads/validators/response\";\nimport { and, eq } from \"drizzle-orm\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../principals/principalPolicyCoordinator\";\nimport { organizationReadModelTables } from \"../../sqlite/schema\";\nimport { organizationDataUsageTables } from \"../../sqlite/schema/organizationDataUsageSchema\";\nimport {\n organizationPresentationDenials,\n organizationReadModelGroups,\n organizationReadModelRequesters,\n organizationReadModelState,\n} from \"../../sqlite/schema/organizationReadModelSchema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../../sqlite/sqlSchema\";\nimport { purgeOrganizationDataUsageProjectionInTransaction } from \"./organizationDataUsagePersistence\";\nimport type {\n OrganizationPresentationDenialProjection,\n OrganizationPresentationDenialScope,\n} from \"./organizationPresentationDenialPersistence\";\nimport { notifyOrganizationReadModelInvalidated } from \"./organizationReadModelInvalidation\";\nimport {\n loadRequesterOrganizationReadModelGroupMembersInTransaction,\n type OrganizationReadModelGroupMembers,\n} from \"./organizationReadModelMemberLoad\";\nimport {\n type ApplyOrganizationReadModelResponseResult,\n applyOrganizationReadModelResponseInTransaction,\n} from \"./organizationReadModelPersistence\";\nimport {\n loadOrganizationReadModelProjectionInTransaction,\n type OrganizationReadModelProjection,\n} from \"./organizationReadModelProjection\";\nimport { OrganizationReadModelIntegrityError } from \"./organizationReadModelProtocol\";\nimport { purgeOrganizationReadModelProjectionInTransaction } from \"./organizationReadModelPurge\";\nimport { assertOrganizationReadModelResponse } from \"./organizationReadModelResponseAssertions\";\n\nconst organizationAccessProjectionTables = [\n ...organizationReadModelTables,\n ...organizationDataUsageTables,\n];\n\n/**\n * The durable organization read-model projection, its group display names,\n * and its presentation denial markers, over one database. Invalidation\n * notices and recovery invalidation are keyed by the executor this\n * repository was built from.\n */\nexport class OrganizationReadModelRepository {\n constructor(\n private readonly execSql: ExecSql,\n private readonly now: () => Date = () => new Date(),\n ) {}\n\n /**\n * The ONE load shell for the durable read-model projection: run `load` in a\n * transaction and, if a stored row fails integrity validation, purge the\n * organization's projection and report null. The projection is a\n * server-refetchable cache, so the next reconcile requests a cursorless\n * snapshot instead of every read and repair pass failing on the same row.\n */\n private async loadWithOrganizationReadModelIntegrityPurge<T>(input: {\n readonly load: (tx: ClientSQLiteTransactionScope) => Promise<T | null>;\n readonly organizationId: string;\n }): Promise<T | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n let purgedInvalidRows = false;\n const result = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(async (tx) => {\n try {\n return await input.load(tx);\n } catch (error) {\n if (!(error instanceof OrganizationReadModelIntegrityError)) {\n throw error;\n }\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n purgedInvalidRows = true;\n return null;\n }\n });\n if (purgedInvalidRows) {\n // Realtime consumers may hold a caught-up lease over rows that no longer\n // exist; the notification lets them drop it and refetch authoritatively.\n notifyOrganizationReadModelInvalidated(\n this.execSql,\n input.organizationId,\n );\n }\n return result;\n }\n\n async loadOrganizationReadModelProjection(\n organizationId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelProjection | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadOrganizationReadModelProjectionInTransaction({\n currentUserId,\n organizationId,\n tx,\n }),\n });\n }\n\n async loadOrganizationReadModelGroupMembers(\n organizationId: string,\n groupId: string,\n currentUserId: string,\n ): Promise<OrganizationReadModelGroupMembers | null> {\n return this.loadWithOrganizationReadModelIntegrityPurge({\n organizationId,\n load: (tx) =>\n loadRequesterOrganizationReadModelGroupMembersInTransaction(tx, {\n currentUserId,\n groupId,\n organizationId,\n }),\n });\n }\n\n async applyOrganizationReadModelResponse(input: {\n readonly currentUserId: string;\n readonly requestedCursor: string | null;\n readonly response: OrganizationReadModelResponse;\n }): Promise<ApplyOrganizationReadModelResponseResult> {\n assertOrganizationReadModelResponse({\n currentUserId: input.currentUserId,\n response: input.response,\n });\n // The requester prune also retires pruned users' usage projections.\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n\n const disposition = await getClientSQLitePersistenceRuntime(\n this.execSql,\n ).transaction(\n (tx): Promise<ApplyOrganizationReadModelResponseResult> =>\n applyOrganizationReadModelResponseInTransaction(tx, {\n currentUserId: input.currentUserId,\n now: this.now,\n requestedCursor: input.requestedCursor,\n response: input.response,\n }),\n );\n // An applied change follows an organization hint or mutation; in-flight\n // operations recover the directory again instead of reusing their memo.\n if (disposition === \"applied\")\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.response.organizationId,\n );\n return disposition;\n }\n\n async purgeOrganizationReadModelProjection(\n organizationId: string,\n options: { readonly onlyRequesterUserId?: string } = {},\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await purgeOrganizationReadModelProjectionInTransaction({\n onlyRequesterUserId: options.onlyRequesterUserId,\n organizationId,\n tx,\n });\n },\n );\n }\n\n /**\n * Purge one requester's access to an organization's presentation projections\n * after the server denied that requester. The denial is requester-scoped: the\n * shared read-model rows stay while another local identity in the same\n * database still holds a requester row, and organization-wide rows fall with\n * the last requester.\n */\n async purgeOrganizationAccessProjection(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationAccessProjectionTables);\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n await tx\n .delete(organizationReadModelRequesters)\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .run();\n const [remainingRequester] = await tx\n .select({ userId: organizationReadModelRequesters.userId })\n .from(organizationReadModelRequesters)\n .where(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n )\n .limit(1);\n if (!remainingRequester) {\n await purgeOrganizationReadModelProjectionInTransaction({\n organizationId: input.organizationId,\n tx,\n });\n }\n await purgeOrganizationDataUsageProjectionInTransaction({\n organizationId: input.organizationId,\n requesterUserId: input.requesterUserId,\n tx,\n });\n },\n );\n // A denial is a realtime-hinted access change: in-flight operations recover\n // the organization's directory again instead of reusing their memo.\n getOrCreatePrincipalPolicyCoordinator(this.execSql).invalidateRecovery(\n input.organizationId,\n );\n }\n\n /**\n * The cursor this requester has applied, or null when it holds none. The\n * organization row's cursor is shared: another identity on this device may\n * have advanced it while this requester's own fields (for example\n * `isOrgAdmin`) still reflect an older response. Only the requester's own\n * applied cursor, while it is still the stored projection's cursor, proves\n * this requester is current. Realtime hints compare against it so a hint for\n * a cursor already applied costs no read.\n */\n async loadAppliedOrganizationReadModelCursor(input: {\n readonly organizationId: string;\n readonly requesterUserId: string;\n }): Promise<string | null> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const [row] = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ cursor: organizationReadModelRequesters.appliedCursor })\n .from(organizationReadModelRequesters)\n .innerJoin(\n organizationReadModelState,\n and(\n eq(\n organizationReadModelState.organizationId,\n organizationReadModelRequesters.organizationId,\n ),\n eq(\n organizationReadModelState.cursor,\n organizationReadModelRequesters.appliedCursor,\n ),\n ),\n )\n .where(\n and(\n eq(\n organizationReadModelRequesters.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelRequesters.userId, input.requesterUserId),\n ),\n )\n .limit(1);\n return row?.cursor ?? null;\n }\n\n /**\n * Every locally projected organization's pointer to its organization_profile\n * document, keyed by organization id.\n *\n * This is the only container-independent handle on that document. Callers\n * that need an org's display name from local state cannot rely on where the\n * document is linked: the provisioner writes it under a deterministic local\n * alias into the organization-metadata container, while a device that only\n * *synced* it (identity recovery, another member) keys it under the server\n * documentId in whichever container the grant arrived through.\n *\n * The local schema stores only the current read-model contract, so every\n * state row is eligible to provide its profile-document pointer.\n */\n async loadOrganizationProfileDocumentIds(): Promise<Map<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n organizationId: organizationReadModelState.organizationId,\n profileDocumentId: organizationReadModelState.profileDocumentId,\n })\n .from(organizationReadModelState);\n\n return new Map(\n rows.flatMap((row) =>\n row.profileDocumentId\n ? [[row.organizationId, row.profileDocumentId]]\n : [],\n ),\n );\n }\n\n async loadOrganizationGroupDisplayNames(\n organizationId: string,\n ): Promise<ReadonlyMap<string, string>> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const { db } = getClientSQLitePersistenceRuntime(this.execSql);\n const rows = await db\n .select({\n groupId: organizationReadModelGroups.groupId,\n name: organizationReadModelGroups.name,\n })\n .from(organizationReadModelGroups)\n .where(eq(organizationReadModelGroups.organizationId, organizationId));\n return new Map(\n rows\n .filter((row) => row.name.length > 0)\n .map((row) => [row.groupId, row.name]),\n );\n }\n\n /** Local display cache only: these labels never enter a server request. */\n async saveOrganizationGroupDisplayNames(input: {\n organizationId: string;\n names: readonly { groupId: string; name: string; stateHash: string }[];\n stillCurrent: () => boolean;\n }): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n await getClientSQLitePersistenceRuntime(this.execSql).guardedTransaction(\n async (tx) => {\n for (const group of input.names) {\n await tx\n .update(organizationReadModelGroups)\n .set({ name: group.name })\n .where(\n and(\n eq(\n organizationReadModelGroups.organizationId,\n input.organizationId,\n ),\n eq(organizationReadModelGroups.groupId, group.groupId),\n eq(organizationReadModelGroups.stateHash, group.stateHash),\n ),\n )\n .run();\n }\n },\n input.stillCurrent,\n );\n }\n\n /**\n * Durably record a server denial before the revoked projection rows are\n * purged. The marker is what keeps a failed purge plus an offline restart\n * from serving the revoked projection; it is cleared only when an\n * authoritative reconcile stores fresh server state for the same scope.\n */\n async recordOrganizationPresentationDenials(\n scope: OrganizationPresentationDenialScope,\n projections: readonly OrganizationPresentationDenialProjection[],\n ): Promise<void> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const deniedAt = this.now().toISOString();\n await getClientSQLitePersistenceRuntime(this.execSql).transaction(\n async (tx) => {\n for (const projection of new Set(projections)) {\n await tx\n .insert(organizationPresentationDenials)\n .values({\n organizationId: scope.organizationId,\n requesterUserId: scope.requesterUserId,\n projection,\n deniedAt,\n })\n .onConflictDoUpdate({\n target: [\n organizationPresentationDenials.organizationId,\n organizationPresentationDenials.requesterUserId,\n organizationPresentationDenials.projection,\n ],\n set: { deniedAt },\n })\n .run();\n }\n },\n );\n }\n\n async hasOrganizationPresentationDenial(\n scope: OrganizationPresentationDenialScope,\n projection: OrganizationPresentationDenialProjection,\n ): Promise<boolean> {\n await ensureSqlTables(this.execSql, organizationReadModelTables);\n const rows = await getClientSQLitePersistenceRuntime(this.execSql)\n .db.select({ projection: organizationPresentationDenials.projection })\n .from(organizationPresentationDenials)\n .where(\n and(\n eq(\n organizationPresentationDenials.organizationId,\n scope.organizationId,\n ),\n eq(\n organizationPresentationDenials.requesterUserId,\n scope.requesterUserId,\n ),\n eq(organizationPresentationDenials.projection, projection),\n ),\n )\n .limit(1);\n return rows.length > 0;\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DOCUMENTS_APP_KIND,
|
|
1
|
+
import { DOCUMENTS_APP_KIND, DocumentRecordRepository, runSerializedSqlMutation, } from "../../../../workflows/documents/index.js";
|
|
2
2
|
import { createAttachmentUploadFailedError, } from "../attachmentUpload/attachmentUploadLane.js";
|
|
3
3
|
import { isDocumentStoreSyncGenerationCurrent, } from "./syncGeneration.js";
|
|
4
4
|
export function reportAttachmentUploadFailure(input) {
|
|
@@ -14,7 +14,7 @@ export function reportAttachmentUploadFailure(input) {
|
|
|
14
14
|
if (!isDocumentStoreSyncGenerationCurrent(input.state, input.attachmentGeneration)) {
|
|
15
15
|
return;
|
|
16
16
|
}
|
|
17
|
-
await recordDocumentSyncFailure(
|
|
17
|
+
await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: input.state.localId }, {
|
|
18
18
|
attemptedAt: new Date().toISOString(),
|
|
19
19
|
message: error.message,
|
|
20
20
|
status: null,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,
|
|
1
|
+
{"version":3,"file":"attachmentUploadFailure.js","sourceRoot":"","sources":["attachmentUploadFailure.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EAExB,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAEL,iCAAiC,GAClC,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAE1B,MAAM,UAAU,6BAA6B,CAAC,KAM7C;IACC,MAAM,KAAK,GAAG,iCAAiC,CAC7C,KAAK,CAAC,iBAAiB,EACvB,KAAK,CAAC,KAAK,CACZ,CAAC;IACF,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC7B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,cAAc,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IAC5D,4EAA4E;IAC5E,sEAAsE;IACtE,yEAAyE;IACzE,yEAAyE;IACzE,kCAAkC;IAClC,KAAK,wBAAwB,CAC3B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EACjC,KAAK,EAAE,aAAa,EAAE,EAAE;QACtB,IACE,CAAC,oCAAoC,CACnC,KAAK,CAAC,KAAK,EACX,KAAK,CAAC,oBAAoB,CAC3B,EACD,CAAC;YACD,OAAO;QACT,CAAC;QACD,MAAM,IAAI,wBAAwB,CAChC,aAAa,CACd,CAAC,yBAAyB,CACzB,EAAE,OAAO,EAAE,kBAAkB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,OAAO,EAAE,EAC7D;YACE,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACrC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,MAAM,EAAE,IAAI;SACb,CACF,CAAC;IACJ,CAAC,CACF,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAC3B,CAAC","sourcesContent":["import {\n DOCUMENTS_APP_KIND,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadFailedError,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { DocumentStoreState } from \"../state\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\nexport function reportAttachmentUploadFailure(input: {\n attachmentGeneration: DocumentStoreSyncGeneration;\n error: unknown;\n pendingAttachment: PendingAttachmentRecord;\n state: DocumentStoreState;\n uploadLane: AttachmentUploadLaneReporter;\n}): void {\n const error = createAttachmentUploadFailedError(\n input.pendingAttachment,\n input.error,\n );\n input.uploadLane.fail(error);\n input.state.runtime.util.log(`Documents: ${error.message}`);\n // Surface the stuck upload in the write queue; a later successful sync pass\n // for the document clears the record. Validated inside the serialized\n // mutation: a teardown (reset/discard) racing this pass just cleared the\n // failure row, and re-recording it would resurrect a phantom queue entry\n // for work that no longer exists.\n void runSerializedSqlMutation(\n input.state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n !isDocumentStoreSyncGenerationCurrent(\n input.state,\n input.attachmentGeneration,\n )\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: input.state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: error.message,\n status: null,\n },\n );\n },\n ).catch(() => undefined);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { DOCUMENTS_APP_KIND, DocumentRecordRepository, resolveDocumentCreateAuthor, } from "../../../../workflows/documents/index.js";
|
|
2
2
|
import { createRuntimePrincipalPolicyWarmer, } from "../../../../workflows/principals/runtimePolicyWarmer.js";
|
|
3
3
|
import { markOriginatedDocuments } from "../../../../workflows/sync/index.js";
|
|
4
4
|
import { requestDocumentStoreSync } from "../../registry.js";
|
|
@@ -82,7 +82,7 @@ export async function syncPendingAttachments(state, nextRecord, encapsulationKey
|
|
|
82
82
|
// retried upload with no pending CRDT update never reaches the document
|
|
83
83
|
// submission that would otherwise clear it, and the stale row would flag the
|
|
84
84
|
// next unrelated edit as failed before it was attempted.
|
|
85
|
-
await
|
|
85
|
+
await new DocumentRecordRepository(state.runtime.infra.execSql).clearDocumentSyncFailure({
|
|
86
86
|
appKind: DOCUMENTS_APP_KIND,
|
|
87
87
|
localId: state.localId,
|
|
88
88
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,wBAAwB,EACxB,kBAAkB,EAGlB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,kCAAkC,GAEnC,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EACL,gCAAgC,EAChC,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yCAAyC,EAAE,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAEL,kCAAkC,GACnC,MAAM,0CAA0C,CAAC;AAQlD,OAAO,EAAE,6BAA6B,EAAE,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AAC,QAAQ;QAAE,OAAO,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAC9D,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IACtC,MAAM,UAAU,GAAG,kCAAkC,CAAC;QACpD,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,iBAAiB;KAClB,CAAC,CAAC;IACH,MAAM,eAAe,GAAG,+BAA+B,CAAC;QACtD,MAAM;QACN,aAAa,EAAE,KAAK;QACpB,MAAM;QACN,MAAM;QACN,cAAc,EAAE,QAAQ;QACxB,UAAU;KACX,CAAC,CAAC;IACH,OAAO,4BAA4B,CAAC;QAClC,eAAe;QACf,eAAe,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;QAC9C,aAAa,EAAE,KAAK;QACpB,UAAU;KACX,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n BlobAttachmentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n clearDocumentSyncFailure,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await clearDocumentSyncFailure(state.runtime.infra.execSql, {\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n { operation: input.pendingUpload.policyOperation },\n ),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"syncAttachments.js","sourceRoot":"","sources":["syncAttachments.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,kBAAkB,EAElB,wBAAwB,EAExB,2BAA2B,GAC5B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,kCAAkC,GAEnC,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,wBAAwB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,EACL,gCAAgC,EAChC,8BAA8B,EAC9B,6BAA6B,GAC9B,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yCAAyC,EAAE,MAAM,6CAA6C,CAAC;AACxG,OAAO,EAEL,kCAAkC,GACnC,MAAM,0CAA0C,CAAC;AAQlD,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAEL,uCAAuC,EACvC,yBAAyB,GAC1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,0BAA0B,EAC1B,8BAA8B,EAC9B,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAiB1B,SAAS,wBAAwB,CAC/B,KAAyB,EACzB,UAAuC;IAEvC,IAAI,CAAC,oCAAoC,CAAC,KAAK,EAAE,UAAU,CAAC,EAAE,CAAC;QAC7D,wBAAwB,CAAC,KAAK,CAAC,CAAC;IAClC,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAAyB,EACzB,UAA0B,EAC1B,oBAA0C,EAC1C,oBAAiD,EACjD,eAAyC;IAEzC,IAAI,KAAK,CAAC,kBAAkB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC1C,OAAO,EAAE,SAAS,EAAE,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mentService,\n BlobByteSource,\n BlobSourceSnapshot,\n} from \"../../../../workflows/blobs\";\nimport type { PreparedUploadDocumentAttachmentRequest } from \"../../../../workflows/blobs/upload\";\nimport {\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type PendingAttachmentRecord,\n resolveDocumentCreateAuthor,\n} from \"../../../../workflows/documents\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { markOriginatedDocuments } from \"../../../../workflows/sync\";\nimport { requestDocumentStoreSync } from \"../../registry\";\nimport {\n dropUnavailablePendingAttachment,\n pendingAttachmentMatchesIntent,\n resolveAttachmentSourceUpload,\n} from \"../attachmentUpload/attachmentSourceUpload\";\nimport { uploadAttachmentWithWriterProjectionRetry } from \"../attachmentUpload/attachmentUploadAttempt\";\nimport {\n type AttachmentUploadLaneReporter,\n createAttachmentUploadLaneReporter,\n} from \"../attachmentUpload/attachmentUploadLane\";\nimport type { AttachmentUploadResume } from \"../attachmentUpload/attachmentUploadResume\";\nimport type {\n DocumentAttachmentBinding,\n DocumentStoreState,\n EncapsulationKeyPair,\n PendingMutationSyncResult,\n} from \"../state\";\nimport { reportAttachmentUploadFailure } from \"./attachmentUploadFailure\";\nimport {\n type CarriedFirstUpdate,\n ensureRemoteDocumentCarryingFirstUpdate,\n uploadCarryingFirstUpdate,\n} from \"./carriedFirstUpdate\";\nimport {\n isNewPendingAttachmentSlot,\n removeSettledPendingAttachment,\n settleRecoveredAttachment,\n settleUploadedAttachment,\n} from \"./syncAttachmentSettlement\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\n\n// Preserve transient failures for retry. Drop irrecoverable missing bytes so a\n// pending attachment cannot wedge the document sync lane across restarts.\ntype PendingAttachmentUploadOutcome =\n | \"uploaded\"\n | \"recovered\"\n | \"retry\"\n | \"dropped\";\n\ninterface AttachmentSyncProgress {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n fetchedRemoteBindings: boolean;\n settledAttachment: boolean;\n uploadedAttachment: boolean;\n}\n\nfunction rearmStaleAttachmentSync(\n state: DocumentStoreState,\n generation: DocumentStoreSyncGeneration,\n): void {\n if (!isDocumentStoreSyncGenerationCurrent(state, generation)) {\n requestDocumentStoreSync(state);\n }\n}\n\nexport async function syncPendingAttachments(\n state: DocumentStoreState,\n nextRecord: DocumentRecord,\n encapsulationKeyPair: EncapsulationKeyPair,\n attachmentGeneration: DocumentStoreSyncGeneration,\n policyOperation: PrincipalPolicyOperation,\n): Promise<PendingMutationSyncResult> {\n if (state.pendingAttachments.length === 0) {\n return { completed: false, nextRecord };\n }\n\n const currentDoc = state.doc;\n if (!currentDoc) {\n return { completed: false, nextRecord };\n }\n\n let carriedFirstUpdate: CarriedFirstUpdate | undefined;\n const currentRecord = nextRecord.documentId\n ? nextRecord\n : await ensureRemoteDocumentCarryingFirstUpdate({\n currentDoc,\n encapsulationKeyPair,\n generation: attachmentGeneration,\n nextRecord,\n onCarried: (carried) => {\n carriedFirstUpdate = carried;\n },\n policyOperation,\n state,\n });\n if (!currentRecord?.documentId) {\n return { completed: false, nextRecord };\n }\n const remoteDocumentId = currentRecord.documentId;\n\n const progress: AttachmentSyncProgress = {\n activeBindingBySlotId: new Map(),\n fetchedRemoteBindings: false,\n settledAttachment: false,\n uploadedAttachment: false,\n };\n\n for (const pendingAttachment of [...state.pendingAttachments]) {\n const step = await syncNextPendingAttachment(\n {\n attachmentGeneration,\n carriedFirstUpdate,\n encapsulationKeyPair,\n pendingAttachment,\n policyOperation,\n remoteDocumentId,\n state,\n },\n progress,\n currentDoc,\n );\n // Only the first bind may carry it; a failed one leaves the row queued.\n carriedFirstUpdate = undefined;\n if (step === \"stop\") {\n return {\n completed: progress.settledAttachment,\n nextRecord: currentRecord,\n };\n }\n }\n\n if (!progress.settledAttachment) {\n return { completed: false, nextRecord: currentRecord };\n }\n\n // Only record the origination once a write landed: the server echoes a\n // document_update_created for it, and this lets the reconciler skip\n // rediscovering a delta we already have locally rather than cycling its lane\n // per uploaded file. Marking here (not before the loop) avoids a dangling id\n // that would suppress the next genuine remote update if every upload failed.\n if (progress.uploadedAttachment) {\n markOriginatedDocuments(state.runtime.state.domainScope, [\n remoteDocumentId,\n ]);\n }\n\n // A settled attachment pass invalidates any recorded failure itself: a\n // retried upload with no pending CRDT update never reaches the document\n // submission that would otherwise clear it, and the stale row would flag the\n // next unrelated edit as failed before it was attempted.\n await new DocumentRecordRepository(\n state.runtime.infra.execSql,\n ).clearDocumentSyncFailure({\n appKind: DOCUMENTS_APP_KIND,\n localId: state.localId,\n });\n\n // The snapshot was already republished progressively inside the loop as each\n // attachment settled, so there is nothing left to publish here.\n return { completed: true, nextRecord: currentRecord };\n}\n\n/** Settles one queued attachment; \"stop\" ends this pass early. */\nasync function syncNextPendingAttachment(\n upload: Omit<PendingAttachmentUploadInput, \"activeBindingBySlotId\">,\n progress: AttachmentSyncProgress,\n currentDoc: NonNullable<DocumentStoreState[\"doc\"]>,\n): Promise<\"continue\" | \"stop\"> {\n const { attachmentGeneration, pendingAttachment, state } = upload;\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n if (!(await loadRemoteAttachmentBindings({ ...upload, progress }))) {\n return \"stop\";\n }\n const outcome = await syncPendingAttachmentUpload({\n ...upload,\n activeBindingBySlotId: progress.activeBindingBySlotId,\n });\n if (outcome === \"retry\") {\n rearmStaleAttachmentSync(state, attachmentGeneration);\n return \"stop\";\n }\n // Re-check after the upload's awaits: settling writes local rows, which a\n // teardown that happened mid-upload has just deleted on purpose.\n if (!isDocumentStoreSyncGenerationCurrent(state, attachmentGeneration)) {\n requestDocumentStoreSync(state);\n return \"stop\";\n }\n removeSettledPendingAttachment(state, currentDoc, pendingAttachment);\n if (outcome === \"uploaded\" || outcome === \"recovered\") {\n progress.settledAttachment = true;\n }\n if (outcome === \"uploaded\") progress.uploadedAttachment = true;\n return \"continue\";\n}\n\nasync function loadRemoteAttachmentBindings(input: {\n pendingAttachment: PendingAttachmentRecord;\n progress: AttachmentSyncProgress;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}): Promise<boolean> {\n const { pendingAttachment, progress, state } = input;\n const freshUpload =\n pendingAttachment.upload == null &&\n isNewPendingAttachmentSlot(state, pendingAttachment);\n if (progress.fetchedRemoteBindings || freshUpload) {\n return true;\n }\n\n const remoteBindings = await state.runtime.apiClient.listDocumentAttachments(\n input.remoteDocumentId,\n );\n if (!remoteBindings) {\n return false;\n }\n\n progress.fetchedRemoteBindings = true;\n for (const binding of remoteBindings) {\n progress.activeBindingBySlotId.set(binding.slotId, binding);\n }\n return true;\n}\n\ninterface PendingAttachmentUploadInput {\n activeBindingBySlotId: Map<string, DocumentAttachmentBinding>;\n attachmentGeneration: DocumentStoreSyncGeneration;\n carriedFirstUpdate?: CarriedFirstUpdate | undefined;\n encapsulationKeyPair: EncapsulationKeyPair;\n pendingAttachment: PendingAttachmentRecord;\n policyOperation: PrincipalPolicyOperation;\n remoteDocumentId: string;\n state: DocumentStoreState;\n}\n\nasync function recoverCommittedAttachment(\n input: PendingAttachmentUploadInput,\n): Promise<boolean> {\n const { pendingAttachment, state } = input;\n const persistedUpload = pendingAttachment.upload;\n const activeBinding = input.activeBindingBySlotId.get(\n pendingAttachment.slotId,\n );\n if (!persistedUpload || activeBinding?.blobId !== persistedUpload.blobId) {\n return false;\n }\n\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: persistedUpload.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n try {\n await settleRecoveredAttachment({\n attachmentGeneration: input.attachmentGeneration,\n binding: activeBinding,\n pendingAttachment,\n remoteDocumentId: input.remoteDocumentId,\n state,\n uploadLane,\n });\n return true;\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane,\n });\n throw error;\n }\n}\n\nfunction createAttachmentBaseUploadInput(input: {\n author: PreparedUploadDocumentAttachmentRequest[\"author\"];\n pendingUpload: PendingAttachmentUploadInput;\n resume: AttachmentUploadResume;\n source: BlobByteSource;\n sourceSnapshot: BlobSourceSnapshot;\n uploadLane: AttachmentUploadLaneReporter;\n}): PreparedUploadDocumentAttachmentRequest {\n const { pendingAttachment, state } = input.pendingUpload;\n return {\n author: input.author,\n blobId: input.resume.blobId,\n bytes: input.source,\n contentKey: input.resume.contentKey,\n contentKeyEpoch: input.resume.contentKeyEpoch,\n documentId: input.pendingUpload.remoteDocumentId,\n documentSync: input.pendingUpload.carriedFirstUpdate?.request,\n expectedBindingId:\n input.pendingUpload.activeBindingBySlotId.get(pendingAttachment.slotId)\n ?.bindingId ?? null,\n nonceSeed: input.resume.nonceSeed,\n multipart: input.resume.multipart,\n onMultipartProgress: input.uploadLane.onMultipartProgress,\n onStageResolved: input.resume.onStageResolved,\n onStageUnavailable: async (stageId) => {\n await input.resume.onStageUnavailable(\n stageId,\n input.pendingUpload.remoteDocumentId,\n );\n requestDocumentStoreSync(state);\n },\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n slotId: pendingAttachment.slotId,\n sourceSnapshot: input.sourceSnapshot,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n state.runtime,\n { operation: input.pendingUpload.policyOperation },\n ),\n };\n}\n\nasync function uploadPendingAttachmentBytes(input: {\n baseUploadInput: PreparedUploadDocumentAttachmentRequest;\n /** Read from the runtime the base input was built from. */\n blobAttachments: BlobAttachmentService;\n pendingUpload: PendingAttachmentUploadInput;\n uploadLane: AttachmentUploadLaneReporter;\n}): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input.pendingUpload;\n const writerProjection =\n state.writerProjection?.documentId === input.pendingUpload.remoteDocumentId\n ? state.writerProjection\n : null;\n const writerProjectionGeneration = state.writerProjectionGeneration;\n\n try {\n const uploadAttempt = await uploadCarryingFirstUpdate({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n carried: input.pendingUpload.carriedFirstUpdate,\n committed: (attempt) => attempt.uploaded?.response.documentSync,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n upload: () =>\n uploadAttachmentWithWriterProjectionRetry({\n baseUploadInput: input.baseUploadInput,\n blobAttachments: input.blobAttachments,\n state,\n writerProjection,\n }),\n });\n const { error: uploadError, remoteSyncBlocked, uploaded } = uploadAttempt;\n if (!uploaded) {\n if (remoteSyncBlocked) {\n input.uploadLane.failIfStarted(\n new Error(\"Attachment upload paused because remote sync is blocked.\"),\n );\n return \"retry\";\n }\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error: uploadError,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n return \"retry\";\n }\n\n await settleUploadedAttachment({\n activeBindingBySlotId: input.pendingUpload.activeBindingBySlotId,\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n pendingAttachment,\n remoteDocumentId: input.pendingUpload.remoteDocumentId,\n state,\n uploadLane: input.uploadLane,\n uploaded,\n writerProjectionGeneration,\n });\n return \"uploaded\";\n } catch (error) {\n reportAttachmentUploadFailure({\n attachmentGeneration: input.pendingUpload.attachmentGeneration,\n error,\n pendingAttachment,\n state,\n uploadLane: input.uploadLane,\n });\n throw error;\n }\n}\n\nasync function syncPendingAttachmentUpload(\n input: PendingAttachmentUploadInput,\n): Promise<PendingAttachmentUploadOutcome> {\n const { pendingAttachment, state } = input;\n // The binding fetch before this call awaits; a teardown during it must not\n // let a brand-new upload start against rows that no longer exist.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!pendingAttachmentMatchesIntent(input)) {\n return dropUnavailablePendingAttachment(input);\n }\n if (await recoverCommittedAttachment(input)) {\n return \"recovered\";\n }\n\n const source = await state.runtime.infra.blobStore.openByteSource(\n pendingAttachment.storageKey,\n );\n if (!source) {\n return dropUnavailablePendingAttachment(input);\n }\n\n const author = resolveDocumentCreateAuthor(state.runtime);\n if (!author) {\n state.runtime.util.log(\n \"Documents: skipped attachment upload because the writer context is unavailable.\",\n );\n return \"retry\";\n }\n\n const prepared = await resolveAttachmentSourceUpload({\n attachmentGeneration: input.attachmentGeneration,\n pendingAttachment,\n source,\n state,\n });\n // Preparation awaited (byte-source open plus resume resolution); a teardown\n // during those awaits must not let the upload itself start — its remote\n // commit could not be recalled once sent.\n if (\n !isDocumentStoreSyncGenerationCurrent(state, input.attachmentGeneration)\n ) {\n return \"retry\";\n }\n if (!prepared) return dropUnavailablePendingAttachment(input);\n const { resume, snapshot } = prepared;\n const uploadLane = createAttachmentUploadLaneReporter({\n blobId: resume.blobId,\n domainScope: state.runtime.state.domainScope,\n pendingAttachment,\n });\n const baseUploadInput = createAttachmentBaseUploadInput({\n author,\n pendingUpload: input,\n resume,\n source,\n sourceSnapshot: snapshot,\n uploadLane,\n });\n return uploadPendingAttachmentBytes({\n baseUploadInput,\n blobAttachments: state.runtime.blobAttachments,\n pendingUpload: input,\n uploadLane,\n });\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { deriveStableDocumentId } from "../../../../data/documents/shared/stableDocumentId.js";
|
|
2
|
-
import { createRemoteDocument, DOCUMENTS_APP_KIND, describeDocumentRevalidationFailure, describeDocumentSyncSubmitFailure,
|
|
2
|
+
import { createRemoteDocument, DOCUMENTS_APP_KIND, DocumentRecordRepository, describeDocumentRevalidationFailure, describeDocumentSyncSubmitFailure, resolveDocumentCreateAuthor, runSerializedSqlMutation, } from "../../../../workflows/documents/index.js";
|
|
3
3
|
import { reportDocumentSyncQuarantine } from "../../../../workflows/documents/sync/reportDocumentSyncQuarantine.js";
|
|
4
4
|
import { createRuntimePrincipalPolicyWarmer, } from "../../../../workflows/principals/runtimePolicyWarmer.js";
|
|
5
5
|
import { chainIdentityWrite } from "../identityWriteChain.js";
|
|
@@ -68,7 +68,7 @@ function documentSyncFailureHandler(input) {
|
|
|
68
68
|
!isDocumentStoreSyncGenerationCurrent(state, generation)) {
|
|
69
69
|
return;
|
|
70
70
|
}
|
|
71
|
-
await recordDocumentSyncFailure(
|
|
71
|
+
await new DocumentRecordRepository(lockedExecSql).recordDocumentSyncFailure({ appKind: DOCUMENTS_APP_KIND, localId: state.localId }, {
|
|
72
72
|
attemptedAt: new Date().toISOString(),
|
|
73
73
|
message: input.describeFailure(failure),
|
|
74
74
|
status: failure.status,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"syncShared.js","sourceRoot":"","sources":["syncShared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oDAAoD,CAAC;AAC5F,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EAGlB,mCAAmC,EACnC,iCAAiC,EAEjC,yBAAyB,EACzB,2BAA2B,EAC3B,wBAAwB,GACzB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,4BAA4B,EAAE,MAAM,mEAAmE,CAAC;AACjH,OAAO,EACL,kCAAkC,GAEnC,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,+BAA+B,EAAE,MAAM,+BAA+B,CAAC;AAChF,OAAO,EAGL,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAEL,oCAAoC,GACrC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,6BAA6B,EAAE,MAAM,qBAAqB,CAAC;AAEpE;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAChD,KAAyB,EACzB,UAAwC;IAExC,OAAO,0BAA0B,CAAC;QAChC,eAAe,EAAE,mCAAmC;QACpD,UAAU;QACV,KAAK;QACL,iBAAiB,EAAE,IAAI;KACxB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAK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yE;QACzE,gBAAgB;QAChB,MAAM,SAAS,GAAG,MAAM,4BAA4B,CAAC;YACnD,OAAO;YACP,UAAU;YACV,UAAU;YACV,IAAI;YACJ,KAAK;SACN,CAAC,CAAC;QACH,IAAI,SAAS,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;YACtC,YAAY,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,SAAS,EAAE,MAAM,IAAI,KAAK,CAAC,MAAM,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n recordDocumentSyncFailure,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await recordDocumentSyncFailure(\n lockedExecSql,\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|
|
1
|
+
{"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M,IAAI,UAAU,CAAC;IACzD,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { deriveStableDocumentId } from \"../../../../data/documents/shared/stableDocumentId\";\nimport {\n createRemoteDocument,\n DOCUMENTS_APP_KIND,\n type DocumentRecord,\n DocumentRecordRepository,\n type DocumentSyncUpdateIsolationError,\n describeDocumentRevalidationFailure,\n describeDocumentSyncSubmitFailure,\n type PendingUpdateRecord,\n resolveDocumentCreateAuthor,\n runSerializedSqlMutation,\n} from \"../../../../workflows/documents\";\nimport { reportDocumentSyncQuarantine } from \"../../../../workflows/documents/sync/reportDocumentSyncQuarantine\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../../../workflows/principals/runtimePolicyWarmer\";\nimport { chainIdentityWrite } from \"../identityWriteChain\";\nimport {\n type DocumentState,\n type DocumentStoreState,\n type EncapsulationKeyPair,\n markDocumentStoreRemoved,\n} from \"../state\";\nimport { installDocumentWriterProjection } from \"../writerProjectionGeneration\";\nimport {\n type CreateSeed,\n type DeferredBindSeed,\n persistCreatedRemoteDocument,\n} from \"./createdDocumentPersistence\";\nimport {\n type DocumentStoreSyncGeneration,\n isDocumentStoreSyncGenerationCurrent,\n} from \"./syncGeneration\";\nimport { recordPlannedRemoteDocumentId } from \"./syncRemoteSignals\";\n\n/**\n * Record a refused read-only revalidation on this document's failure row, so\n * a document that can never refresh stops failing silently (edge-case row\n * 13). 403s stay suppressed on purpose — a read-only 403 must never flag\n * unattempted local edits (row 9) — and the row clears on the next clean\n * pass like every other sync failure.\n */\nexport function documentRevalidationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentRevalidationFailure,\n generation,\n state,\n suppressForbidden: true,\n });\n}\n\n/**\n * Record a terminal submit failure on this document's write-queue row. Shared\n * by every store pass that can submit queued writes (create and sync), so\n * re-key exhaustion and denial failures surface no matter which pass hits\n * them first.\n */\nexport function documentTerminalSubmitFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n return documentSyncFailureHandler({\n describeFailure: describeDocumentSyncSubmitFailure,\n generation,\n state,\n });\n}\n\n/** Persist quarantine and report its Error through the host's diagnostics. */\nexport function documentIncomingUpdateIsolationFailureHandler(\n state: DocumentStoreState,\n generation?: DocumentStoreSyncGeneration,\n) {\n const recordFailure = documentSyncFailureHandler({\n describeFailure: (failure) => failure.message,\n generation,\n state,\n });\n return async (failure: DocumentSyncUpdateIsolationError) => {\n await recordFailure({ message: failure.message, status: null });\n if (generation && !isDocumentStoreSyncGenerationCurrent(state, generation))\n return;\n reportDocumentSyncQuarantine(\n generation?.currentDoc ?? state.doc ?? state,\n state.runtime.util.logError,\n failure,\n );\n };\n}\n\n/**\n * The generation recheck runs INSIDE the serialized mutation (like the\n * attachment failure path): a teardown (discard/reset) that wins the ordering\n * deletes this document's rows first and invalidates the generation, so a\n * stale handler can never resurrect a deleted or orphan failure row\n * afterwards.\n */\nfunction documentSyncFailureHandler(input: {\n describeFailure: (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => string;\n generation: DocumentStoreSyncGeneration | undefined;\n state: DocumentStoreState;\n suppressForbidden?: boolean;\n}) {\n const { generation, state } = input;\n return async (failure: {\n readonly message: string;\n readonly status: number | null;\n }) => {\n if (input.suppressForbidden && failure.status === 403) {\n return;\n }\n\n await runSerializedSqlMutation(\n generation?.execSql ?? state.runtime.infra.execSql,\n async (lockedExecSql) => {\n if (\n generation &&\n !isDocumentStoreSyncGenerationCurrent(state, generation)\n ) {\n return;\n }\n await new DocumentRecordRepository(\n lockedExecSql,\n ).recordDocumentSyncFailure(\n { appKind: DOCUMENTS_APP_KIND, localId: state.localId },\n {\n attemptedAt: new Date().toISOString(),\n message: input.describeFailure(failure),\n status: failure.status,\n },\n );\n },\n );\n };\n}\n\nfunction hasPersistedRemoteDocumentSyncState(record: DocumentRecord): boolean {\n return (\n record.lastCommitLsn !== null &&\n record.contentKeyBundle !== null &&\n record.documentKekTargets !== null &&\n record.documentManifestBundle !== null\n );\n}\n\nexport function shouldSkipCleanScheduledDocumentSync(input: {\n currentRecord: DocumentRecord;\n pendingUpdates: readonly PendingUpdateRecord[];\n state: DocumentStoreState;\n}): boolean {\n return (\n input.pendingUpdates.length === 0 &&\n input.state.pendingAttachments.length === 0 &&\n input.state.pullContinuation === null &&\n !input.currentRecord.pullContinuationRecoveryRequired &&\n !input.state.remoteUpdatePending &&\n hasPersistedRemoteDocumentSyncState(input.currentRecord)\n );\n}\n\n/**\n * True when the store's container exists locally but has not been created on\n * the server yet (its own create intent is still pending). Creating a document\n * inside it would 404 on the container writer projection and surface a\n * spurious sync error; the container-contents lane re-arms document sync once\n * the container lands. An unknown or unqueryable container resolves false so\n * store-level consumers without container persistence keep creating eagerly.\n */\nexport async function isContainerAwaitingRemoteCreate(\n state: DocumentStoreState,\n): Promise<boolean> {\n const containerId = state.runtime.state.containerId;\n if (!containerId) {\n return false;\n }\n\n try {\n const rows = await state.runtime.infra.execSql(\n \"SELECT server_created_at FROM containers WHERE id = :containerId\",\n { \":containerId\": containerId },\n );\n const row = rows[0];\n return row !== undefined && Reflect.get(row, \"server_created_at\") == null;\n } catch {\n return false;\n }\n}\n\nasync function hasDurableDocumentForCreate(\n state: DocumentStoreState,\n isCurrent: () => boolean,\n): Promise<boolean> {\n // A bulk import can leave this store queued long after trash purged its\n // durable row. The persistence guard runs too late to prevent an orphaned\n // remote create, so check existence before beginning the network work.\n const record = await state.persistence.loadDocument(\n state.runtime.infra.execSql,\n state.localId,\n );\n if (!isCurrent()) return false;\n if (record) return true;\n markDocumentStoreRemoved(state);\n return false;\n}\n\nexport async function ensureRemoteDocument(\n state: DocumentStoreState,\n currentDoc: DocumentState,\n nextRecord: DocumentRecord | null,\n encapsulationKeyPair: EncapsulationKeyPair,\n policyOperation: PrincipalPolicyOperation,\n generation?: DocumentStoreSyncGeneration,\n seed?: CreateSeed,\n deferredSeed?: DeferredBindSeed,\n): Promise<DocumentRecord | null> {\n const generationIsCurrent = () =>\n !generation || isDocumentStoreSyncGenerationCurrent(state, generation);\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n if (nextRecord?.documentId) {\n return nextRecord;\n }\n\n const runtime = state.runtime;\n if (!runtime.state.containerId) {\n runtime.util.log(\n \"Documents: cannot create a remote document without a container.\",\n );\n // A local-only document with no container scope (e.g. a last-link orphan\n // from a tombstone cascade, docs/sync-edge-cases.md row 3) can never\n // create; record the stuck state durably so the write queue surfaces it\n // instead of this lane going silent on every trigger.\n await documentTerminalSubmitFailureHandler(\n state,\n generation,\n )({\n message: \"Local document has no container for its remote create\",\n status: null,\n });\n return nextRecord;\n }\n\n const author = resolveDocumentCreateAuthor(runtime);\n if (!author) {\n runtime.util.log(\n \"Documents: skipped remote create because the writer context is unavailable.\",\n );\n return nextRecord;\n }\n\n const documentId =\n nextRecord?.recoveryDocumentId ??\n (await deriveStableDocumentId(state.localId));\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n // Hints for the document can arrive before the create's response installs\n // its id; see recordPlannedRemoteDocumentId.\n recordPlannedRemoteDocumentId(state, documentId);\n\n if (!(await hasDurableDocumentForCreate(state, generationIsCurrent)))\n return state.record;\n\n const writerProjectionGeneration = state.writerProjectionGeneration;\n const created = await createRemoteDocument({\n apiClient: runtime.apiClient,\n author,\n containerId: runtime.state.containerId,\n deferredSeedUpdate: seed ? undefined : deferredSeed?.update,\n // Derive the remote id from the stable local id so a retry after a lost\n // create response re-sends the same id and adopts the existing remote\n // document instead of creating a duplicate.\n documentId,\n execSql: runtime.infra.execSql,\n isRemoteSyncBlocked: runtime.util.isRemoteSyncBlocked,\n onTerminalSubmitFailure: documentTerminalSubmitFailureHandler(\n state,\n generation,\n ),\n resolveProjectionUserKey: state.resolveProjectionUserKey,\n seedUpdate: seed?.update,\n stillCurrent: generationIsCurrent,\n targetSecretKey: encapsulationKeyPair.secretKey,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: policyOperation },\n ),\n });\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n if (!created) {\n return nextRecord;\n }\n\n return chainIdentityWrite(state, async () => {\n if (!generationIsCurrent()) return state.record ?? nextRecord;\n\n // A concurrent relink (e.g. live duplicate-facade resolution) may have\n // assigned this store a different remote identity while the create round\n // trip was in flight. That identity wins: persisting the created one here\n // would clobber the relink. The just-created remote document is left an\n // orphan, the same benign outcome as a lost create response.\n const liveDocumentId = state.record?.documentId;\n if (liveDocumentId && liveDocumentId !== created.documentId) {\n return state.record;\n }\n\n runtime.util.log(`Created document: ${created.documentId}`);\n installDocumentWriterProjection(\n state,\n created.writerProjection,\n writerProjectionGeneration,\n );\n\n // This persist is a remote-identity write (documentId + content keys), not a\n // content change. It runs after a network round trip, during which the user\n // may have kept typing into a brand-new note. The Loro doc is mutated\n // asynchronously on the write chain, so it can lag the optimistic snapshot;\n // re-deriving text/structured fields from the doc here would republish that\n // stale read over the live editor value and drop the just-typed characters\n // (the new-note \"type immediately\" race). Preserve the optimistic snapshot —\n // documentId/keys still propagate via state.record, independent of the\n // snapshot text — matching finalizeDocumentSync and the keystroke writes.\n // A committed seed settles its row in this persist, so the pass needs no\n // sync request.\n const persisted = await persistCreatedRemoteDocument({\n created,\n currentDoc,\n generation,\n seed,\n state,\n });\n if (persisted && created.deferredSeed) {\n deferredSeed?.onSigned(created.deferredSeed);\n }\n return persisted?.record ?? state.record ?? nextRecord;\n });\n}\n"]}
|