-
Notifications
You must be signed in to change notification settings - Fork 168
Feat: add Google Cloud Storage Connector #109
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { Storage } from '@smythos/sdk'; | ||
|
||
async function main() { | ||
const gcsStorage = Storage.GCS({ | ||
projectId: process.env.GCP_PROJECT_ID, | ||
clientEmail: process.env.GCP_CLIENT_EMAIL, | ||
privateKey: process.env.GCP_PRIVATE_KEY, | ||
bucket: process.env.GCP_BUCKET_NAME, | ||
}); | ||
|
||
await gcsStorage.write('test.txt', 'Hello, world!'); | ||
|
||
const data = await gcsStorage.read('test.txt'); | ||
|
||
const dataAsString = data.toString(); | ||
|
||
console.log(dataAsString); | ||
} | ||
|
||
main(); |
Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -81,3 +81,50 @@ SRE.init({ | |||||||||||||||||||||||||||||||
- Store credentials securely using environment variables or AWS Secrets Manager | ||||||||||||||||||||||||||||||||
- Configure appropriate bucket policies and CORS settings | ||||||||||||||||||||||||||||||||
- Enable encryption at rest and in transit for sensitive data | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
--- | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
### GCS | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
**Role**: Google Cloud Storage connector | ||||||||||||||||||||||||||||||||
**Summary**: Provides scalable cloud storage using Google Cloud Storage, suitable for production deployments requiring high availability and durability on Google Cloud Platform. | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
| Setting | Type | Required | Default | Description | | ||||||||||||||||||||||||||||||||
| ------------- | ------ | -------- | ------- | ----------------------------------------------- | | ||||||||||||||||||||||||||||||||
| `projectId` | string | Yes | - | Google Cloud Project ID where the bucket is located | | ||||||||||||||||||||||||||||||||
| `clientEmail` | string | Yes | - | Service account email address | | ||||||||||||||||||||||||||||||||
| `privateKey` | string | Yes | - | Service account private key | | ||||||||||||||||||||||||||||||||
| `bucket` | string | Yes | - | GCS bucket name for storing files | | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
**Example Configuration:** | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
```typescript | ||||||||||||||||||||||||||||||||
import { SRE } from '@smythos/sre'; | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
SRE.init({ | ||||||||||||||||||||||||||||||||
Storage: { | ||||||||||||||||||||||||||||||||
Connector: 'GCS', | ||||||||||||||||||||||||||||||||
Settings: { | ||||||||||||||||||||||||||||||||
projectId: 'my-project-id', | ||||||||||||||||||||||||||||||||
clientEmail: process.env.GCP_CLIENT_EMAIL, | ||||||||||||||||||||||||||||||||
privateKey: process.env.GCP_PRIVATE_KEY, | ||||||||||||||||||||||||||||||||
bucket: 'my-app-storage', | ||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||
}, | ||||||||||||||||||||||||||||||||
}); | ||||||||||||||||||||||||||||||||
``` | ||||||||||||||||||||||||||||||||
Comment on lines
+101
to
+115
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. π οΈ Refactor suggestion Private key newline gotcha (common failure in env vars) Service account keys stored in env vars often need newline restoration. Add a tip: - privateKey: process.env.GCP_PRIVATE_KEY,
+ // If stored as single-line env var, restore newlines:
+ privateKey: process.env.GCP_PRIVATE_KEY?.replace(/\\n/g, '\n'), I can update the example + add a warning callout. π Committable suggestion
Suggested change
π€ Prompt for AI Agents
|
||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
**Use Cases:** | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
- Production environments requiring scalability on Google Cloud Platform | ||||||||||||||||||||||||||||||||
- Multi-region deployments within GCP infrastructure | ||||||||||||||||||||||||||||||||
- Applications with high availability requirements | ||||||||||||||||||||||||||||||||
- Integration with Google Cloud ecosystem | ||||||||||||||||||||||||||||||||
- Large-scale data storage and processing | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
**Security Notes:** | ||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||
- Use service accounts with minimal required permissions | ||||||||||||||||||||||||||||||||
- Store credentials securely using environment variables or Google Secret Manager | ||||||||||||||||||||||||||||||||
- Configure appropriate bucket policies and IAM settings | ||||||||||||||||||||||||||||||||
- Enable encryption at rest and in transit for sensitive data |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
import { Storage, Bucket, LifecycleRule } from '@google-cloud/storage'; | ||
import { Logger } from '@sre/helpers/Log.helper'; | ||
|
||
const console = Logger('GCSCache'); | ||
|
||
export function generateLifecycleRules(): LifecycleRule[] { | ||
const rules: LifecycleRule[] = []; | ||
|
||
// Add rules for 1-100 days | ||
for (let i = 1; i < 100; i++) { | ||
rules.push({ | ||
condition: { | ||
age: i, | ||
matchesSuffix: [`ExpireAfter${i}Days`] | ||
}, | ||
action: { | ||
type: 'Delete' | ||
} | ||
}); | ||
} | ||
|
||
// Add rules for 110-1000 days with 10-day steps | ||
for (let i = 100; i < 1000; i += 10) { | ||
rules.push({ | ||
condition: { | ||
age: i, | ||
matchesSuffix: [`ExpireAfter${i}Days`] | ||
}, | ||
action: { | ||
type: 'Delete' | ||
} | ||
}); | ||
} | ||
SyedZawwarAhmed marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
// Add rules for 1000-10000 days with 100-day steps | ||
for (let i = 1000; i <= 10000; i += 100) { | ||
rules.push({ | ||
condition: { | ||
age: i, | ||
matchesSuffix: [`ExpireAfter${i}Days`] | ||
}, | ||
action: { | ||
type: 'Delete' | ||
} | ||
}); | ||
} | ||
|
||
return rules; | ||
} | ||
|
||
export function generateExpiryMetadata(expiryDays: number) { | ||
let metadataValue: string; | ||
|
||
if (expiryDays >= 1 && expiryDays < 100) { | ||
metadataValue = `ExpireAfter${expiryDays}Days`; | ||
} else if (expiryDays >= 100 && expiryDays < 1000) { | ||
const roundedUpDays = Math.ceil(expiryDays / 10) * 10; | ||
metadataValue = `ExpireAfter${roundedUpDays}Days`; | ||
} else if (expiryDays >= 1000 && expiryDays <= 10000) { | ||
const roundedUpDays = Math.ceil(expiryDays / 100) * 100; | ||
metadataValue = `ExpireAfter${roundedUpDays}Days`; | ||
} else { | ||
throw new Error('Invalid expiry days. Please provide a valid expiry days value.'); | ||
} | ||
|
||
return { | ||
Key: 'expiry-tag', | ||
Value: metadataValue, | ||
}; | ||
} | ||
SyedZawwarAhmed marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
export function getNonExistingRules(existingRules: LifecycleRule[], newRules: LifecycleRule[]): LifecycleRule[] { | ||
return newRules.filter((newRule) => | ||
!existingRules.some((existingRule) => | ||
existingRule.condition.age === newRule.condition.age && | ||
JSON.stringify(existingRule.condition.matchesSuffix) === JSON.stringify(newRule.condition.matchesSuffix) | ||
) | ||
); | ||
} | ||
|
||
export function ttlToExpiryDays(ttl: number): number { | ||
// seconds to days | ||
return Math.ceil(ttl / (60 * 60 * 24)); | ||
} | ||
|
||
export async function checkAndInstallLifecycleRules(bucketName: string, storage: Storage): Promise<void> { | ||
// Validate inputs | ||
if (!bucketName || bucketName.trim() === '') { | ||
throw new Error('Bucket name is required and cannot be empty'); | ||
} | ||
|
||
if (!storage) { | ||
throw new Error('Storage client is required'); | ||
} | ||
|
||
console.log(`Checking lifecycle rules for GCS bucket: ${bucketName}`); | ||
|
||
try { | ||
const bucket = storage.bucket(bucketName); | ||
|
||
// Check existing lifecycle configuration | ||
const [metadata] = await bucket.getMetadata(); | ||
const existingRules = metadata.lifecycle?.rule || []; | ||
|
||
const newRules = generateLifecycleRules(); | ||
const nonExistingNewRules = getNonExistingRules(existingRules, newRules); | ||
|
||
if (nonExistingNewRules.length > 0) { | ||
const allRules = [...existingRules, ...nonExistingNewRules]; | ||
|
||
await bucket.setMetadata({ | ||
lifecycle: { | ||
rule: allRules | ||
} | ||
}); | ||
|
||
console.log(`Added ${nonExistingNewRules.length} new lifecycle rules to GCS bucket: ${bucketName}`); | ||
} else { | ||
console.log('Lifecycle configuration already exists'); | ||
} | ||
} catch (error) { | ||
if (error.code === 404) { | ||
console.log('Bucket not found or no lifecycle configuration. Creating new configuration...'); | ||
|
||
const bucket = storage.bucket(bucketName); | ||
const lifecycleRules = generateLifecycleRules(); | ||
|
||
await bucket.setMetadata({ | ||
lifecycle: { | ||
rule: lifecycleRules | ||
} | ||
}); | ||
|
||
console.log('Lifecycle configuration created successfully.'); | ||
} else { | ||
console.error('Error checking lifecycle configuration:', error); | ||
console.error('Bucket name provided:', bucketName); | ||
console.error('Error details:', { | ||
name: error.name, | ||
message: error.message, | ||
code: error.code, | ||
}); | ||
} | ||
} | ||
SyedZawwarAhmed marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Env private key likely breaks without newline restoration
Most env-injected SA keys require
replace(/\\n/g, '\n')
. Without it, auth fails.Apply:
π Committable suggestion
π€ Prompt for AI Agents